Gulf Asian English School, Sharjah
Revision of Python
Introduction
Programming is an effective tool to develop applications that positively impact the
working of an organisation, economy and society.
Python- is a programming language developed by Guido Van Rossum in early 1990’s.
It is an open source, case sensitive, and platform independent(Cross Platform) language.
Interactive interpreter of Python is Python Shell.
Two modes of Python shell: Interactive mode (>>>) Python command prompt.
Script Mode(Python Editor)
Extension of Python file is .py or .pyw.
Function key used to execute Python program is F5.
Tokens in Python
The smallest individual unit in a program is known as a Token.
Python has the following tokens:
*Keywords
*Identifiers
*Literals
*Operators
*Punctuators
Keywords:
Keywords are reserved words with special meaning by the programming language.
It must not be used as normal identifier names.
Following are the Python keywords:
False assert del for in or while
None break elif from is pass with
True continue else global lambda raise yield
and class except if non local return
As def finally import not try
Identifiers
These are the names given to different parts of the program(for variables, objects, classes,
functions, lists, dictionaries and so on…)
Identifiers must follow the given rules:
• Identifiers must start with an alphabet(capital or small) or an underscore character(_).
• Cannot contains spaces.
• Can contain any number of letters, digits and underscore. No characters apart from these are allowed.
• Keywords cannot be used as an identifier.
• Identifiers are case sensitive( Capital letters & small letters are different).
Valid Identifiers Invalid Identifier
Data-Rec
Myfile, Date9_7_77
29abc
MYFILE, _CHK,
break
z2g0z9
My.file
Literals
Data items that have a fixed or constant value.
Example: ‘,”,\n,\t, int, float, complex, Boolean(True/False), None.
Operators
These are symbols used to perform some calculations.
Example:
*Arithmetic Operators( +, -, *, /, %, **, //)
*Assignment Operator(=)
*Relational Operator(>, <, >=, <=, ==, !=)
*Logical Operators( and, or, not)
*Membership Operator(in, not in, is, is not)
*Arithmetic Assignment Operator(+=, -=, *=, /=, %=, **=, //=)
Punctuators
Symbols used in programming languages to organise sentence structures.
Example:
‘ , “, #, (), [], {}, :, =
Variables & Assignments
It is like a containers that stores values that we can access or change.
Variable declaration is implicit in Python.
Example: x=10, name=‘Arun’
Multiple assignment in variables is possible in Python.
Example: a=b=c=10 means value of a, b,& c are 10.
Assigning multiple values to multiple variables can also be possible.
Example: x, y, z=10,20,30
Assigning single value to multiple variables is invalid in python. It gives an error.
Example : x, y, z=10 ERROR
Datatypes
Type of the data used in the programs.
type() function is used to get the type of data.
Various datatypes are:
* int : 1,2,10 *string: “abc”, “Python”
*Boolean: True, False *List: [1,2,3,4,5], [‘A’,’B’,’C’]
* float: 1.56, 2.90 *Tuples: (1,2,3,4,5), (‘A’,’B’,’C’)
* complex: 1+5j *Dictionary: {‘a’:1,’b’:2,’c’:3}
Type Casting
An explicit conversion is user-defined conversion of an operand to a specific type. This
conversion is known as Type Casting.
Ex: b=5.0
int(b) will cast data type of ‘b’ as int.
Mutable & Immutable Types
Mutability means that in the same memory address, new value can be stored as and
when you want.
Mutable types are those whose values can be changed in place.
Ex: list,dictionaries
Immutable types are those that can never change their values in place.
Ex: integers, float Booleans, strings, tuples
Comments
Statements that are ignored by the Python interpreter.
Single line comment starts with # symbol and multiple line comments starts with ‘’’
and ends with ‘’’.
Expressions
It is any valid combination of operators, literals/constants and variables.
Types of expressions:
*Arithhmetic Expressions: 2+5*3
*Logical Expressions: AND (*), OR(+)
*Relational Expressins: x>y, x==y
*String Expressions: “abc”+”def” gives “abcdef”, “abc”*2 gives “abcabc”
Expression Evaluation
Follows Order of Precedence
Table Operator Precedence
Activity
Evaluate the following expressions:
(12+3)*4-6/2
12*(3%4)//2+6
10>5 and 7>12 or not 18>3
5<20 and not 5<10
Input & Output (Built-in Functions)
To get input from user during run time, we use built-in function input().
Example: name=input(“Enter Name”)
input() always return a value of String type.
int() or float() function is used with input() to convert values received through
input() into int and float.
Example: int(input(“Enter Age:”))
print() function is used to send output to output device.
Syntax: print(object, sep=‘ ’ or <separator string>, end=‘\n’ or <end-string>)
Sep & end are optional parameters.
Example: print(“Python”, “Language”) output is Python Language
print(“Python Language”, end=‘$’)
print(“Class XII”)
Output is Python Language $Class XII
Activity
Write a program to input a number and print its cube.
Write a python program to input your name and age and display it.
Write a python program that input radius from user and find the area of a
circle. (Area of Cirlce=𝐴 = 𝜋𝑟 )
Flow of Execution
The way in which statements are executed defines the flow of execution
in a python program.
Types of Flow of Execution:
* Sequential Statements
* Selection/Conditional Statements
* Iteration/Looping Constructs
Sequential Statements
Here, statements are executed one after the other,i.e., from the first
statement till the last statement.
Conditional Constructs
For checking a particular condition
if
Syntax: if <condition>:
statements
if-else
Syntax: if <condition:
statements
else:
statements
if-elif Nested if
Syntax: if <condition>: if <condition>:
statements if<condition>:
elif <condition>: statements
statements else:
else: statements
statements else:
statements
Activity
Write a python program to input a number from user and display whether it
is negative or Zero or positive number.
Write a Python program that inputs a number between 0 and 999 from user
and print if the number is a single digit or two digits or three digits number.
Looping Constructs
Provides capability to execute a set of statements in a program repetitively, based on a
condition.
* for loops (Finite Loop)
Example: for i in “PYTHON”:
print(i) Output P
Y
T
H
O
N
range(): is used to create a list containing a sequence of numbers starting with start and ending with
one less than stop.
Example: for i in range(3,7):
print(i) Output 3
4
5
6
Nested for loops
A for loop may contain another for loop.
Example: program to print pattern *
* *
* * *
for i in range (1,4):
for j in range(1,i+1):
print(‘*’,end=‘ ’)
* While loop(Infinite Loops)
Loop will repeat instructions within itself as long as condition remains true.
Syntax: while<logical expression>:
statements
Example:
x=0 # Initialization of Looping Variable
while x<5: # Test Expression
print(x) # Body of Loop
x=x+1 # Update Looping Variable
Output 1
2
3
4
Jump Statements
break:
It terminates the loop it lies within and execution resumes at the statement
immediately after the end of that loop.
Example: for i in range(9): Output 0
if i > 3: 1
break 2
print(i) 3
continue:
Continue statements takes the control to next iteration skipping the execution of
statements for current iteration.
Example: for i in range(6): Output 0
if i == 3: 1
continue 2
print(i) 4
5
Activity
Write a python program to display the multiplication table of an inputted
number using for loop.
Write a python program to find the sum of first 10 natural numbers using while
loop.
Write a python program to display the following pattern
#
##
###
####