You are on page 1of 37

Control Structures

The if statement
• The simple if statement allows the program to branch based on the
evaluation of an expression
• The basic format of the if statement is:
The while loop
• A “while-loop” allows you to repeat a block of code until a
condition is no longer true:
while <condition>:
block of code
For loop
• The for loop, like the while loop repeatedly executes a set of
statements. The difference is that in the for loop we know in at
the outset how often the statements in the loop will be
executed.
• The basic format of the for statement is
for variable_name in some_sequence :
statement1
statement2
...
statementn
Exercise
1. Write a program in python to check whether the entered year is a
leap year or not.
2. Write a program in python to check the person age and accordingly
show him the price of train ticket that fit his age.
• #children until 18 years ticket = 20
• #old people bigger than or equal 60 years ticket = 50
• #young people from 18 - 59 year ticket = 100
3. Write a program to display numbers from 1 to 10
4. Write a program to find the number of character ‘a’ in the letter
‘banana’.(change the indentation and check the answer)
How to read data from the user
• To prompt the user to enter the values we make use of input()
method.
• For Example: Write a program to enter a name and age, converts the
age into an integer, and then displays the data.

In [10]:name = input("Enter your name ")


age = int (input("Enter your age "))
print ("\nName =", name);
print ("\nAge =", age)
Declaring variables and assigning values
• Python allows you to assign a value to multiple variables in a single
statement, which is also known as multiple assigns. You can assign a
single value to multiple variables or assign multiple values to multiple
variables.
• For Example:
age= marks = score =25 age, mark, code=10,75,"CIS2403"
print (age) print (age)
print (marks) print (mark)
print (score) print (code)
Functions in Jupyter
• A function is a block of organized, reusable code that can make
your scripts more effective, easier to read, and simple to manage
• For Example: converting temperatures from Fahrenheit to
Celsius.
Cont…

• The function definition opens with the keyword def followed by the
name of the function and a list of parameter names in parentheses.
The body of the function — the statements that are executed when it
runs — is indented below the definition line.

• When we call the function, the values we pass to it are assigned to


the corresponding parameter variables so that we can use them
inside the function (e.g., the variable temp in this function example).
Inside the function, we use a return statement to define the value
that should be given back when the function is used or called.
Calling functions
• Calling our self-defined function is no different from calling any other
function such as print().
• You need to call it with its name and send your value to the required

def celsius_to_fahr(temp):
return 9/5 * temp + 32
freezing_point = celsius_to_fahr(0)
print(freezing_point)

Q. Write a function to check whether the given number is even or odd


Positional and keyword arguments
• A Python function can accept an arbitrary number of
arguments, called positional arguments. It can also accept
optional named arguments, called keyword arguments.
• For example:
def remainder(number, divisor=2):
return number % divisor
• The second argument of this function, divisor, is optional. If it
is not provided by the caller, it will default to the number 2
Cont…
• There are two equivalent ways of specifying a keyword argument when
calling a function. They are as follows:

remainder(5, 3)
Output: 2

remainder(5, divisor=3)
Output: 2

• In the first case, 3 is understood as the second argument, divisor. In the


second case, the name of the argument is given explicitly by the caller. This
second syntax is clearer and less error-prone than the first one.
Example 2:
• Define a function to return salary after discount tax of 5%
• Consider a list of data as follows:

