0% found this document useful (0 votes)
4 views

Python_Module1_Notes

Module I of the Python Programming on Raspberry PI course covers Python fundamentals including data types, operators, flow control, loop statements, and exception handling. It discusses the installation of Python and various IDEs, as well as the basics of conversing with Python through the command prompt and IDLE. Additionally, it explains concepts such as variables, expressions, statements, and the order of operations in Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python_Module1_Notes

Module I of the Python Programming on Raspberry PI course covers Python fundamentals including data types, operators, flow control, loop statements, and exception handling. It discusses the installation of Python and various IDEs, as well as the basics of conversing with Python through the command prompt and IDLE. Additionally, it explains concepts such as variables, expressions, statements, and the order of operations in Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Python Programming on Raspberry PI (22ECE136) Module I

MODULE I

Python Fundamentals
Data types
Operators
Flow Control statements
Loop statements
Exception Handling in Python

Dept of ECE, BNMIT Page 1


Python Programming on Raspberry PI (22ECE136) Module I

 Words and Sentences


 Every programming language has its own constructs to form syntax of the language.
 Basic constructs of a programming language includes set of characters and keywords that it
supports.
 The keywords have special meaning in any language and they are intended for doing specific task.
Python has a finite set of keywords as given in Table below.

Table : Keywords in Python


and as assert Break class continue
def del elif Else except False
finally for from Global if import
In is lambda None nonlocal not
Or pass raise Return True try
while with Yield

 A programmer may use variables to store the values in a program.


 Unlike many other programming languages, a variable in Python need not be declared before its
use.
 Python Editors and Installing Python
 Before getting into details of the programming language Python, it is better to learn how to install
the software.
 Python is freely downloadable from the internet. There are multiple IDEs (Integrated Development
Environment) available for working with Python. Some of them are PyCharm, LiClipse, IDLE etc.
 When you install Python, the IDLE editor will be available automatically. Apart from all these
editors, Python program can be run on command prompt also.
 One has to install suitable IDE depending on their need and the Operating System they are using.
Because, there are separate set of editors (IDE) available for different OS like Window, UNIX,Ubuntu,
Soloaris, Mac, etc. The basic Python can be downloaded from the link:
https://www.python.org/downloads/
 Python has rich set of libraries for various purposes like large-scale data processing, predictive
analytics, scientific computing etc. Based on one‟s need, the required packages can be downloaded.
But, there is a free open source distribution Anaconda, which simplifies package management and
deployment.
 Hence, it is suggested for the readers to install Anaconda from the below given link, rather than just
installing a simple Python.
https://anaconda.org/anaconda/python
 Successful installation of anaconda provides you Python in a command prompt, the default editor
IDLE and also a browser-based interactive computing environment known as jupyter notebook.

Dept of ECE, BNMIT Page 2


Python Programming on Raspberry PI (22ECE136) Module I

 Conversing with Python


 Once Python is installed, one can go ahead with working with Python.
 Use the IDE of your choice for doing programs in Python.
 After installing Python (or Anaconda distribution), if you just type „python‟ in the command
prompt, you will get the message as shown in Figure

Figure : Python initialization in command prompt


 The prompt >>> (usually called as chevron) indicates the system is ready to take Python instructions.
 If you would like to use the default IDE of Python, that is, the IDLE, then you can just run IDLE
and you will get the editor as shown in Figure.

Figure : Python IDLE editor

Dept of ECE, BNMIT Page 3


Python Programming on Raspberry PI (22ECE136) Module I

 After understanding the basics of few editors of Python, let us start our communication with Python,
by saying Hello World. The Python uses print() function for displaying the contents. Consider the
following code –

>>> print(“Hello World”) #type this and press enter key


Hello World #output displayed
>>> #prompt returns again

 Here, after typing the first line of code and pressing the enter key, we could able to get the output
of that line immediately. Then the prompt (>>>) is returned on the screen. This indicates, Python
isready to take next instruction as input for processing.

 Once we are done with the program, we can close or terminate Python by giving quit() command
asshown –
>>> quit() #Python terminates

 Terminology: Interpreter and Compiler


 All digital computers can understand only the machine language written in terms of zeros and
ones. But, for the programmer, it is difficult to code in machine language.
 Hence, we generally use high level programming languages like Java, C++, PHP, Perl, JavaScript
etc.
 Python is also one of the high level programming languages. The programs written in high level
languages are then translated to machine level instruction so as to be executed by CPU.
 How this translation behaves depending on the type of translators viz. compilers and interpreters.
 A compiler translates the source code of high-level programming language into machine level
