Session 5
Session 5
While Loop
With the while loop we can execute a set of statements as long as a condition is true.
while condition:
statements
TRY IT YOURSELF
using while loop print the table like:
5 x 1 = 5
5 x 2 = 10
.
.
.
5 x 10 = 50
In [ ]: 1 # break
2 number = int(input("Enter any number: "))
3 loop_number = 1
4 while loop_number <= 10:
5 product = number * loop_number
6
7 if product > 20:
8 break
9
10 print(str(number) + " X " + str(loop_number) + " = " + str
11 loop_number += 1
In [ ]: 1 # continue
2 current_number = 0
3 while current_number < 10:
4 current_number += 1
5
6 if current_number % 2 == 0:
7 continue
8 print(current_number)
In [9]: 1 8 % 5
Out[9]: 3
For Loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works more
like an iterator method as found in other object orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list,
tuple, set etc.
b a n a n a
0,1,2,3,4,5,6,7,8,9,
0 10 20 30 40 50 60 70 80 90 100
Functions
These are named blocks of code that are designed to do one specific job.
When you want to perform a particular task that you’ve defined in a function, you call
the name of the function responsible for it.
def function_name():
statements
Hello, Vishwas!
Try it yourself
In [38]: 1 # Passing Information to a Function
2 def greet_user(fname, lname):
3 print("Hello, " + fname.title() + " " + lname.title() + "!
4
5 # calling with parameters
6 greet_user("vishwas","srivastava")
Sometimes you won’t know ahead of time how many arguments a function needs to
accept.
Fortunately, Python allows a function to collect an arbitrary number of arguments
from the calling statement.
In [ ]: 1 def make_pizza(*toppings):
2 print("\nMaking a pizza with the following toppings:")
3 for x in toppings:
4 print("- " + x)
5
6 make_pizza('pepperoni')
7 make_pizza('mushrooms', 'green peppers', 'extra cheese')
TRY IT YOURSELF