[go: up one dir, main page]

0% found this document useful (0 votes)
12 views76 pages

unit2

Uploaded by

pm481628
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)
12 views76 pages

unit2

Uploaded by

pm481628
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/ 76

Python Programming

Unit 2
(BCC-302)
Ms. Akansha Singh
Assistant Professor
CSE/IT
UNIT II- Python Program Flow Control
Conditional blocks:
• if, else and else if
• Simple for loops in python
• For loop using ranges
• string, list and dictionaries
• Use of while loops in python
• Nested Loops,
• Break and Continue.
• Loop manipulation using pass, continue, break and else
• Programming using Python conditional and loop blocks
Conditional Statements
1) if: If condition is evaluated to True, the code
inside the body of if is executed.
• If condition is evaluated to False, the code
inside the body of if is skipped.
Example 1:

name= input("enter your name : ")


if(name=="abc"):
print("hello how are you:" , name)
print("i dont know")
Example 2:
num=int(input("enter a number: "))
if num>0:
print(‘number is positive:’)
print(‘the if statement is easy’)
2) if-else: if condition is true then Action-1 will
be executed otherwise Action-2 will be
executed.
Example1:
name= input("enter your name : ")
if(name=="abc"):
print("hello how are you:" , name)
else:
print("i dont know")
Example 2:

num=int(input("enter a number: "))


if num>0:
print("the number is not zero")
print("its not zero")
else:
print("the number is zero")
print("hello")
print("the acutual no. is: ", num)
print(‘this statement is always excuted”)
3) if-elif-else: Based condition the corresponding action will
be executed.
if condition1:
Action-1
elif condition2:
Action-2
elif condition3:
Action-3
elif condition4:
Action-4
...
else:
Default Action
Example1:

num=int(input("enter a number: "))