language. For this purpose, the source code must be a complete program stored in a file (with
extension, say, .java, .c, .cpp etc). The compiler generates executable files (usually with extensions
.exe, .dll etc) that are in machine language. Later, these executable files are executed to give the
output of the program.
 On the other hand, interpreter performs the instructions directly, without requiring them to be pre-
compiled. Interpreter parses (syntactic analysis) the source code ant interprets it immediately. Hence,
every line of code can generate the output immediately, and the source code as a complete set, need
not be stored in a file. That is why, in the previous section, the usage of single line print(“Hello
World”) could able to generate the output immediately.
 Consider an example of adding two numbers –
>>> x=10
>>> y=20
>>> z= x+y
>>> print(z)

Dept of ECE, BNMIT Page 4


Python Programming on Raspberry PI (22ECE136) Module I

30
 Here, x, y and z are variables storing respective values. As each line of code above is processed
immediately after the line, the variables are storing the given values.
 Observe that, though each line is treated independently, the knowledge (or information) gained in the
previous line will be retained by Python and hence, the further lines can make use of previously used
variables.
 Thus, each line that we write at the Python prompt are logically related, though they look independent.

NOTE that, Python do not require variable declaration (unlike in C, C++, Java etc) before its use. One
can use any valid variable name for storing the values. Depending on the type (like number, string etc)
of the value being assigned, the type and behavior of the variable name is judged by Python.

VARIABLES, EXPRESSIONS AND STATEMENTS

After understanding some important concepts about programming and programming languages, we
will now move on to learn Python as a programming language with its syntax and constructs.
 Values and Types
 A value is one of the basic things a program works with.
 It may be like 2, 10.5, “Hello” etc.
 Each value in Python has a type. Type of 2 is integer; type of 10.5 is floating point number;
“Hello” is string etc.
 The type of a value can be checked using type function as shown below –
>>> type("hello")
<class 'str'>
>>> type(3)
<class 'int'>
>>> type(10.5)
<class 'float'>
>>> type("15")
<class 'str'>

 In the above four examples, one can make out various types str, int and float.
 Observe the 4th example – it clearly indicates that whatever enclosed within a double quote is a
string.

 Variable Names and Keywords

 It is a good programming practice to name the variable such that its name indicates its purpose in
the program.

Dept of ECE, BNMIT Page 5


Python Programming on Raspberry PI (22ECE136) Module I

 There are certain rules to be followed while naming a variable –


 Variable name must not be a keyword
 They can contain alphabets (lowercase and uppercase) and numbers, but should not start
with a number.
 It may contain a special character underscore(_), which is usually used to combine
variables with two words like my_salary, student_name etc. No other special characters
like @, $ etc. are allowed.
 Variable names can start with an underscore character, but we generally avoid it.
 As Python is case-sensitive, variable name sum is different from SUM, Sum etc.

 Examples:
>>> 3a=5 #starting with a number
SyntaxError: invalid syntax
>>> a$=10 #contains $
SyntaxError: invalid syntax
>>> if=15 #if is a keyword
SyntaxError: invalid syntax

 Statements
 A statement is a small unit of code that can be executed by the Python interpreter.
 It indicates some action to be carried out.
 In fact, a program is a sequence of such statements.
 Two kinds of statements are: print being an expression statement and assignment statement
 Following are the examples of statements –
>>> print("hello") #printing statement
hello
>>> x=5 #assignment statement
>>> print(x) #printing statement
5
 Operators and Operands
 Special symbols used to indicate specific tasks are called as operators.
 An operator may work on single operand (unary operator) or two operands (binary operator).
 There are several types of operators like arithmetic operators, relational operators, logical operators
etc. in Python.
 Arithmetic Operators are used to perform basic operations as listed in Table:

Dept of ECE, BNMIT Page 6


Python Programming on Raspberry PI (22ECE136) Module I

Table listing Arithmetic Operators


Operator Meaning Example
+ Addition Sum= a+b
- Subtraction Diff= a-b
* Multiplication Pro= a*b
/ Division Q = a/b
X = 5/3
(X will get a value 1.666666667)
// Floor Division – returns only F = a//b
integral part after division X= 5//3 (X will get a value 1)
% Modulus – remainder after R = a %b
division (Remainder after dividing a by b)
** Exponent E = x** y
(means x to the powder of y)
 Relational or Comparison Operators are used to check the relationship (like less than, greater than
etc) between two operands. These operators return a Boolean value – either True or False.
 Assignment Operators: Apart from simple assignment operator = which is used for assigning
values to variables, Python provides compound assignment operators.
 For example,
x=x+y can be written as x+=y
 Now, += is compound assignment operator. Similarly, one can use most of the arithmetic and bitwise
