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

02 Conditional Statements

This document provides an overview of key Python programming concepts including control structures like if/else statements and for/while loops. It discusses operators like comparison, logical, and bitwise operators. It also covers functions, including defining functions with parameters and return values, as well as variable number of arguments. Finally, it briefly introduces list comprehensions and lambda functions.

Uploaded by

Ankur Jawa
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)
49 views

02 Conditional Statements

This document provides an overview of key Python programming concepts including control structures like if/else statements and for/while loops. It discusses operators like comparison, logical, and bitwise operators. It also covers functions, including defining functions with parameters and return values, as well as variable number of arguments. Finally, it briefly introduces list comprehensions and lambda functions.

Uploaded by

Ankur Jawa
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/ 38

CSN213: Python Programming

Control Structures (Loops and


Conditionals) and Functions
If-else control statements
• The if statement has the following general form.
if expression:
statements

• If the boolean expression evaluates to True, the


statements are executed. Otherwise, they are
skipped entirely.
• Any non-zero value is considered as True.
If-else control statements(Eg.)
a =1
b =0
c =2
if a >b:
if a >c:
print("a is greatest")
else:
print("c is greatest")
elif b >c:
print("b is greatest")
else:
print("c is greatest")
Comparison Operators
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Logical Operator
Operator Description Example
and Returns True if both x < 5 and x < 10
statements are true
or Returns True if one of the x < 5 or x < 4
statements is true
not Reverse the result, returns not(x < 5 and x < 10)
False if the result is true
Identity Operator
Operator Description Example
is Returns true if both x is y
variables are the same
object
is not Returns true if both x is not y
variables are not the same
object
Membership Operator
Operator Description Example
in Returns True if a sequence x in y
with the specified value is
present in the object
not in Returns True if a sequence x not in y
with the specified value is
not present in the object
Bitwise Operator
Operator Name Description

& AND Sets each bit to 1 if both bits are 1


| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the right and
let the leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the leftmost bit
in from the left, and let the rightmost bits fall
off
Precedence of operators
Operator Description
lambda Lambda expression
if – else Conditional expression
or Boolean OR
and Boolean AND
not x Boolean NOT
in, not in, is, is not, <, <=, >, >=, !=, == Comparisons, including membership tests and identity tests
| Bitwise OR
^ Bitwise XOR
& Bitwise AND
<<, >> Shifts
+, - Addition and subtraction
*, @, /, //, % Multiplication, matrix multiplication, division, floor division, remainder
+x, -x, ~x Positive, negative, bitwise NOT
** Exponentiation
await x Await expression
x[index], x[index:index], x(arguments...),
Subscription, slicing, call, attribute reference
x.attribute
(expressions...), [expressions...], {key: va
Binding or tuple display, list display, dictionary display, set display
lue...},{expressions...}
Conditional Expressions
• Provides compact representation for if-else:
• Syntax: [on_true] if [expression] else
[on_false]
• Eg.
>>>a,b=10,20
>>>a if a> b else b
>>>"Both a and b are equal" if a == b else "a is
greater than b" if a > b else "b is greater than a"
Range
• Range is also a sequence type
• Syntax: range(start, stop[, step])
• Eg.
>>>list(range(0,10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>list(range(5,15,3))
[5, 8, 11, 14]
>>>list(range(7))
[0, 1, 2, 3, 4, 5, 6]
>>>list(range(5, -15, -4))
[5, 1, -3, -7, -11]
For loops
• The for loop has the following general form.
• for var in sequence:
statements
• Eg.
>>>for letter in "aeiou":
>>> print "vowel: ", letter
>>> for i in [1,2,3]:
>>> print i
>>> for i in range(0,3):
>>> print i
For Loops(contd.)
• for loop can have a else clause which is executed
when loop terminates through exhaustion
• Eg.
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
print(n, 'is a prime number')
Break, Continue and Pass
• Similar to C/C++
• pass is used when semantically we want some
statement but don’t to execute anything
• Eg.
>>>a=10
>>>b=20
>>>if a>b:
>>> pass
>>>else:
>>> print(“b is greater”)
While loop
• Similar to C/C++
• Syntax: while condition:
• Will execute until the condition is True.
• Eg.
>>>a=1
>>>while a<10:
>>> print(a)
>>> a=a+1
Iterator in python
• We can create an iterator object using iter()
• Using next() on iterator variable we can iterate
over the list or any sequence
• Eg.
>>>l=[1,2,3,4]
>>>itr=iter(l)
>>>print(next(itr))
1
>>>print(next(itr))
2
Function
• Syntax: def <function_name>(<arguments>)
• Eg. some function that accepts four
arguments to connect to a remote machine
def connect(uname, pword, server, port):
print(“Connecting to", server, ":", port, "...“)
# Connecting code here ...

connect(‘admin', ‘admin123', ‘pec.ac.in', 9160)


Function (Contd.)
• Function with default value
• We can provide a default value for any number of arguments in a
function.
• Allows functions to be called with a variable number of arguments.
• Arguments with default values must appear at the end of the
arguments list!
• Eg.
def connect(uname, pword, server = 'localhost', port = 9160):
# connecting code

connect('admin', 'admin123 ')


connect('admin', 'admin123 ', ‘pec.ac.in')
connect('admin', 'admin123 ', 'pec.ac.in', 6379)
Functions (Contd.)
• Keyword arguments
connect(uname='admin', pword='admin123',
server=‘pec.ac.in', port=6379)

• If keyword arguments are used they must


follow any positional arguments, although the
relative order of keyword arguments is
unimportant.
Functions (Contd.)
1. connect('admin', 'admin123', 'pec.ac.in') --
VALID

2. connect(uname='admin', pword='admin123',
'pec.ac.in') -- INVALID

3. connect('admin', 'admin123', port=6379,


server='pec.ac.in') -- VALID
Functions (Contd.)
• Surprising Behaviour
''' Module adder.py '''
def add_item(item, item_list = []):
item_list.append(item)
print item_list

>>> from adder import *


>>> add_item(4)
[4]
>>> add_item(5)
[4, 5]
Functions (Contd.)
• Python’s default arguments are evaluated once when the
function is defined, not every time the function is called.
This means that if you make changes to a mutable default
argument, these changes will be reflected in future calls to
the function.

''' Module adder.py '''


def add_item(item, item_list = None):
if item_list == None:
item_list = []
item_list.append(item)
print item_list
Functions (Contd.)
• Parameters of the form *param contain a
variable number of positional arguments
within a tuple. Parameters of the form
**param contain a variable number of
keyword arguments.
• This is known packing
Functions (Contd.)
def connect(uname, *args, **kwargs):
print(uname )
for arg in args:
print (arg )
for key in kwargs.keys():
print (key, ":", kwargs[key] )
connect('admin', ‘admin123’, server='localhost', port=9160)
Output:
admin
admin123
port : 9160
server : localhost
Functions (Contd.)
• We can use *args and **kwargs not only to define a function, but
also to call a function. Let’s say we have the following function.
def func(arg1, arg2, arg3):
print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)

>>> args = ("one", 2, 3)


>>> func(*args)
arg1: one
arg2: 2
arg3: 3
Functions (Contd.)
>>> kwargs = {"arg3": 3, "arg1": "one", "arg2": 2}
>>> func(**kwargs)
arg1: one
arg2: 2
arg3: 3

• This is called unpacking


Lambda Functions
• One can also define lambda functions within Python.
• Use the keyword lambda instead of def.
• Can be used wherever function objects are used.
• Restricted to one expression
• Eg.
>>> def f(x):
... return x**2
...
>>> print f(8)
64
>>> g = lambda x: x**2
>>> print g(8)
64
List Comprehensions
• List comprehensions provide a nice way to
construct lists where the items are the result of
some operation.
• The simplest form of a list comprehension is
[expr for x in sequence]
• Any number of additional for and/or if
statements can follow the initial for statement. A
simple example of creating a list of squares:
>>> squares = [x**2 for x in range(0,11)]
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
List Comprehensions (Cont’d)
>>> [[x*y for x in range(1,5)] for y in range(1,6)]
[[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12], [4, 8, 12,
16],[5,10,15,20]]
Modules
• A module is a file containing Python definitions and
statements.
• The file name is the module name with the suffix .py
appended.
• Within a module, the module’s name (as a string) is
available as the value of the global variable __name__.
• If a module is executed directly however, the value of
the global variable __name__ will be “__main__”.
• Modules can contain executable statements aside from
definitions. These are executed only the first time the
module name is encountered in an import statement
as well as if the file is executed as a script.
Modules
''' Module fib.py '''
from __future__ import print_function

def even_fib(n):
total = 0
f1, f2 = 1, 2
while f1 < n:
if f1 % 2 == 0:
total = total + f1
f1, f2 = f2, f1 + f2
return total

if __name__ == "__main__":
limit = input(“Max Fibonacci number: “)
print(even_fib(int(limit)))
Modules
I can run our module directly at the command line.
In this case, the module’s __name__ variable has
the value “__main__”.

$ python fib.py
Max Fibonacci number: 4000000
4613732

$ python
>>> import fib
>>> fib.even_fib(4000000)
4613732
Mini module quiz
''' Module bar.py '''

print "Hi from bar's top level!"

def print_hello():
print "Hello from bar!"

if __name__ == "__main__":
print "bar's __name__ is __main__"
''' Module foo.py'''
import bar

print "Hi from foo's top level!"

if __name__ == "__main__":
print "foo's __name__ is __main__"
bar.print_hello()
Mini module quiz
$ python bar.py
Hi from bar's top level!
bar's __name__ is __main__

$ python foo.py
Hi from bar's top level!
Hi from foo's top level!
foo's __name__ is __main__
Hello from bar!
Mini module quiz
$ python
>>> import foo
Hi from bar's top level!
Hi from foo's top level!
>>> import bar
>>>
Random Module
• To generate random numbers
• Some functions:
– random.seed(a=None, version=2) : to seed from a
specific value, default is system time or provided by
OS. Generates float value in range [0,1).
>>> random.seed(1)
– random.randrange(stop)
random.randrange(start, stop[,step]): retunrs a
randomly selected element form the range.
>>> random.randrange(1, 100, 5)
Random Module
– random.randint(a,b): Return a random integer N such
that a <= N <= b. Alias for randrange(a, b+1)
– random.getstate(): return an object capturing the
current internal state of the generator. This object can
be passed to setstate() to restore the state
– random.setstate(): state should have been obtained
from a previous call to getstate(), and setstate()
restores the internal state of the generator to what it
was at the time getstate() was called.
– random.random(): to generate random numbers
Command line arguments
• Command line arguments are stored in
the sys module’s argv attribute as a list:

$ python command_line.py one two 3


4
['command_line.py', 'one', 'two', '3']
command_line.py

You might also like