Staff_Salary = { 'Rajesh' : 30000 , 'Alia' : 24000, 'Amar': 25000,


'Majid’ : 10000}

Ans: ln:29
Example 3:
• Create a new function called hello with 2 parameters
• Parameter 1 should be called name and you should assign some text to this
parameter this when using the function
• Parameter 2 should be called age and you should provide a number value for this
parameter when using the function

• When using the function, the value that is returned should be a character
string stating the name and age that were provided, which you can assign
to a variable called output. Printing out output should produce something
like the following:

print(output)
'Hello, my name is Dave. I am 39 years old.'
Anonymous Functions – Lambda
• A lambda function is a small function containing a single
expression.
• Lambda functions can also act as anonymous functions where
they don’t require any name.
• These are very helpful when we have to perform small tasks
with less code.
• We can also use lambda functions when we have to pass a small
function to another function.
• The lambda's general form is :
lambda arg1, arg2, ...argN : expression using arguments
Cont…
• We can also use lambda functions when we have to pass a small
function to another function.
• In Python, lambda functions have the following syntax:
• Lambda functions consist of three parts:
• Keyword
• Bound variable/argument, and
• Body or expression
• The keyword is mandatory, and it must be a lambda, whereas
the arguments and body can change based on the requirements.
Comparing Lambda with Regular function

Lambda functions are defined using the keyword lambda. They can have
any number of arguments but only one expression. A lambda function
cannot contain any statements, and it returns a function object which
can be assigned to any variable. They are generally used for one-line
expressions.

Regular functions are created using the def keyword. They can have any
number of arguments and any number of expressions. They can contain
any statements and are generally used for large blocks of code.
Example
• (lambda x: x*x*x)(10)

• f = lambda x, y, z: x + y + z
f(2, 30, 400)

• l_func = lambda x: x**2


print (l_func(4))

• mz = (lambda a = 'Database', b = ' Management', c = ' System': a + b + c)


mz('Relational',' Database')
Modules in Python
• Modules provide us with a way to share reusable functions. A
module is simply a “Python file” which contains code we can
reuse in multiple Python programs. A module may contain
functions, classes, lists, etc.
• Modules in Python can be of two types:
• Built-in Modules.
• User-defined Modules.
Built-in Modules in Python

• They are pre-written lines of codes as functions pre-stored in python


programming language ready to reuse by the python programmers.
• Before using these modules, we need to import them.
• We also call them as python libraries
• For Example
• Pandas
• Matplotlib
• Numpy
• Random
User-Defined Modules in Python
• You can create your own functions and classes, put them inside
modules and can now include hundreds of lines of code into any
program just by writing a simple import statement.
• Steps to create user defined module
• Open one jupyter file in text mode
• Type a function definition in the text file and save as .py file

• Open a Jupyter notebook in Python3 mode and import the function


Using from…import statement
• You can import a specific function, class, or attribute from a
module rather than importing the entire module.

from math import pi, sqrt


print(3 * pi)
print(sqrt(100))

• If we need to import everything from a module and we don’t


want to use the dot operator

from math import *


print(3 * pi)
print(sqrt(100))
To demonstrate how to access standard
functions using import keyword
Python Calendar Module
1. import calendar
calendar.prcal(2021)
If you change the day your calendar
month will start from that day.
2. import calendar
c= calendar.TextCalendar(calendar.SUNDAY)
str= c.formatmonth(2022,1)
print(str)
• To print the calendar in HTML format
import calendar
c= calendar.HTMLCalendar(calendar.SUNDAY)
str= c.formatmonth(2022,1)
print(str)
Python time Module
• Python has a module named time to handle time-related tasks.
• To use functions defined in the module, we need to import the module
first.
Commonly used time-related functions.
• Python time.time()
The time() function returns the number of seconds passed since epoch.

import time
seconds = time.time()
print("Seconds since epoch =", seconds)
• Python time.ctime()
The time.ctime() function takes seconds passed since epoch as an
argument and returns a string representing local time.

import time
# seconds passed since epoch
seconds = 1545925769.9618232
local_time = time.ctime(seconds)
print("Local time:", local_time)
Cont…
• Python time.sleep()
The sleep() function suspends (delays) execution of the current
thread for the given number of seconds.

import time
print("This is printed immediately.")
time.sleep(2.4)
print("This is printed after 2.4 seconds.")
Cont…
• Python time.strftime()
• The strftime() function takes struct_time (or tuple corresponding to it) as an
argument and returns a string representing it based on the format code used.
• Here, %Y, %m, %d, %H etc. are format codes.

• %Y - year [0001,..., 2018, 2019,..., 9999]


• %m - month [01, 02, ..., 11, 12]
• %d - day [01, 02, ..., 30, 31]
• %H - hour [00, 01, ..., 22, 23
• %M - minutes [00, 01, ..., 58, 59]
• %S - second [00, 01, ..., 58, 61]
Python can create a digital clock
import time
while True:
localtime = time.localtime()
result = time.strftime("%I:%M:%S %p", localtime)
print(result)
time.sleep(1)
Exercise
• Table of any number entered by the user
• Find the maximum number among the three numbers
• Program to use switch case statement – Accept two numbers from the user and ask
the choice of performing operation such as addition, multiplication, subtraction or
division. As per the users choice perform the operation.
• Write a program to print even numbers between 1 to 20 and odd numbers between
1 to 20
• Write a program to add the digits of a given number (3+2+1=6)
• Fibonacci series – using modules
• Factorial of a number - using modules
• Factorial of a number using lambda function
• Create a python module contain python code used to calculate the area of a square
shape, Then use this module in another python file to calculate the area of a square
has the side equal 20 cm

You might also like