operators (only binary operators, but not unary) like *, /, %, //, &, ^ etc. as compound assignment
operators.
 For example,
>>> x=3
>>> y=5
>>> x+=y #x=x+y
>>> print(x)
8
>>> y//=2 #y=y//2
>>> print(y)
2 #only integer part will be printed

NOTE:
1. Python has a special feature – one can assign values of different types to multiple variables in
a single statement.
For example,
>>> x, y, st=3, 4.2, "Hello"
>>> print("x= ", x, " y= ",y, " st= ", st)
x=3 y=4.2 st=Hello

Dept of ECE, BNMIT Page 7


Python Programming on Raspberry PI (22ECE136) Module I

2. Python supports bitwise operators like &(AND), | (OR), ~(NOT), ^(XOR), >>(right shift) and
<<(left shift). These operators will operate on every bit of the operands. Working procedure of
these operators is same as that in other languages like C and C++.
3. There are some special operators in Python viz. Identity operator (is and is not) and
membership operator (in and not in). These will be discussed in further Modules.

 Expressions
 A combination of values, variables and operators is known as expression.
 Following are few examples of expression –
x=5
y=x+10
z= x-y*3
 The Python interpreter evaluates simple expressions and gives results even without print().
 For example,
>>> 5
5 #displayed as it is
>>> 1+2
3 #displayed the sum
 But, such expressions do not have any impact when written into Python script file.
 Order of Operations
 When an expression contains more than one operator, the evaluation of operators depends on the
precedence of operators.
 The Python operators follow the precedence rule (which can be remembered as PEMDAS) as given
below –
 Parenthesis have the highest precedence in any expression. The operations within parenthesis
will be evaluated first. For example, in the expression (a+b)*c, theaddition has to be
done first and then the sum is multiplied with c.
 Exponentiation has the 2nd precedence. But, it is right associative. That is, if there are two
exponentiation operations continuously, it will be evaluated from right to left (unlike
most of other operators which are evaluated from left to right).
For example,
>>> print(2**3) #It is 23
8
2
>>> print(2**3**2) #It is 512 i.e., 23
 Multiplication and Division are the next priority. Out of these two operations, whichever
comes first in the expression is evaluated.
>>> print(5*2/4) #multiplication and then division 2.5
>>> print(5/4*2) #division and then multiplication 2.5

Dept of ECE, BNMIT Page 8


Python Programming on Raspberry PI (22ECE136) Module I

 Addition and Subtraction are the least priority. Out of these two operations, whichever
appears first in the expression is evaluated i.e., they are evaluated from left to right

 String Operations
 String concatenation can be done using + operator as shown below –
>>> x="32"
>>> y="45"
>>> print(x+y)
3245
 Observe the output: here, the value of y (a string “45”, but not a number 45) is placed just in front
of value of x( a string “32”). Hence the result would be “3245” and its type would bestring.

NOTE: One can use single quotes to enclose a string value, instead of double quotes.

 Asking the User for Input


 Python uses the built-in function input() to read the data from the keyboard.
 When this function is invoked, the user-input is expected. The input is read till the user presses
enter- key.
 For example:
>>> str1=input()
Hello how are you? #user input
>>> print(“String is “,str1)
String is Hello how are you? #printing str1
 When input() function is used, the curser will be blinking to receive the data.
 For a better understanding, it is better to have a prompt message for the user informing what needs
to be entered as input.
 The input() function itself can be used to do so, as shown below –
>>> str1=input("Enter a string: ")
Enter a string: Hello
>>> print("You have entered: ",str1)
You have entered: Hello
 One can use new-line character \n in the function input() to make the cursor to appear in the next
line of prompt message –
>>> str1=input("Enter a string:\n")
Enter a string:
Hello #cursor is pushed here
 The key-board input received using input() function is always treated as a string type.
 If you need an integer, you need to convert it using the function int().

Dept of ECE, BNMIT Page 9


Python Programming on Raspberry PI (22ECE136) Module I

 Observe the following example –


>>> x=input("Enter x:")
Enter x:10 #x takes the value “10”, but not 10
>>> type(x) #So, type of x would be str
<class 'str'>
>>> x=int(input("Enter x:")) #use int()
Enter x:10
>>> type(x) #Now, type of x is int
<class 'int'>
 A function float() is used to convert a valid value enclosed within quotes into float number as
shown below –
>>> f=input("Enter a float value:")
Enter a float value: 3.5
>>> type(f)
<class 'str'> #f is actually a string “3.5”
>>> f=float(f) #converting “3.5” into float value 3.5
>>> type(f)
<class 'float'>
 A function chr() is used to convert an integer input into equivalent ASCII character.
