Beruflich Dokumente
Kultur Dokumente
Variables, Expressions
Precedence of operators
Comments
Flow of execution
MZCET A.SANGEETHA
1
PYTHON
Python is a
General-purpose
Interpreted
Powerful
High-level
Interactive
Object-oriented programming language
It was created by Guido van Rosseum
• Simple
• free and open-source
• Portability
• Extensible and Embeddable
• A high-level, interpreted language
• Large standard libraries
• Object-oriented
• Databases
• GUI Programming
APPLICATIONS OF PYTHON:
Testing : Honeywell, HP
PROBLEM SOLVING:
PROGRAMMING LANGUAGE:
• High-level language
• A programming language like Python that is designed to be easy or
humans to read and write.
• Low-level languages
• A programming language that is designed to be easy or a computer
to execute.
• Also called MACHINE LANGUAGE or ASSEMBLY LANGUAGE.
MZCET A.SANGEETHA
3
ADVANTAGES OF HIGH-LEVEL LANGUAGE:
• Easier to program.
• High-level languages are portable ie., meaning that they can run on different
kinds of computers with few or no modifications.
MZCET A.SANGEETHA
4
An Interpreter is a program that read and execute the codes line by line.
Python is an interpreted language because Python programs are executed
by an interpreter.
TWO WAYS TO USE THE INTERPRETER INTERACTIVE MODE / MODES OF
PROGRAMMING:
• Interactive mode
• Script mode
INTERACTIVE MODE
>>> 1 + 1
The chevron, >>> is the prompt the interpreter uses to indicate that it is
ready
SCRIPT MODE
• Code is stored in a file and use the interpreter to execute the contents of
the file is called a SCRIPT.
• Python scripts have names that end with .py
• To execute / run the script in Windows
• Press 5 or Goto Run menu and press Run Module
• To execute / run the script in UNIX
• Type python filename.py
• Ex. python abc.py
PROGRAM:
• A program is a sequence of instructions that specifies how to perform a
computation.
MZCET A.SANGEETHA
5
INPUT:
• Get data rom the keyboard, a file, or some other device.
OUTPUT:
• Display data on the screen or send data to a file or other device.
DEBUGGING:
BUG:
DEBUGGING:
MZCET A.SANGEETHA
6
PYTHON PROGRAM SAMPLE:
OUTPUT:
PROGRAM:
Hello World
print “Hello World”
'Hello, World!
print('Hello, World!')
VARIABLE
_a
a
a_
MZCET A.SANGEETHA
7
• Variable name may consist of letters, numbers and underscores.
password1
a12b
un_der_scores
• Names are case sensitive.
Ex., OUTPUT
print 1 1 2
x=2
print x
ASSIGNMENT STATEMENTS:
PROGRAM – SINGLE ASSIGNMENT: OUTPUT:
a = 12
a = 12 b=4
b=4
print (“a = “,a)
Print (“b = “,b)
MZCET A.SANGEETHA
8
PROGRAM – MULTIPLE ASSIGNMENT: OUTPUT:
a,b = 12,4 a = 12
print("a = ",a) b=4
print("b = ",b)
PROGRAM- SWAP 2 VALUES USING TEMPORARY VARIABLE : OUTPUT:
a = 12 a=4
b=4
b = 12
t=a
a=b
b=t
print("a = ",a)
print("b = ",b)
MZCET A.SANGEETHA
9
EXPRESSIONS
• An expression is a combination of values, variables, and operators.
ex.
Avg = a + b + c
PEMDAS
P Parenthesis
E Exponentiation
M Multiplication
D Division
A Addition
S Subtraction
RULES OF PRECEDENCE
• Parentheses have the highest precedence.
2 * (3-1) = 4
• Exponentiation has the next highest precedence
2**1+1 = 3
• Multiplication and Division have the same precedence, which is higher
than Addition and Subtraction, which also have the same precedence.
2*3-1 = 5
• Operators with the same precedence are evaluated rom left to right.
MZCET A.SANGEETHA
10
VALUE AND TYPES:
VALUE:
• A value is one of the basic things a program works with, like a letter or a
number.
• Ex.
1
'Hello, World!‘
“abc”
“good”
7.4
100.567
Var1 = 1
Var2 = 10
• Python supports 4 different numerical types
• int (signed integers)- Whole numbers without decimal point
• long (long integers, they can also be represented in octal and
hexadecimal)
• float (floating point real values)
• complex (complex numbers)
STRING:
MZCET A.SANGEETHA
12
str = 'HELLO WORLD!’
HELLO WORLD!
print(str) #print complete string
H
print(str[0]) #print first character o
string
LLO
print(str[2:5]) #print character starting
rd th
rom 3 to 5
LLO WORLD!
print(str[2:]) #print string starting rom
rd
3 character
HELLO WORLD!HELLO WORLD!
print(str*2) #print string two times
#print concatenated string HELLO WORLD! TEST
print(str + 'TEST')
Repetition operator
• Strings can be repeated with the * operator
MZCET A.SANGEETHA
13
STRING – UNPACKED:
>>> S = ab
>>> x,y = S
>>> print x
>>> print y
b
• The number of elements on both sides needs to be the same or else an error
is generated.
LISTS:
• Lists are compound data types
• A list is a sequence of data values called items or elements.
• An item can be of any type.
• A list contains items separated by commas and enclosed with square
brackets [ ]
• Each of the items in a list is ordered by position.
• Lists is similar to array in c.
• One difference between them is that all the items belonging to a list can be
of difference data types.
NESTED LIST:
Ex..
num = [1951, 1969, 1984]
# A list oƒ integers
fruits = ['apples', 'oranges', 'cherries']
# A list oƒ strings
emp = [ ]
# An empty list
MZCET A.SANGEETHA
14
newlist = [ 'spam', 2.0, 5, [10, 20] ]
• A list within another list is nested.
• A list that contains no elements is called an empty list. newlist = [ ]
>>>first=[1,2,3,4]
>>>second =list(range(1,5))
>>>first
[1,2,3,4]
>>>second
[1,2,3,4]
>>>
len operator
>>>len(first)
>>>first[0]
>>>first[2:4]
[3,4]
>>>
MZCET A.SANGEETHA
15
Slice operation in LIST:
Examples:
list = ['abcd' , '786' , 2.23 , 'john' , 70.2]
tinylist = [123 , 'john']
print(list) #print complete ['abcd' , '786' , 2.23 , 'john' , 70.2]
list
print(list[0]) #print first abcd
elements of the
list
print(list[1:3]) #print elements ['786', 2.23]
starting from 2nd
till 3rd
print(list[2:]) #print elements [2.23, 'john', 70.2]
starting From 3rd
elements
print(tinylist * 2) #print list two [123, 'john', 123, 'john']
times
print(list + tinylist) #print ['abcd', '786', 2.23, 'john', 70.2, 123,
concatenated lists 'john']
TUPLE:
abcd
(786, 2.23)
• Syntax :
• In a list, the indices have to be integers; in a dictionary they can be any type.
one = {} OUTPUT:
print(type(one))
<class 'dict'>
MZCET A.SANGEETHA
18
DICTIONARY Example
dict = {}
OUTPUT:
This is one
This is two
MZCET A.SANGEETHA
19
BOOLEAN:
Boolean expression :
• An expression whose value is either true or false.
• The built-in function bool() can be used to cast any value to a Boolean, if the
value can be interpreted as a truth value They are written as False and True,
respectively.
BOOLEAN Strings:
MZCET A.SANGEETHA
20
>>> print(my_string.isspace()) #false
a = s.islower()
Hello there
b = s.lower()
False
print(s)
print(b)
print(list1[0:1],list1[5:7])
x = colors.index('White')
print(x)
print(my_list[0].title())
MZCET A.SANGEETHA
21
Program to know the ascii number or the character
# Program to find the ASCII value o the given character
c = input("Enter a character: ")
print("The ASCII value of '" + c + "' is",ord(c))
OUTPUT:
Enter a character: T
Tuple Assignment:
>>> temp = a
>>> a = b
>>> b = temp
• In Tuple Assignment,
>>> a, b = b, a
• The left side is a tuple of variables
• The right side is a tuple of expressions.
• Each value is assigned to its respective variable.
• All the expressions on the right side are evaluated before any of the
assignments.
• The number of variables on the left and the number of values on the right
have to be the same.
MZCET A.SANGEETHA
22
COMMENTS:
# This is a comment
print('Hello')
Multiline comment
• Multiple lines can be created by repeating the number sign several times:
x=5
FUNCTION:
• A function is a block of reusable code that is used to perform a specific
action.
• Function is a group of related statements that perform a specific task.
• It is a named sequence of statements that performs a computation
• It helps the programmer to break the program into small manageable
units or modules
MZCET A.SANGEETHA
23
ADVANTAGES OF USING FUNCTIONS:
FUNCTION TYPES:
• Built-in functions
• User defined functions
Built-in functions:
• Math function
• Type conversion function
Ex.
math.sin() math.cos()
MZCET A.SANGEETHA
24
FUNCTION TYPES:
• Built-in functions
• User defined functions
Built-in functions :
MZCET A.SANGEETHA
25
MATH FUNCTIONS
cmp(x, y) -1 if x < y, 0 if x == y, or 1 if
x > y.
body of function
MZCET A.SANGEETHA
26
• Keyword def : Start of function header.
• Function name : Name of the function.
• Parameters : Arguments - pass values to a function.
They are optional.
• A colon (:) :End of function header
• The function body is any piece of Python code.
• An optional return statement to return a value from the function.
Example of a function
FUNCTION DEFINITION:
def first():
print("Hello, Good morning!")
Function Call
• To call a function, type the function name.
#function definition
def first():
print("Hello, Good morning!")
#main program
first() #function call
Example of a function
#FUNCTION DEFINITION
def add():
a = 11
b = 22
c=a+b
print(“sum =“, c)
#main program
add() #function call
MZCET A.SANGEETHA
27
RETURN STATEMENT
• The return statement is used to exit a function and go back to the place
from where it was called.
Syntax of return
Return [expression_list]
• This statement can contain expression which gets evaluated and the value
is returned.
Example of a function with return type
b=2
c=a+b
return c
#main program
sum = add() #function call
print("SUM = ",sum)
MZCET A.SANGEETHA
28
Function with no argument and no return type
Function did not take any value from the main program and it does not
return any value to main function.
Example program
def add():
a = 11
b = 22
c=a+b
print(“Sum =“, c)
#main program
add()
Function take some value from the main program and it does not return
value to main function.
def add(a,b):
c=a+b
print("sum = ",c)
#main program
x = 11
y=2
add(x, y)
Function did not take any value from the main program and it return
value to main function.
MZCET A.SANGEETHA
29
def add():
a = 11
b=2
c=a+b
return c
#main program
sum = add()
print("SUM = ",sum)
Function take some value from the main program and it return value to
main function.
def add(a,b):
c=a+b
return c
#main program
x = 11
y=2
sum = add(x,y)
print("SUM = ",sum)
MZCET A.SANGEETHA
30
FLOW OF EXECUTION:
• Statements inside the function are not executed until the function is
called.
• Instead of going to the next statement, the flow jumps to the body of the
function, executes all the statements there, and then comes back to the
next of function call statement.
PARAMETER:
MZCET A.SANGEETHA
31
• Inside the function, the arguments are assigned to variables called
parameters.
ARGUMENT:
LOCAL VARIABLE:
def print_twice(bruce):
Parameter
print bruce
print bruce
>>> print_twice('Spam')
Spam
Spam
>>> print_twice(17)
17
17
LOCAL VARIABLE:
MZCET A.SANGEETHA
32
def twice( b ):
a=5
twice(34)
OUTPUT:
Scope of variable:
Variables that are defined inside a function body have a local scope and
those defined outside have a global scope.
MZCET A.SANGEETHA
33
The local variables can be accessed only inside the function in which
they declared, whereas global variables can be accessed throughout the
program body by all functions.
When you call a function the variables declared inside it are brought into
scope.
Local variable:
When you declare variables inside a function definition they are not
related to any other variables with the same names used outside the
function i.e. variable names local to the function.
This is called scope of the variable.
All the variables have the scope of the block they are declared in starting
from the point of definition of the name.
Required Arguments
Keyword Arguments
MZCET A.SANGEETHA
35
Default Arguments
It assumes default value if a value is not provided in the function call for
that argument.
MZCET A.SANGEETHA
36
Lambda or Anonymous Functions
These are not defined like normal functions by using the keyword def.
It is defined using the keywords lambda
Syntax:
Lambda functions are used along with built-in functions like filter(), map()
etc.
Filtering:
The function is called with all the items in the list and a new list is
returned which contains items for the function evaluates True.
The function filter (function, list) offers a easy way to filter out all the
elements of a list.
The function filter (f, l) needs a function ‘f’ as its first argument. ‘f’
returns a Boolean value.
MZCET A.SANGEETHA
37
Map() Function:
The function is called with all the items in the list and a new list is
returned which contains items returned by that function and a list.
The first argument func is the name of a function and the second one seq
is a sequence.
Modules :
Create a python file with one or more functions and save it with .py
extension.
Include the import statement.
When the interpreter comes across an import statement, it imports
the module if the module is already present in the search path
A search path is a list of directories that the interpreter searches
before importing modules.
Module is loaded only once, even if multiple imports occur.
Using the module name the function is accessed using dot (.) operation
MZCET A.SANGEETHA
38
For example,
Module creation:
def add(a,b):
return a + b
import sample
c = sample.add(5,8)
print("C=",c)
MZCET A.SANGEETHA
39
Multiple functions can be imported by separating their name with
commas
For example
Built in Modules
Random
Math
Illustrative Problem:
Program:
X=10
Y= 20
print(X)
print(Y)
MZCET A.SANGEETHA
41
X,Y = Y,X
print(“After Swapping”)
print(X)
print(Y)
list1[i-1] = list1[i] 2
3
list1[i] = temp 4
5
for i in range(len(list1)):
6
print(list1[i]) 7
1
MZCET A.SANGEETHA
42
Python program to find distance between two points
def pt(x1,y1,x2,y2):
x=x2-x1
y=y2-y1
x=x**2
y=y**2
d=(x+y)**(0.5)
return d
k=pt(x1,y1,x2,y2)
OUTPUT:
MZCET A.SANGEETHA
43
Difference between Interpreter and Compiler.
Interpreter Compiler
Program Script
MZCET A.SANGEETHA
44
Python Identifiers
Rules:
Python Indentation:
MZCET A.SANGEETHA
45
In the above example, the block of statements inside the if statement
contains indentation (4 spaces)
Input Statements
Python provides two built-in function to read a line of text from standard input
device, keyboard
input()
If user enters integer input an integer will be returned, if user enters
raw_input()
It takes what user typed and passes it back as string.
For examples:
Output
MZCET A.SANGEETHA
46