if num>0:
print("the number is postivite integer")
print("the number is :", num)
elif num==0:
print("the number is zero")
else:
print("the number is negative integer")
print("the Number is:", num)
print("this statement is always excuted")
PROGRAM
1. Write a Program to find Biggest of given 2 Numbers?
2. Write a Program to find Biggest of given 3 Numbers?
3. Write a program to check whether the given number is even
or odd?
4. Write a Program to check whether the given Number is in
between 1 and 100?
5. Write a Program to take a Single Digit Number from the
Keyboard and Print is Value in English Word?
Python Loops
• The flow of the programs written in any
programming language is sequential by
default.
• Sometimes we may need to alter the flow of
the program.
• The execution of a specific code may need to
be repeated several numbers of times.
Python for loop
The for loop in Python is used to iterate the
statements or a part of the program several
times. It is frequently used to traverse the
data structures like list, tuple, or dictionary.
The syntax of for loop in python is given below.
for iterating_var in sequence:
statement(s)
The range() Function
• To loop through a set of code a specified
number of times, we can use
the range() function,
• The range() function returns a sequence of
numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a
specified number.
Example
for x in range(6):
print(x)
• Note that range(6) is not the values of 0 to 6,
but the values 0 to 5.
• The range() function defaults to 0 as a starting
value, however it is possible to specify the
starting value by adding a parameter:
• range(2, 6), which means values from 2 to 6
(but not including 6):
The range() function defaults to increment the
sequence by 1, however it is possible to
specify the increment value by adding a third
parameter: range(2, 30, 3):
Example
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
i=1
n=int(input("Enter the number up to which you
want to print the natural numbers?"))
for i in range(0,10):
print(i,end = ' ')

Output:
0123456789
printing the table of the given number
i=1
num = int(input("Enter a number:"))
for i in range(1,11):
print("%d X %d = %d"%(num,i,num*i))
Nested for loop in python
• Python allows us to nest any number of for
loops inside a for loop.
• The inner loop is executed n number of times
for every iteration of the outer loop.
Syntax
for iterating_var1 in sequence:
for iterating_var2 in sequence:
#block of statements
#Other statements
Pattern
n=int(input("enter the number of rows"))
for i in range (0,n):
for j in range (0,i+1):
print("*",end=" ")
print()
Output
Using else statement with for loop
• Unlike other languages like C, C++, or Java,
python allows us to use the else statement
with the for loop which can be executed only
when all the iterations are exhausted.
• Here, we must notice that if the loop contains
any of the break statement then the else
statement will not be executed.
Example
for i in range(0,5):
print(i)
else:
print("for loop completely exhausted, since there is
no break.");
Output
0
1
2
3
4
for loop completely exhausted, since there is no
break.
Example
for i in range(0,5):
print(i)
break;
else:
print("for loop is exhausted");
print("The loop is broken due to break statemen
t...came out of loop")
Output:
0
The loop is broken due to break
statement...came out of loop
Program

1. Python Program to calculate the square of a


given number.
n = int(input("enter a number"))

# Finding square by multiplying them


# with each other
square = n * n

# Printing square
print(square)
2. Python Program to convert Celsius to
Fahrenheit.
celsius = float(input("enter a celsius:" ))

# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree
Fahrenheit' %(celsius,fahrenheit))
3. WAP in python to check whether an integer is
Armstrong or Not.
i=int(input("enter a number"))
org=i
sum=0
while i>0:
sum=sum+(i%10)*(i%10)*(i%10)
i=i//10
if org==sum:
print("number is Armstrong")
else:
print("number is not armstrong")
Output
enter a number258number is not
armstrong
4. WAP in python to check given number is
prime or not
num=int(input("enter a number"))
if num>1:
for i in range(2, num):
if(num%i==0):
print(num,"is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
enter a number13
13 is a prime number
5. WAP in python to print the Fibonacci Series
using iterative method
n=int(input("enter a number till the fabonacci series"))
x=0
y=1
z=0
while(z<=n):
x=y
y=z
z=x+y
print(z)

6. Python Program to check the given year is a
leap year or not.
year = int(input("enter a year:"))
# divided by 100 means century year (ending with 00)
# century year divided by 400 is leap year
if (year % 400 == 0) and (year % 100 == 0):
print("{0} is a leap year".format(year))
# not divided by 100 means not a century year
# year divided by 4 is a leap year
elif (year % 4 ==0) and (year % 100 != 0):
print("{0} is a leap year".format(year))
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))
Transfer Statement:
• Break
• Continue
• Pass
The break Statement
With the break statement we can stop the loop
before it has looped through all the items:
Example
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
Example-2
Output
Example-3
Output
The continue Statement
With the continue statement we can stop the
current iteration of the loop, and continue
with the next:
Example
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
Output
Example-2
for i in range(1,20):
if i%2==0:
continue
print(i)
Output
1
3
5
7
9
11
13
15
17
19
Print each fruit in a fruit list
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Looping Through a String
for x in "banana":
print(x)
Example
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
Example-3
x=[10,20,0,30,0,40,50]

for i in x:
if(i==0):
print("how we can divide zero.... just skip")
continue
print("100/{} = {}".format(i,100/i))
Output
100/10 = 10.0
100/20 = 5.0
how we can divide zero.... just skip
100/30 = 3.3333333333333335
how we can divide zero.... just skip
100/40 = 2.5
100/50 = 2.0
Python Pass
• In Python, pass keyword is used to execute
nothing; it means, when we don't want to
execute code, the pass can be used to execute
empty.
• It just makes the control to pass by without
executing any code. If we want to bypass any
code pass statement can be used.
Example

for i in [1,2,3,4,5]:
if i==3:
pass
print "Pass when value is",i
print i,
Example
Program-2
1. Write a program to reverse an integer in
Python.
Program-2 (Cont..)

num = int(input("enter a number: "))


reversed_num = 0

while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10

print("Reversed Number: " + str(reversed_num))


Program-2 (Cont..)
2. Write a program in Python to check whether a
number is palindrome or not using iterative
method.
Program-2 (Cont..)
n = int(input("please give a number : "))
reverse,temp = 0,n
while temp!=0:
reverse = reverse*10 + temp%10;
temp=temp//10;
if reverse==n:
print("number is palindrom")
else:
print("number is not palindrom")
Program-2 (Cont..)
3. Write a program in Python to find sum of
digits of a number
Program-2 (Cont..)
num = int(input("enter a number: "))
sum = 0

while num!=0:
digit = int(num%10)
sum += digit
num = num/10

print(sum)
Program-2 (Cont..)
4. Write a program in Python to swap two
numbers without using third variable
Program-2 (Cont..)
x = int(input("enter a number:"))
y = int(input("enter a number:"))
print ("Before swapping: ")
print("Value of x : ", x, " and y : ", y)
# Swap code
x=x+y
y=x-y
x=x-y
print ("After swapping: ")
print("Value of x : ", x, " and y : ", y)
Program-2 (Cont..)
5. Python Program to calculate the square root
of a given number.
Program-2 (Cont..)
num = int(input("enter a number :"))
num_sqrt = num ** 2
print('The square root of ',num_sqrt)
Program-2 (Cont..)
6. Pattern-1
----*
---**
--***
-****
*****
Program-2 (Cont..)
for i in range(1,6):
print(' ' * (5-i)+ '*'* (2*i-1))
Program-2 (Cont..)
7. Pattern 2
*--------*
**-------**
***----***
****--****
**********
Program-2 (Cont..)
----*
---**
--***
-****
*****
****-
***--
**---
*----
1
22
333
4444
55555

You might also like