>>> a=int(input("Enter an integer:"))
Enter an integer:65
>>> ch=chr(a)
>>> print("Character Equivalent of ", a, "is ",ch)
Character Equivalent of 65 is A
There are several such other utility functions in Python, which will be discussed later.
 Comments
 It is a good programming practice to add comments to the program wherever required.
 This will help someone to understand the logic of the program.
 Comment may be in a single line or spread into multiple lines.
 A single-line comment in Python starts with the symbol #.
 Multiline comments are enclosed within a pair of 3-single quotes.
 
Ex1. #This is a single-line comment

Ex2. ''' This is a


multiline
comment '''

 Python (and all programming languages) ignores the text written as comment lines.
 They are only for the programmer‟s (or any reader‟s) reference.

Dept of ECE, BNMIT Page 10


Python Programming on Raspberry PI (22ECE136) Module I

 Choosing Mnemonic Variable Names


 Choosing an appropriate name for variables in the program is always at stake.
 Consider the following examples –
Ex1.
a=10000
b=0.3*a
c=a+b
print(c) #output is 13000

Ex2.
basic=10000
da=0.3*basic
gross_sal=basic+da
print("Gross Sal = ",gross_sal) #output is 13000

 One can observe that both of these two examples are performing same task.
 But, compared to Ex1, the variables in Ex2 are indicating what is being calculated.
 That is, variable names in Ex2 are indicating the purpose for which they are being
used in the program. Such variable names are known as mnemonic variable names.
The word mnemonic means memory aid. The mnemonic variables are created to
help the programmer to remember the purpose for which they have been created.
 Python can understand the set of reserved words (or keywords), and hence it flashes
an error when such words are used as variable names by the programmer.
 Moreover, most of the Python editors have a mechanism to show keywords in a
different color. Hence, programmer can easily make out the keyword immediately
when he/she types that word.

Dept of ECE, BNMIT Page 11


Python Programming on Raspberry PI -22ECE136 Module I

Formatting the output:


There are various ways of formatting the output and displaying the variables with a required number of
space-width in Python. We will discuss few of them with the help of examples.

 Ex1: When multiple variables have to be displayed embedded within a string, the format()
function is useful as shown below –
>>> x=10
>>> y=20
>>> print("x={0}, y={1}".format(x,y))
x=10, y=20

While using format() the arguments of print() must be numbered as 0, 1, 2, 3, etc. and they must be
provided inside the format() in the same order.

 Ex2: The format() function can be used to specify the width of the variable (the number of
spaces that the variable should occupy in the output) as well. Consider below given example which
displays a number, its square and its cube.

for x in range(1,5):
print("{0:1d} {1:3d} {2:4d}".format(x,x**2, x**3))
Output:
1 1 1
2 4 8
3 9 27
4 16 64
Here, 1d, 3d and 4d indicates 1-digit space, 2-digit space etc. on the output screen.
 Ex3: One can use % symbol to have required number of spaces for a variable. This will be useful
in printing floating point numbers.
>>> x=19/3
>>> print(x)
6.333333333333333 #observe number of digits after dot
>>> print("%.3f"%(x)) #only 3 places after decimal point 6.333

>>> x=20/3
>>> y=13/7
>>> print("x= ",x, "y=",y) #observe actual digits
x=6.666666666666667 y= 1.8571428571428572
>>> print("x=%0.4f, y=%0.2f"%(x,y))
x=6.6667, y=1.86 #observe rounding off digits

Dept of ECE, BNMIT Page 12


Python Programming on Raspberry PI -22ECE136 Module I

FLOW CLONTROL STATEMENTS:

 In general, the statements in a program will be executed sequentially.


 But, sometimes we need a set of statements to be executed based on some conditions.
 Such situations are discussed in this section.

 Boolean Expressions
 A Boolean Expression is an expression which results in True or False.
 The True and False are special values that belong to class bool.
 Check the following –
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
 Boolean expression may be as below –
>>> 10==12
False
>>> x=10
>>> y=10
>>> x==y
True
 Various comparison operations are shown in Table.

Table listing Relational (Comparison) Operators


Operator Meaning Example
> Greater than a>b
< Less than a<b
>= Greater than or equal to a>=b
<= Less than or equal to a<=b
== Comparison a==b
!= Not equal to a !=b
is Is same as a is b
is not Is not same as a is not b
 Examples:
>>> a=10
>>> b=20
>>> x= a>b

Dept of ECE, BNMIT Page 13


Python Programming on Raspberry PI -22ECE136 Module I

