0% found this document useful (0 votes)
4 views16 pages

Day 02 (Module # 2B)

This document is a guide for a Raspberry Pi course focusing on Python programming, covering fundamental concepts such as operators, control flow (if statements, while loops, for loops), and functions. It explains how to use mathematical and logical operators, control flow statements, and the structure of functions including parameters and return values. The guide includes examples and outputs to illustrate the concepts discussed.

Uploaded by

Haya
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 views16 pages

Day 02 (Module # 2B)

This document is a guide for a Raspberry Pi course focusing on Python programming, covering fundamental concepts such as operators, control flow (if statements, while loops, for loops), and functions. It explains how to use mathematical and logical operators, control flow statements, and the structure of functions including parameters and return values. The guide includes examples and outputs to illustrate the concepts discussed.

Uploaded by

Haya
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/ 16

Module # 2B Prepared by:

Python Programming M. Wasiq Pervez

RASPBERRY PI COURSE GUIDE

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2B Prepared by:
Python Programming M. Wasiq Pervez

Operators and Expressions


Most statements (logical lines) that you write will contain expressions.

A simple example of an expression is 2 + 3. An expression can be broken down into


operators and operands.

Operators are functionality that do something and can be represented by symbols


such as + or by special keywords. Operators require some data to operate on and
such data is called operands. In this case, 2 and 3 are the operands.

Mathematical operators perform basic math operations on numbers:

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2B Prepared by:
Python Programming M. Wasiq Pervez

Logical operators compare two numbers and returns one of


the Boolean values: True or False.

Compound logical operators require Boolean inputs and give a Boolean answer.

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2B Prepared by:
Python Programming M. Wasiq Pervez

Shortcut for math operation and assignment


It is common to run a math operation on a variable and then assign the result of the
operation back to the variable, hence there is a shortcut for such expressions:

a = 2
a = a * 3

can be written as:

a = 2
a *= 3

Expressions:
length = 5
breadth = 2

area = length * breadth


print('Area is', area)
print('Perimeter is', 2 * (length + breadth))

Output:
$ python expression.py
Area is 10
Perimeter is 14

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2B Prepared by:
Python Programming M. Wasiq Pervez

Control Flow
The Python interpreter executes statements in your code from the top to the bottom of
the file, in sequential order. That is unless, of course, we employ some time of control
flow statements to break this normal sequential flow.

The if statement
The if statement is used to check a condition: if the condition is true, we run a block of
statements (called the if-block), else we process another block of statements (called
the else-block). The else clause is optional.

number = 23
guess = int(input('Enter an integer : '))

if guess == number:
# New block starts here
print('Congratulations, you guessed it.')
print('(but you do not win any prizes!)')
# New block ends here
elif guess < number:
# Another block
print('No, it is a little higher than that')
# You can do whatever you want in a block ...
else:
print('No, it is a little lower than that')
# you must have guessed > number to reach here

print('Done')
# This last statement is always executed,
# after the if statement is executed.

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2B Prepared by:
Python Programming M. Wasiq Pervez

Output:
$ python if.py
Enter an integer : 50
No, it is a little lower than that
Done

$ python if.py
Enter an integer : 22
No, it is a little higher than that
Done

$ python if.py
Enter an integer : 23
Congratulations, you guessed it.
(but you do not win any prizes!)
Done

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2B Prepared by:
Python Programming M. Wasiq Pervez

The while statement


The while statement allows you to repeatedly execute a block of statements as long
as a condition is true. A while statement is an example of what is called
a looping statement. A while statement can have an optional else clause.

number = 23
running = True

while running:
guess = int(input('Enter an integer : '))

if guess == number:
print('Congratulations, you guessed it.')
# this causes the while loop to stop
running = False

elif guess < number:


print('No, it is a little higher than that.')

else:
print('No, it is a little lower than that.')

else:
print('The while loop is over.')
# Do anything else you want to do here

print('Done')

Output:
$ python while.py
Enter an integer : 50
No, it is a little lower than that.
Enter an integer : 22
No, it is a little higher than that.
Enter an integer : 23
Congratulations, you guessed it.
The while loop is over.
Done

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2B Prepared by:
Python Programming M. Wasiq Pervez

The for loop

The for..in statement is another looping statement which iterates over a sequence of
objects i.e. go through each item in a sequence. A sequence is just an ordered
collection of items.

for i in range(1, 5):


print(i)
else:
print('The for loop is over')

Output:
1
2
3
4
The for loop is over

 range() returns a sequence of numbers starting from the first number and up to
the second number. For example, range(1,5) gives the sequence [1, 2, 3, 4].

 By default, range takes a step count of 1. If we supply a third number to range,


then that becomes the step count. For example, range(1,5,2) gives [1,3].

 Remember that the range extends up to the second number i.e. it


does not include the second number.

 Note that range() generates only one number at a time, if you want the full list
of numbers, call list()on the range(), for example, list(range(5)) will result in [0,
1, 2, 3, 4]. Lists are explained in the data structure.

 The for loop then iterates over this range - for i in range(1,5) is equivalent to for
i in [1, 2, 3, 4]

 Remember that the else part is optional. When included, it is always executed
once after the for loop is over unless a break statement is encountered.

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2B Prepared by:
Python Programming M. Wasiq Pervez

The break Statement


The break statement is used to break out of a loop statement i.e. stop the execution
of a looping statement, even if the loop condition has not become False or the
sequence of items has not been completely iterated over.

An important note is that if you break out of a for or while loop, any corresponding
loop else block is not executed.

Example:

while True:
s = input('Enter something : ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')

The length of the input string can be found out using the built-in len function.

Output:
$ python break.py
Enter something : Programming is fun
Length of the string is 18
Enter something : When the work is done
Length of the string is 21
Enter something : if you wanna make your work also fun:
Length of the string is 37
Enter something : use Python!
Length of the string is 11
Enter something : quit
Done

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2B Prepared by:
Python Programming M. Wasiq Pervez

The continue Statement:

The continue statement is used to tell Python to skip the rest of the statements in the
current loop block and to continue to the next iteration of the loop.

while True:
s = input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
print('Too small')
continue
print('Input is of sufficient length')
# Do other kinds of processing here...

Output:
$ python continue.py
Enter something : a
Too small
Enter something : 12
Too small
Enter something : abc
Input is of sufficient length
Enter something : quit

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2B Prepared by:
Python Programming M. Wasiq Pervez

Functions:
Functions are reusable pieces of programs. They allow you to give a name to a block
of statements, allowing you to run that block using the specified name anywhere in
your program and any number of times. This is known as calling the function.
We have already used many built-in functions such as len() and range().
Functions are defined using the def keyword. After this keyword comes
an identifier name for the function, followed by a pair of parentheses which may
enclose some names of variables, and by the final colon that ends the line.
Next follows the block of statements that are part of this function.

def say_hello():
# block belonging to the function
print('hello world')
# End of function

say_hello() # call the function


say_hello() # call the function again

Output:
$ python function1.py
hello world
hello world

Function Parameters:
A function can take parameters, which are values you supply to the function so that
the function can do something utilising those values.

Parameters are specified within the pair of parentheses in the function definition,
separated by commas. When we call the function, we supply the values in the same
way.
Note the terminology used - the names given in the function definition are
called parameters whereas the values you supply in the function call are
called arguments.
thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2B Prepared by:
Python Programming M. Wasiq Pervez

Example:
def print_max(a, b):
if a > b:
print(a, 'is maximum')
elif a == b:
print(a, 'is equal to', b)
else:
print(b, 'is maximum')

# directly pass literal values


print_max(3, 4)

x = 5
y = 7

# pass variables as arguments


print_max(x, y)

Output:

$ python function_param.py
4 is maximum
7 is maximum

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2B Prepared by:
Python Programming M. Wasiq Pervez

Local Variables
When you declare variables inside a function definition, they are not related in any
way to other variables with the same names used outside the function - i.e. variable
names are local to the function. This is called the scope of the variable.

All variables have the scope of the block they are declared in starting from the point
of definition of the name.

Example:
x = 50

def func(x):
print('x is', x)
x = 2
print('Changed local x to', x)

func(x)
print('x is still', x)

Output:
$ python function_local.py
x is 50
Changed local x to 2
x is still 50

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2B Prepared by:
Python Programming M. Wasiq Pervez

The global statement

If you want to assign a value to a name defined at the top level of the program (i.e.
not inside any kind of scope such as functions or classes), then you have to tell
Python that the name is not local, but it is global. We do this using
the global statement. It is impossible to assign a value to a variable defined outside a
function without the global statement.

Example:
x = 50

def func():
global x

print('x is', x)
x = 2
print('Changed global x to', x)

func()
print('Value of x is', x)

Output:
$ python function_global.py
x is 50
Changed global x to 2
Value of x is 2

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2B Prepared by:
Python Programming M. Wasiq Pervez

Keyword Arguments
If you have some functions with many parameters and you want to specify only some
of them, then you can give values for such parameters by naming them - this is
called keyword arguments - we use the name (keyword) instead of the position (which
we have been using all along) to specify the arguments to the function.

There are two advantages - one, using the function is easier since we do not need to
worry about the order of the arguments. Two, we can give values to only those
parameters to which we want to, provided that the other parameters have default
argument values.
Example:

def func(a, b=5, c=10):


print('a is', a, 'and b is', b, 'and c is', c)

func(3, 7)
func(25, c=24)
func(c=50, a=100)

Output:

$ python function_keyword.py
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2B Prepared by:
Python Programming M. Wasiq Pervez

The return statement:

The return statement is used to return from a function i.e. break out of the function.
We can optionally return a value from the function as well.

Example:
def maximum(x, y):
if x > y:
return x
elif x == y:
return 'The numbers are equal'
else:
return y

print(maximum(2, 3))

Output:
$ python function_return.py
3

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]

You might also like