Professional Documents
Culture Documents
Tokens
• Smallest Individual unit in a program is known as Token
• Python has following tokens:
– Keywords
– Identifiers
– Literals
– Operators
– Punctuators
Keywords
– Keywords are the words that have special meaning reserved by
programming language.
– They are reserved for special purpose and cannot be used for
normal identifier names.
– E.g. in, if, break, class, and, continue, True, False
Identifiers
– Identifiers are fundamental building block of a program.
– They are names given to variable, functions, objects classes
etc.
– Python is case sensitive i.e. it treats upper case and lower case
letter differently.
– Naming Conventions:
• Contain A-Z, a-z, _
• Name should not start with digit
• It can start with alphabet or ( _ ) underscore
Literals
– Literals are data items that have fixed value.
– Python allows several kinds of literals:
• String literals
• Numeric literals
• Boolean literals
• Special Literal None
• Literal Collections
String Literals
• The text enclosed in single or double quotes.
• There is no character literal.
• Example ‘a’, ‘anant’, “HelloWorld”
• Python allows non-graphic characters in string values.
• Non-graphic characters are represented using escape
sequence. \n for newline, \t tab space, \r carriage return
String Types in Python
• Strings are declared in two ways :
– Single-line String: enclosed within single or double quotes. It must terminate in
one line.
• Text1=“Computer”
• Text2=‘Science’
– Multiline String: text spread over multiple lines in one single string.
• It can be created in two ways
• By adding backslash at end of each line
• By enclosing the text in triple quotation mark
Size of Strings
• Size of string can be
determined by len( ) function.
• It tells the count of the
characters in the string.
• In multiline comments
backslash is not counted.
• In multiline comments with
triple quotes EOL character
at end of line is counted.
Numeric Literals
• Integer: positive negative numbers without decimal
• Floating Point: Real numbers with decimal points
• Complex Number: are in form a+bj , where a and b are floating point
numbers and j is √-1 . Where a is real part and b is imaginary part.
Boolean literals
Special Literal None
• True and False are the two Boolean Literals
• Special literal None represent absence of value
• None also indicates end of List
• They are built-in constant literals of Python
Operator
• Operators are the symbol, which triggers some computation when applied on operand.
– Unary Operator: those operators that require only one operand.
• Unary Plus +
• Unary Minus –
• Bitwise Complement ~
• Logical Negation not
– Binary Operator: those operators that require only two operand.
• Arithmetic Operator +,-,*,/,%
• Bitwise Operator &,^,|
• Shift Operator >>,<<
• Identity Operator is , is not
Relational Operators
• Less Than
<
• Greater Than >
• Less Than or Equal to <=
• Greater than or Equal to >=
• Equal To
==
• Not Equal to !=
Logical Operators
• Logical AND and
• Logical OR or
Assignment Operator
• Assignment =
• Assign Quotient /=
• Assign Sum +=
• Assign Product *=
• Assign Remainder %=
• Assign Difference -=
• Assign Exponent **=
• Assign Floor Division //=
Membership Operator
• Whether variable in sequence in
• Whether variable not in sequence not in
Punctuator
• Punctuators are the symbols used in programming language
to organise the statements of the program.
• Common Punctuators are
‘“#\()[]{}@,:.=
Barebones of Python Program
• Components of Program are
➢
Expression: legal combination of symbols to represent a value.
➢
A=5 b=b+9
➢
Statement: Instruction that performs certain action.
➢
Print(“Hello”) if(a>90):
➢
Comments: Additional information regarding the source code which is not executed.
➢
Single Line Comment: begins with #’
➢
Multiline Comments: enclosed in triple quotes(‘’’) called docstring
➢
Functions: block of code having name , and can be reused by specifying the name in the
program, whenever required.
➢
Block and Indentation: Group of statement which are part of another statement or function.
Variable and Assignments
• Named Label whose value can be changed and processed
during the program run.
• Creating Variable: Name Anant
– Name=‘Anant’ Age X 9
– Age=9
– Age=30
• Python do not have fixed memory 30
locations, when the value changes
they change their location
• lvalue: expression that can come on lhs of an assignment.
• Rvalue: expression that can come on rhs of an assignment.
Dynamic Typing
• The process in which the variable pointing to a value of certain
type, can be made to point to the value of other type.
age=10
print(age)
age=“ten”
print(age)
Dynamic Typing
p y t h o n
-6 -5 -4 -3 -2 -1
Backward Indexing
– Length of the string can be determined using len(string).
– Individual letter of a string cannot be changed because the String is immutable.
name=‘hello’
name*2+=‘g’ # Not Possible
name=‘Computer’ #Possible , we can assign string to another string
List
• List in Python represents a list of comma-separated values of any data
type between square brackets. Mutable Data Type
[1,2,3,4,5]
*‘a’, ‘b’,’c’,’d’+
*‘rat’, ‘bat’,’cat’,’dog’+
st
>>>List[0]=20 >>>print(List) [20,2,3,4,5] #changes the 1 element
th
>>>List[3]=8 >>>print(List) [20,2,3,8,5] #changes the 4 element
Tuples
• Tuples in Python represents a list of comma-separated values of
any data type between round brackets. Immutable Data Type
T=(1,2,3,4,5)
A=(‘a’, ‘b’,’c’,’d’)
B=(‘rat’, ‘bat’, ‘cat’, ’dog’)
Dictionary
• Dictionary in Python represents unordered set of comma-separated key :
value pair within { }, with the requirement that within a dictionary, no two
keys can be the same.
A=,‘a’:1, ‘b’:2,’c’:3,’d’:4-
>>>A*‘b’+
2
>>> A*‘d’+
4
Immutable Types
• The immutable types are those that can never change their value in place.
• Immutable Data Types are
– Integer
– Floating Point Number
– Boolean
– String
– Tuples
>>>a=10 >>>print(a) 10
>>>a=20 >>>print(a) 20
Note: We see that the above code is changing the value of the variable, values are not
changing in place. Variable names are stored as references to a value-object, each time
you change the value, the variable’s reference memory address changes.
Mutable Types
• Mutable types are those whose values can be changed
in place.
• Mutable Data Types are
– List
– Dictionary
– Sets
• Thus Mutability means that in the same memory address
, new value can be stored as and when you want.
Expression
• Expression is the valid combination of operators, literals and variables.
• Expression is formed by atoms and operators.
• Atoms are something which has value. E.g. Literals, identifier, string,
list, tuples, sets and dictionary etc.
• Types of Expression
– Arithmetic Expression: a+5-6
– Relational Expression: x>90
– Logical Expression: a>b or 6<p
– String Expression: “computer” + “science”, “web” *3
Evaluating Arithmetic Expression:
• During evaluation if the operand are of same data type then the resultant will be of the
data type which is common.
• Incase, during evaluation if the operand are of different data type then the resultant will
be of the data type of the largest operand. We need to promote all the operand to the
largest type through type promotion.
• Implicit Type Conversion/Coercion
– Implicit conversion is performed by the compiler without programmer’s intervention.
Note:
• Division operator will result in floating point number, even if
both operands are integer type.
Type Casting
• Python internally changes the data type of some operand , so that all
operand have same data type. This is called Implicit Type Conversion.
• Explicit Type Conversion/ Type Casting: user defined conversion that
forces an expression to be of specific type.
– Type casting is done by <datatype> (expression)
• Amt= int(amount)
• Different data types are int(), float(), complex(), str(), bool()
Types of statements in Python
• Smallest executable unit of the program.
• These are instructions given to the computer to perform any kind of action,
data movement, decision making, repeating actions etc.
• They are of three types
– Empty Statement: Statement which does nothing. In Python empty statement
is a pass statement.
– Simple Statement: Any single executable statement is a simple statement.
– Compound Statement: Group of Statement executed as a unit. It has a header
line and a body.
• Header line: It begins with the keyword and ends with a colon.
• Body: consist of one or more Python statements ,indented inside
header line. All Statement are at same level of indentation.
Program to find the Eligibility for voting
# Voting Eligibility
age=int(input("Enter your age")) //Simple Statement
pass //Empty Statement
if age>17 :
print('Eligible to vote')
else : Compound
Statement
print('Not Eligible to vote')
if Statement
• In Python, if Statement is used for decision making. It will run
the body of code only when IF statement is true.
• When you want to justify one condition while the other condition
is not true, then you use "if statement".
Syntax:
if expression
Statement
Example:
a = 33
b = 200
if b > a:
print("b is greater than a")
What happen when "if condition" does not meet
Example:
a = 33
b = 200
if b > a:
print("b is greater than a")
else:
print(“a is greater than b")
Exercise
• WAP to input a number and check whether the number is
greater than 100.
• WAP to input a number and check whether the number is
negative or positive.
• WAP to input a sales and calculate the discount on the following
criteria, if the sales is greater than 3000 then 10% discount and
less than 3000 or equal to 3000 then 5% discount.
• WAP to input three numbers and print the largest of the three.
• WAP to input a number and check whether the given number id
odd or even.
• WAP to check whether the given year is leap year or not.
WAP to check whether the given year is leap year or not.
year=int(input("Enter year:"))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print(year, "is a leap year")
else:
print(year, "is not a leap year")
else:
print(year, "is not a leap year")
else:
print(year, "is not a leap year")
How to use "elif" condition
• By using "elif" condition, you are telling the program to print out the third
condition or possibility when the other condition goes wrong or incorrect.
x,y =8,8
if(x < y):
st= "x is less than y"
elif (x == y):
st= "x is same as y"
else:
st="x is greater than y"
print(st)
Exercise
• WAP to input a number and check whether the number is greater than
100, equal to 100 or less than 100.
• WAP to input a number and check whether the number is negative, positive
or zero.
• WAP to read two numbers and an arithmetic operator and display
the computed result.
• WAP to print whether the given character is uppercase or lowercase
character or digit or any other character.
• WAP to read temperature and convert it into degree centigrade or
Fahrenheit depending on users choice.
Repetition of Tasks -- A Necessity
There are many situations when we need to repeat certain task or
functions some given number of times or based on certain condition.
What is Loop?
• Loops can execute a block of code number of times until a certain condition is
met. Their usage is fairly common in programming. Unlike other
programming language that have For Loop, while loop, do while, etc.
• To carry out repetitive task python provides following
looping/iterative statements:
– Conditional Loop while
– Counting Loop for
The range( ) Function
• The range( ) function of Python generates a list which is special
sequence type.
• Range function works in three forms:
– range( lower limit, upper limit)
range( l, u) will give l, l+1, l+2…………..u-1
range(3,7) will give 3,4,5,6
range(13,7) will give empty list
Default step value is +1
– range( lower limit, upper limit, step value)
range( l, u, s) will give l, l+s, l+2s…………..u-1
range(3,17,3) will give 3,6,9,12,15
range(13,7,2) will give 13,11,9,7
– Range(number)
range( n) will give 0,1,2…………..n-1
range(7) will give 0,1,2,3,4,5,6
Operators in and not in
• in operator tests if a given value is contained in a sequence
or not and return True or False.
The for loop
Syntax:
for <variable> in <sequence>:
statements to repeat
Example:
WAP to print natural numbers from 1 to
n, n is entered by the user.
WAP to print even numbers in the
range 1 to n, n is entered by the user.
WAP to print table of n,
where n is entered by the user.
Exercise
• WAP to print sum of n natural numbers,
where n is entered by the user
• WAP to print the factorial of the given
number, where number is entered by the user.
• WAP to input sales of the month and
calculate the average sales of that month.
The while loop
Syntax:
while <logical expression> :
loop body
Body of Loop
Update expression
WAP to print natural numbers from 1 to n,
n is entered by the user.
WAP to print even numbers in the range 1 to n,
n is entered by the user.
WAP to print table of n,
where n is entered by the user.
Loop Else Statement
• Both the loops of Python has else clause. The else of a loop
executes only when the loop end normally( i.e. only when
the loop is ending because the while loop’s test condition has
become false and for loop has executed the last sequence)