>>> print(x)
False
>>> print(a==b)
False
>>> print("a<b is ", a<b)
a<b is True
>>> print("a!=b is", a!=b)
a!=b is True
>>> 10 is 20
False
>>> 10 is 10
True
NOTE: For a first look, the operators ==and is look same. Similarly, the operators !=and is not look the
same. But, the operators == and != does the equality test. That is, they will compare the values stored in
the variables. Whereas, the operators is and is not does the identity test. That is, they will compare whether
two objects are same. Usually, two objects are same when their memory locations are same. This concept
will be more clear when we take up classes and objects in Python.
 Logical Operators
 There are 3 logical operators in Python as shown in Table
Table listing Logical Operators
Operator Meaning Example
and Returns true, if both operands are true a and b
or Returns true, if any one of two operands is true a or b
not Return true, if the operand is false (it is a unary operator) not a
NOTE:
1. Logical operators treat the operands as Boolean (True or False).
2. Python treats any non-zero number as True and zero as False.
3. While using and operator, if the first operand is False, then the second operand is not
evaluated by Python. Because False and’ed with anything is False.
4. In case of or operator, if the first operand is True, the second operand is not evaluated.
Because True or’ed with anything is True.

Example 1 (with Boolean Operands):


>>> x= True
>>> y= False
>>> print('x and y is', x and y)
x and y is False
>>> print('x or y is', x or y)
x or y is True
>>> print('Complement of x is ', not x)
Dept of ECE, BNMIT Page 14
Python Programming on Raspberry PI -22ECE136 Module I

Complement of x is False
Example 2 (With numeric Operands):
>>> a=-3
>>> b=10
>>> print(a and b) #and operation
10 #a is true, hence b is evaluated and printed
>>> print(a or b) #or operation
-3 #a is true, hence b is not evaluated
>>> print(0 and 5) #0 is false, so printed
0

 Conditional Execution
 The basic level of conditional execution can be achieved in Python by using if statement.
 The syntax and flowcharts are as below – 

if condition:
Statement block False
condition?

 Observe the colon symbol after condition. When the True


condition which is a boolean expression is true, the
Statement block will be executed. Otherwise, it is skipped. Statement Block

 A set (block) of statements to be executed under if is Exit


decided by the indentation (tab space) given.

 Consider an example –
>>> x=10
>>> if x<40:
print("Fail") #observe indentation after if
Fail #output
 Usually, the if conditions have a statement block.
 In any case, the programmer feels to do nothing when the condition is true, the statement block can
be skipped by just typing pass statement as shown below –
>>> if x<0:
pass #do nothing when x is negative

 Alternative Execution
 A second form of if statement is alternative execution, in which there are two possibilities based on
condition evaluation.
 Here, when the condition is true, one set of statements will be executed and when the condition isfalse,
another set of statements will be executed.
Dept of ECE, BNMIT Page 15
Python Programming on Raspberry PI -22ECE136 Module I

 The syntax and flowchart are as given below -

if condition: True
Statement block -1 Condition?
else:
Statement block -2
block-1 block -2

 As the condition will be either true or false, only one


among Statement block-1 and Statement block-2 will
be get executed. These two alternatives are known as
branches.
Example:
x=int(input("Enter x:"))
if x%2==0:
print("x is even")
else:
print("x is odd")

Sample output:
Enter x: 13
x is odd
 Nested Conditionals
 The conditional statements can be nested.
 That is, one set of conditional statements can be nested inside the other.
 It can be done in multiple ways depending on programmer’s requirements.
 Examples are given below –

Ex1. marks=float(input("Enter marks:"))


if marks>=60:
if marks<70:
print("First Class")
else:
print("Distinction")
Sample Output:
Enter marks: 68
First Class
Here, the outer condition marks>=60 is checked first. If it is true, then there are two branches for the
inner conditional. If the outer condition is false, the above code does nothing.
Ex2. gender=input("Enter gender:")
Dept of ECE, BNMIT Page 16
Python Programming on Raspberry PI -22ECE136 Module I

age=int(input("Enter age:"))

if gender == "M" :
if age >= 21:
print("Boy, Eligible for Marriage")
else:
print("Boy, Not Eligible for Marriage")
elif gender == "F":
if age >= 18:
print("Girl, Eligible for Marriage")
else:
print("Girl, Not Eligible for Marriage")
Sample Output:
Enter gender: F
Enter age: 17
Girl, Not Eligible for Marriage
NOTE: Nested conditionals make the code difficult to read, even though there are proper indentations.
Hence, it is advised to use logical operators like and to simplify the nested conditionals. For example,
the outer and inner conditions in Ex1 above can be joined as -
if marks>=60 and marks<70:
#do something

 Chained Conditionals
 Some of the programs require more than one possibility to be checked for executing a set of
