You are on page 1of 5

In [ ]: 1 # The if-elif-else Chain

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


3 if age < 4:
4 print("Your admission cost is $0.")
5 elif age < 18:
6 print("Your admission cost is $5.")
7 else:
8 print("Your admission cost is $10.")

Enter your age: 23


Your admission cost is $10.

In [ ]: 1 age = int(input("Enter your age: "))


2 if age < 4:
3 price = 0
4 elif age < 18:
5 price = 5
6 else:
7 price = 10
8 print("Your admission cost is $" + str(price) + ".")
Enter your age: 12
Your admission cost is $5.

While Loop
With the while loop we can execute a set of statements as long as a condition is true.

while condition:
statements

In [3]: 1 # while loop


2 current_number = 1
3 while current_number <= 5:
4 print(current_number)
5 current_number += 1 # a += 1 ---> a = a+1
6
7 print()
8 print(current_number)
1
2
3
4
5

TRY IT YOURSELF
using while loop print the table like:

5 x 1 = 5
5 x 2 = 10
.
.
.
5 x 10 = 50

In [ ]: 1 prompt = "\nTell me something, and I will repeat it back to


2 prompt += "\nPress n to quit. "
3 message = ""
4 while message != 'n':
5 message = input(prompt)
6 print(message)

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.

for iterator_var in sequence:


statements(s)

In [15]: 1 # for loop


2 fruits = ["apple", "banana", "cherry", "mango"]
3 for x in fruits:
4 print(x.title())
Apple
Banana
Cherry
Mango

In [20]: 1 # loop through the letters in the word "banana":


2 for x in "banana":
3 print(x, end=" ")

b a n a n a

In [22]: 1 cars = ['audi', 'bmw', 'subaru', 'toyota']


2
3 for car in cars:
4 if car == 'bmw':
5 print(car.upper())
6 else:
7 print(car.title())
Audi
BMW
Subaru
Toyota

In [26]: 1 # using the range() function:


2 for x in range(10):
3 print(x, end=',')

0,1,2,3,4,5,6,7,8,9,

In [27]: 1 # using the start parameter:


2 for x in range(2, 6):
3 print(x)
2
3
4
5
In [30]: 1 # Increment the sequence with 3 (default is 1):
2 # range(start, end-1, steps)
3 for x in range(0, 101, 10):
4 print(x, end=" ")

0 10 20 30 40 50 60 70 80 90 100

In [ ]: 1 l1 = ['black', 'white', 'yellow']


2 l2 = ['laptop', 'table', 'book']
3
4 # black laptop
5 # black table
6 # black book
7 # white laptop
8 # white table
9 # white book

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.

In Python a function is defined using the def keyword:

def function_name():
statements

In [31]: 1 # Display a simple greeting.


2 def greet_user():
3 print("Hello!")
4
5 # function calling
6 greet_user()
Hello!

In [35]: 1 # Passing Information to a Function


2 def greet_user(username):
3 print("Hello, " + username.title() + "!")
4
5 # calling with parameters
6 greet_user("vishwas")

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")

Hello, Vishwas Srivastava!

Passing an Arbitrary Number of Arguments

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 [40]: 1 def make_pizza(*toppings):


2 # doc string
3 """Print the list of toppings
4 that have been requested."""
5 print(toppings)
6
7 # function calling
8 make_pizza('pepperoni')
9 make_pizza('mushrooms', 'green peppers', 'extra cheese')
()
('mushrooms', 'green peppers', 'extra cheese')

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

Write a function that accepts a list of items a person wants on a sandwich.


The function should have one parameter that collects as many items as the
function call provides,and it should print a summary of the sand- wich that is
being ordered. Call the function three times, using a different num- ber of
arguments each time.

You might also like