Professional Documents
Culture Documents
if statement
Syntax
if test expression:
statement( s)
Here, the program evaluates the test expression and will execute statement(s)
only if the text expression is True. If the text expression is False, the statement(s) is
not executed. In Python, the body of the if statement is indicated by the indentation.
Body starts with an indentation and ends with the first unindented line. Python
interprets non-zero values as True. None and 0 are interpreted as False.
if num = = 0:
print(“ Zero”)
Output 1
Enter a number: 0
Zero
This is always printed
Output 2
Enter a number: 2
This is always printed
if test expression:
Body of if
else:
Body of else
The if.. else statement evaluates test expression and will execute body of if only
when test condition is True. If the condition is False, body of else is executed.
Indentation is used to separate the blocks.
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
The elif is short for else if. It allows us to check for multiple expressions. If the
condition for if is False, it checks the condition of the next elif block and so on. If
all the conditions are False, body of else is executed. Only one block among the
several if... elif... else blocks is executed according to the condition. Aif block can
have only one else block. But it can have multiple elif blocks.
num = int( input(“ Enter a number: “))
if num > 0:
print(“ Positive number”)
elif num = = 0:
print(“ Zero”)
else:
print(“ Negative number”)
Nested if statement
We can have a if... elif... else statement inside another if... elif... else statement.
This is called nesting in computer programming. Indentation is the only way to
identify the level of nesting.
num = int( input(“ Enter a number: “))
if num > = 0:
if num = = 0:
print(“ Zero”)
else:
print(“ Positive number”)
else:
print(“ Negative number”)
LOOPS
Python provides various control structures that allow for repeated execution. A loop
statement allows us to execute a statement or group of statements multiple times.
for loop
The for loop in Python is used to iterate over a sequence (list, tuple, string) or
other objects that can be iterated. Iterating over a sequence is called traversal.
Syntax
Here, item is the variable that takes the value of the item inside the sequence of
each iteration. The sequence can be list, tuple, string, set etc. Loop continues
until we reach the last item in the sequence. The body of for loop is separated
from the rest of the code using indentation.
Example 1
numbers = [2,4,6,8,10]
sum = 0
for item in numbers:
sum = sum + item
print(“ The sum is”, sum)
Example 2
while loop
The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is True. We generally use this loop when we don’t know the
number of times to iterate in advance.
Syntax
while test_expression:
Body of while
The body of the loop is entered only if the test_expression evaluates to True. After
one iteration, the test expression is checked again. This process is continued until
the test_expression evaluates to False. In Python, the body of the while loop is
determined through indentation. Body starts with indentation and the first un
indented line shows the end. When the condition is tested and the result is False, the
loop body will be skipped and the first statement after the while loop will be
executed.
Program
If the else statement is used with a while loop, the else statement is executed when
the condition becomes False. while loop can be terminated with a break statement.
In such case, the else part is ignored. Hence, a while loop’s else part runs if no break
occurs and the condition is False.
Output
Python Programming
Python Programming
Python Programming
Exit
End of Program
NESTED LOOPS
Sometimes we need to place a loop inside another loop. This is called nested
loop. We can have nested loops for both while and for.
Program using nested for
LIST
List is an ordered sequence of items. It is one of the most used data type in
Python and is very flexible. All the items in a list do not need to be of the same
type. Items separated by commas are enclosed within brackets [ ]. To some
extent, lists are similar to arrays in C. One difference between them is that all the
items belonging to a list can be of different data type. The values stored in a list
can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in
the beginning of the list and ending with -1. The plus (+) sign is the list
concatenation operator, and the asterisk (*) is the repetition operator.
Example
print( first_list[ 1: 3]) # Prints elements starting from 2nd till 3rd
Output
abcd
[147, 2.43]
To remove an item from a list, there are two methods. We can use del
statement or remove() method.
Example
print( list)
del list[ 2]
Output
max( list) – Returns item from the list with maximum value.
min( list) – Returns item from the list with minimum value.
Output
List: [‘ abcd’, 147, 2.43, ’Tom’]
list.append( 100)
Output
Old List before Append: [‘ abcd’, 147, 2.43, ‘Tom’]
list.count( obj) – Returns how many times the object obj appears in a list.
list.count(147)
list.index( obj) - Returns index of the object obj if found, otherwise raise an
exception indicating that value does not exist.
print( list1)
list.insert( index, obj) – Returns a list with object obj inserted at the given index.
list1. sort()
list.pop([ index]) – Removes or Returns the last object obj from a list. We can
even pop out any item in a list with the index specified.
list1. clear()
l1 = ["eat","sleep","repeat"]
obj1 = enumerate(l1)
Output
x=range(6)
for n in x:
print(n)
Syntax
Example
Create a sequence of numbers from 3 to 19, but increment by 2 instead of 1:
x= range(3, 20, 2)
for n in x:
print(n)
Tuples
Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.
index() Searches the tuple for a specified value and returns the position of
where it was found
Sets
Set is an unordered collection of unique items. Set is defined by values separated by
comma inside braces { }. It can have any number of items and they may be of
different types (integer, float, tuple, string etc.). Items in a set are not ordered. Since
they are unordered we cannot access or change an element of set using indexing or
slicing. We can perform set operations like union, intersection, difference on two
sets. Set have unique values. They eliminate duplicates. The slicing operator [] does
not work with sets. An empty set is created by the function set().
Dictionaries
Dictionary is an unordered collection of key-value pairs. It is generally used when we
have a huge amount of data. We must know the key to retrieve the value. In Python,
dictionaries are defined within braces {} with each item being a pair in the form
key:value. Key and value can be of any type. Keys are usually numbers or strings.
Values, on the other hand, can be any arbitrary Python object. Dictionaries are
sometimes found in other languages as “associative memories” or “associative
arrays”.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]).
clear()
Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist:
insert the key, with the specified value