Python 2
Python 2
if <condition>:
statement(s)
Python---if-else Statements
If out of two statements, it is required to select one statement for processing on the basis
of a condition, if-else statement is to be used.
Its syntax is-
if <condition>:
statement(s) when condition is true
else:
statement(s) when condition is false
Loop/Repetitive Task/Iteration
These control structures are used for repeated execution of statement(s) on the basis of a
condition. Loop has 3 main components-
1.Start (initialization of loop)
2.Step (moving forward in loop )
3.Stop (ending of loop)
Output:
Example. 2
Output:
continue Statement
Output:
range () Function
An important function is range( ). its syntax is- range ( <lower limit>,<upper limit>)
If we write - range (0,5 )
Then a list will be created with the values [0,1,2,3,4] i.e. from lower limit to the value
one less than ending limit.
String Slicing
0 1 2 3 4 5 6 7 8 9 10 11 12 13
R E S P O N S I B I L I T Y
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
word = “RESPONSIBILITY”
word[ 0 : 14 ] will result into‘RESPONSIBILITY’
word[ 0 : 3] will result into‘RES’
word[ 2 : 5 ] will result into‘SPO’
word[ -7 : -3 ] will result into‘IBIL’
word[ : 14 ] will result into‘RESPONSIBILITY’
word[ : 5 ] will result into ‘RESPO’
word[ 3 : ] will result into ‘PONSIBILITY’
List Creation:
List is a standard data type of Python. It is a sequence which can store values of
different type.
•List is represented by square brackets “ [ ] “
For ex -
•[ ] Empty list
•[1, 2, 3] integers list
•[1, 2.5, 5.6, 9] numbers list (integer and float)
•[ ‘a’, ‘b’, ‘c’] characters list
•[‘a’, 1, ‘b’, 3.5, ‘zero’] mixed values list
•[‘one’, ’two’, ’three’] string list
Only list and dictionary are mutable data types, rest of all the data types are immutable
data types.
Creation of Tuple :
•In Python, “( )” parenthesis are used for tuple creation.
( ) empty tuple
( 1, 2, 3) integers tuple
( 1, 2.5, 3.7, 7) numbers tuple
(‘a’, ’b’, ’c’ ) characters tuple
( ‘a’, 1, ‘b’, 3.5, ‘zero’) mixed values tuple
(‘one’, ’two’, ’three’, ’four’) string tuple
*Tuple is an immutable sequence whose values can not be changed.
Dictionary Creation :
•To create a dictionary, it is needed to collect pairs of key:value in “{ }”.
•<dictionary-name>={ <key1>:<value1>,<key2>:<value2>,<key3>:<value3>. . . }
Example:
teachers={“Rajeev”:”Math”, “APA”:”Physics”,”APS”:”Chemistry:”SB”:”CS”}
Features of Dictionary
1.Unordered set: dictionary is a unordered collection of key:value pairs.
2.Not a sequence: like list, string and tuple , it is not a sequence because it is a
collection of unordered elements whereas a sequence is a collection of indexed numbers
to keep them in order.
3.Keys are used for its indexing because according to Python key can be of immutable
type. String and numbers are of immutable type and therefore can be used as a key
Adding an element in Dictionary