statements.
 That means, we may have more than one branch. This is solved with the help of chained
conditionals.
 The syntax and flowchart is given below –

Dept of ECE, BNMIT Page 17


Python Programming on Raspberry PI -22ECE136 Module I

if condition1:
Statement Block-1
elif condition2:
Statement Block-2
|
|
|
|
elif condition_n:
Statement Block-n
else:
Statement Block-(n+1)


 The conditions are checked one by one sequentially. If any condition is satisfied, the respective
statement block will be executed and further conditions are not checked. Note that, the last else block
is not necessary always.
Example: marks=float(input("Enter marks:"))
if marks >= 80:
print("First Class with Distinction")
elif marks >= 60 and marks < 80:
print("First Class")
elif marks >= 50 and marks < 60:
print("Second Class")
elif marks >= 35 and marks < 50:
print("Third Class")
else:
print("Fail")
Sample Output:
Enter marks: 78
First Class

Dept of ECE, BNMIT Page 18


Python Programming on Raspberry PI -22ECE136 Module I

ITERATION
Iteration is a processing of repeating some task. In a real time programming, we require a set of
statements to be repeated certain number of times and/or till a condition is met. Every programming
language provides certain constructs to achieve the repetition of tasks. In this section, various such
looping structures are discussed.
 The while Statement
The while loop has the syntax as below –

while condition:
statement_1
statement_2
…………….
statement_n

statements_after_while
 Here, while is a keyword, the flow of execution for a while statement is as below.
 The condition is evaluated first, yielding True or False
 If the condition is false, the loop is terminated and statements after the loop will be executed.
 If the condition is true, the body will be executed which comprises of the statement_1 to
statement_n and then goes back to condition evaluation.
 Consider an example –
n=1
while n<=5:
print(n) #observe indentation
n=n+1
print("over")
The output of above code segment would be –
1
2
3
4
5
over
 In the above example, a variable n is initialized to 1. Then the condition n<=5 is being checked. As
the condition is true, the block of code containing print statement print(n) and increment statement
(n=n+1)are executed. After these two lines, condition is checked again. The procedure continues till
condition becomes false, that is when n becomes 6. Now, the while-loop is terminated and next statement
after the loop will be executed. Thus, in this example, the loop is iterated for 5 times.
 Consider another example –
n=5
while n>0:
print(n) #observe indentation
Dept of ECE, BNMIT Page 19
Python Programming on Raspberry PI -22ECE136 Module I

n=n-1
print("Blast off!")

The output of above code segment would be –


5
4
3
2
1
Blast off!
 Iteration is referred to each time of execution of the body of loop.
 Note that, a variable n is initialized before starting the loop and it is incremented/decremented inside
the loop. Such a variable that changes its value for every iteration and controls the total execution
of the loop is called as iteration variable or counter variable. If the count variable is not updated
properly within the loop, then the loop may not terminate and keeps executing infinitely.
 Infinite Loops, break and continue
 A loop may execute infinite number of times when the condition is never going to become false.
 For example,
n=1
while True:
print(n)
n=n+1
 Here, the condition specified for the loop is the constant True, which will never get terminated.
Sometimes, the condition is given such a way that it will never become false and hence by restricting
the program control to go out of the loop. This situation may happen either due to wrong condition
or due to not updating the counter variable.
 In some situations, we deliberately want to come out of the loop even before the normal termination
of the loop. For this purpose break statement is used.
 The following example depicts the usage of break. Here, the values are taken from keyboard until a
negative number is entered. Once the input is found to be negative, the loop terminates.

while True:
x=int(input("Enter a number:"))
if x>= 0:
print("You have entered ",x)
else:
print("You have entered a negative number!!")
break #terminates the loop
Output:
Enter a umber: 23
Dept of ECE, BNMIT Page 20
Python Programming on Raspberry PI -22ECE136 Module I

You have entered 23


Enter a number:12
You have entered 12
Enter a number:45
You have entered 45
Enter a number:0
You have entered 0
Enter a number:-2
You have entered a negative number!!
 In the above example, we have used the constant True as condition for while-loop, which will never
become false. So, there was a possibility of infinite loop. This has been avoided by using break
statement with a condition.
 The condition is kept inside the loop such a way that, if the user input is a negative number, the loop
terminates. This indicates that, the loop may terminate with just one iteration (if user gives negative
number for the very first time) or it may take thousands of iteration (if user keeps on giving only
positive numbers as input). Hence, the number of iterations here is unpredictable.
 But, we are making sure that it will not be an infinite-loop, instead, the user has control on the loop.
 Another example for usage of while with break statement: the below code takes input from the user
until they type done:

while True:
line = input(">")
if line == 'done':
break
print(line)
print('Done!')
 In the above example, since the loop condition is True, so the loop runs repeatedly until it hits the
break statement.
 Each time it prompts the user to enter the data. If the user types done, the break statement exits the
loop. Otherwise the program echoes whatever the user types and goes back to the top of the loop.
 Output will be:
>hello
hello
>finished
finished
>done
Done!

Dept of ECE, BNMIT Page 21


Python Programming on Raspberry PI -22ECE136 Module I

 Sometimes, programmer would like to move to next iteration by skipping few statements in the
loop, based on some condition with current iteration. For this purpose continue statement is used.
For example, we would like to find the sum of 5 even numbers taken as input from the keyboard.
The logic is –
 Read a number from the keyboard
 If that number is odd, without doing anything else, just move to next iteration for reading
another number
 If the number is even, add it to sum and increment the accumulator variable.
 When accumulator crosses 5, stop the program
 The program for the above task can be written as –
sum=0
count=0
while True:
x=input("Enter a number:")
if x%2!=0:
continue
else:
sum+=x
count+=1
if count==5:
break
print("Sum= ", sum)
Output:
Enter a number: 23
Enter a number: 67
Enter a number: 789
Enter a number: 78
Enter a number: 5
Enter a number: 7
Sum= 891
 Example of a loop that copies its input until the user types “done”, but treats lines that start with
the hash character as lines not to be printed
while True:
line=input('>')
if line[0] == '#':
continue
Dept of ECE, BNMIT Page 22
Python Programming on Raspberry PI -22ECE136 Module I

if line =='done':
break
print(line)
print('Done!')
Output:
> hello there
hello there
> #don’t print this
> print this!
print this!
> done
Done!
 Above, all lines are printed except the one that starts with ‘#’ because when continue is executed, it
ends the current iteration and jumps back to the while statement to start the next iteration, thus
skipping the print statement.

 Definite Loops using for


 The while loop iterates till the condition is met and hence, the number of iterations are usually
unknown prior to the loop. Hence, it is sometimes called as indefinite loop.
 When we know total number of times the set of statements to be executed, for loop will be used.
This is called as a definite loop. The for-loop iterates over a set of numbers, a set of words, lines
in a file etc. The syntax of for-loop would be –
for var in list/sequence:
statement_1
statement_2
………………
statement_n

statements_after_for

Here, for and in are keywords


list/sequence is a set of elements on which the loop is iterated. That is, the loop
will be executed till there is an element in list/sequence
statements constitutes body of the loop

 Example: In the below given example, a list names containing three strings has been created. Then
the counter variable x in the for-loop iterates over this list. The variable x takes the elements in
names one by one and the body of the loop is executed.
names=["Ram", "Shyam", "Bheem"]
for x in names:
print("Happy New Year",x)
Dept of ECE, BNMIT Page 23
Python Programming on Raspberry PI -22ECE136 Module I

print('Done!')
The output would be –
Happy New Year Ram
Happy New Year Shyam
Happy New Year Bheem
Done!

NOTE: In Python, list is an important data type. It can take a sequence of elements of different types.
It can take values as a comma separated sequence enclosed within square brackets. Elements in the list
can be extracted using index (just similar to extracting array elements in C/C++ language). Various
operations like indexing, slicing, merging, addition and deletion of elements etc. can be applied on lists.
The details discussion on Lists will be done in Module 3.
 The for loop can be used to print (or extract) all the characters in a string as shown below –
for i in "Hello":
print(i, end=‟\t‟)
Output:
H e l l o
 When we have a fixed set of numbers to iterate in a for loop, we can use a function
range(). The function range() takes the following format –
range(start, end, steps)
 The start and end indicates starting and ending values in the sequence, where end is excluded in the
sequence (That is, sequence is up to end-1). The default value of start is 0. The argument steps
indicates the increment/decrement in the values of sequence with the default value as 1. Hence, the
argument steps is optional.
 Let us consider few examples on usage of range() function.

Ex1. Printing the values from 0 to 4 –


for i in range(5):
print(i, end= „\t‟)
Output:
0 1 2 3 4
Here, 0 is the default starting value. The statement range(5)is same as range(0,5) and range(0,5,1).

Ex2. Printing the values from 5 to 1 –


for i in range(5,0,-1):
print(i, end= „\t‟)
Output:
5 4 3 2 1
The function range(5,0,-1)indicates that the sequence of values are 5 to 0(excluded) in steps of -1
(downwards).
Dept of ECE, BNMIT Page 24
Python Programming on Raspberry PI -22ECE136 Module I

Ex3. Printing only even numbers less than 10 –


for i in range(0,10,2):
print(i, end= „\t‟)
Output:
0 2 4 6 8

 Loop Patterns
The while-loop and for-loop are usually used to go through a list of items or the contents of a file and
to check maximum or minimum data value. These loops are generally constructed by the following
procedure –
 Initializing one or more variables before the loop starts
 Performing some computation on each item in the loop body, possibly changing the variables
in the body of the loop
 Looking at the resulting variables when the loop completes

The construction of these loop patterns are demonstrated in the following examples.
Counting and Summing Loops: One can use the for loop for counting number of items in the list as
shown –
count = 0
for i in [4, -2, 41, 34, 25]:
count = count + 1
print(“Count:”, count)

 Here, the variable count is initialized before the loop. Though the counter variable is not being
used inside the body of the loop, it controls the number of iterations.
 The variable count is incremented in every iteration, and at the end of the loop the total number of
elements in the list is stored in it.
 One more loop similar to the above is finding the sum of elements in the list –
total = 0
for x in [4, -2, 41, 34, 25]:
total = total + x
print(“Total:”, total)
 Here, the variable total is called as accumulator because in every iteration, it accumulates the sum
of elements. In each iteration, this variable contains running total of values so far.

NOTE: In practice, both of the counting and summing loops are not necessary, because there are
built-in functions len()and sum()for the same tasks respectively.
Maximum and Minimum Loops:
To find maximum element in the list, the following code can be used –
big = None
Dept of ECE, BNMIT Page 25
Python Programming on Raspberry PI -22ECE136 Module I

print('Before Loop:', big)


for x in [12, 0, 21,-3]:
if big is None or x > big :
big = x
print('Iteration Variable:', x, 'Big:', big)
print('Biggest:', big)
Output:
Before Loop: None
Iteration Variable: 12 Big: 12
Iteration Variable: 0 Big: 12
Iteration Variable: 21 Big: 21
Iteration Variable: -3 Big: 21
Biggest: 21
 Here, we initialize the variable big to None. It is a special constant indicating empty.
 Hence, we cannot use relational operator == while comparing it with big. Instead, the is operator
must be used.
 In every iteration, the counter variable x is compared with previous value of big. If x > big, then x
is assigned to big.
 Similarly, one can have a loop for finding smallest of elements in the list as given below –
small = None
print('Before Loop:', small)
for x in [12, 0, 21,-3]:
if small is None or x < small :
small = x
print('Iteration Variable:', x, 'Small:', small)
print('Smallest:', small)
Output:
Before Loop: None
Iteration Variable: 12 Small: 12
Iteration Variable: 0 Small: 0
Iteration Variable: 21 Small: 0
Iteration Variable: -3 Small: -3
Smallest: -3

NOTE: In Python, there are built-in functions max() and min()to compute maximum and minimum
values among. Hence, the above two loops need not be written by the programmer explicitly. The
inbuilt function min()has the following code in Python –
def min(values):
smallest = None
for value in values:

Dept of ECE, BNMIT Page 26


Python Programming on Raspberry PI -22ECE136 Module I

if smallest is None or value < smallest:


smallest = value return smallest
 Catching Exceptions using try and except
 As discussed there is a chance of runtime error while doing some program.
 One of the possible reasons is wrong input.
 For example, consider the following code segment –
a=int(input("Enter a:"))
b=int(input("Enter b:"))
c=a/b
print(c)
 When you run the above code, one of the possible situations would be –
Enter a:12
Enter b:0
Traceback (most recent call last):
c=a/b
ZeroDivisionError: division by zero
 For the end-user, such type of system-generated error messages is difficult to handle.
 So the code which is prone to runtime error must be executed conditionally within try block.
 The try block contains the statements involving suspicious code and the except block contains the
possible remedy (or instructions to user informing what went wrong and what could be the way to
get out of it).
 If something goes wrong with the statements inside try block, the except block will be executed.
 Otherwise, the except-block will be skipped.
 Consider the example –
a=int(input("Enter a:"))
b=int(input("Enter b:"))
try:
c=a/b
print(c)
except:
print("Division by zero is not possible")
Output:
Enter a:12
Enter b:0
Division by zero is not possible
 Handling an exception using try is called as catching an exception.
 In general, catching an exception gives the programmer to fix the probable problem, or to try again
or at least to end the program gracefully.
**** ****

Dept of ECE, BNMIT Page 27

You might also like