SlideShare ist ein Scribd-Unternehmen logo
1 von 43
Downloaden Sie, um offline zu lesen
8 Apr 2022: Unit 2: Decision statements; Loops
PYTHON PROGRAMMING
B.Tech IV Sem CSE A
Unit 2
 Decision Statements: Boolean Type, Boolean Operators, Using
Numbers with Boolean Operators, Using String with Boolean
Operators, Boolean Expressions and Relational Operators,
Decision Making Statements, Conditional Expressions.
 Loop Control Statements: while Loop, range() Function, for Loop,
Nested Loops, break, continue.
 Functions: Syntax and Basics of a Function, Use of a Function,
Parameters and Arguments in a Function, The Local and Global
Scope of a Variable, The return Statement, Recursive Functions,
The Lambda Function.
Boolean type
Python boolean data type has two values: True and False.
Use the bool() function to test if a value is True or False.
a = True
type(a)
<class 'bool'>
b = False
type(b)
<class 'bool'>
branch = "CSEA"
section = 4
print(bool(branch))
print(bool(section))
True
True
bool("Welcome")
True
bool(‘’)
False
print(bool("abc"))
print(bool(123))
print(bool(["app", “bat", “mat"]))
True
True
True
Boolean operators
 not
 and
 or
A=True
B=False
A and B
False
A=True
B=False
A or B
True
A=True
B=False
not A
False
A=True
B=False
not B
True
A=True
B=False
C=False
D= True
(A and D) or(B or C)
True
Write code that counts the number of words in
sentence that contain either an “a” or an “e”.
sentence=input()
words = sentence.split(" ")
count = 0
for i in words:
if (('a' in i) or ('e' in i)) :
count +=1
print(count)
BOOLEAN EXPRESSIONS AND RELATIONAL
OPERATORS
2 < 4 or 2
True
2 < 4 or [ ]
True
5 > 10 or 8
8
print(1 <= 1)
print(1 != 1)
print(1 != 2)
print("CSEA" != "csea")
print("python" != "python")
print(123 == "123")
True
False
True
True
False
False
x = 84
y = 17
print(x >= y)
print(y <= x)
print(y < x)
print(x <= y)
print(x < y)
print(x % y == 0)
True
True
True
False
False
False
x = True
y = False
print(not y)
print(x or y)
print(x and not y)
print(not x)
print(x and y)
print(not x or y)
True
True
True
False
False
False
Decision statements
Python supports the following decision-
making statements.
if statements
if-else statements
Nested if statements
Multi-way if-elif-else statements
if
 Write a program that prompts a user to enter two integer values.
Print the message ‘Equals’ if both the entered values are equal.
 if num1- num2==0: print(“Both the numbers entered are Equal”)
 Write a program which prompts a user to enter the radius of a circle.
If the radius is greater than zero then calculate and print the area
and circumference of the circle
if Radius>0:
Area=Radius*Radius*pi
.........
 Write a program to calculate the salary of a medical
representative considering the sales bonus and incentives
offered to him are based on the total sales. If the sales
exceed or equal to 1,00,000 follow the particulars of
Column 1, else follow Column 2.
Sales=float(input(‘Enter Total Sales of the Month:’))
if Sales >= 100000:
basic = 4000
hra = 20 * basic/100
da = 110 * basic/100
incentive = Sales * 10/100
bonus = 1000
conveyance = 500
else:
basic = 4000
hra = 10 * basic/100
da = 110 * basic/100
incentive = Sales * 4/100
bonus = 500
conveyance = 500
salary= basic+hra+da+incentive+bonus+conveyance
# print Sales,basic,hra,da,incentive,bonus,conveyance,sal
Write a program to read three numbers from a user and
check if the first number is greater or less than the other
two numbers.
if num1>num2:
if num2>num3:
print(num1,”is greater than “,num2,”and “,num3)
else:
print(num1,” is less than “,num2,”and”,num3)
Finding the Number of Days in a Month
flag = 1
month = (int(input(‘Enter the month(1-12):’)))
if month == 2:
year = int(input(‘Enter year:’))
if (year % 4 == 0) and (not(year % 100 == 0)) or (year % 400 == 0):
num_days = 29
else:
num_days = 28
elif month in (1,3,5,7,8,10,12):
num_days = 31
elif month in (4, 6, 9, 11):
num_days = 30
else:
print(‘Please Enter Valid Month’)
flag = 0
if flag == 1:
print(‘There are ‘,num_days, ‘days in’, month,’ month’)
Write a program that prompts a user to enter two different
numbers. Perform basic arithmetic operations based on the
choices.
.......
if choice==1:
print(“ Sum=,”is:”,num1+num2)
elif choice==2:
print(“ Difference=:”,num1-num2)
elif choice==3:
print(“ Product=:”,num1*num2)
elif choice==4:
print(“ Division:”,num1/num2)
else:
print(“Invalid Choice”)
Multi-way if-elif-else Statements: Syntax
If Boolean-expression1:
statement1
elif Boolean-expression2 :
statement2
elif Boolean-expression3 :
statement3
- - - - - - - - - - - - - -
- - - - - - - - - - - -- -
elif Boolean-expression n :
statement N
else :
Statement(s)
CONDITIONAL EXPRESSIONS
if x%2==0:
x = x*x
else:
x = x*x*x
x=x*x if x % 2 == 0 else x*x*x
find the smaller number among the two numbers.
min=print(‘min=‘,n1) if n1<n2 else print(‘min = ‘,n2)
Loop Controlled Statements
while Loop
range() Function
for Loop
Nested Loops
break Statement
continue Statement
Multiplication table using while
num=int(input("Enter no: "))
count = 10
while count >= 1:
prod = num * count
print(num, "x", count, "=", prod)
count = count - 1
Enter no: 4
4 x 10 = 40
4 x 9 = 36
4 x 8 = 32
4 x 7 = 28
4 x 6 = 24
4 x 5 = 20
4 x 4 = 16
4 x 3 = 12
4 x 2 = 8
4 x 1 = 4
num=int(input(“Enter the number:”))
fact=1
ans=1
while fact<=num:
ans=ans*fact
fact=fact+1
print(“Factorial of”,num,” is: “,ans)
Factorial of a given number
text = "Engineering"
for character in text:
print(character)
E
n
g
i
n
e
e
r
i
n
g
courses = ["Python", "Computer Networks", "DBMS"]
for course in courses:
print(course)
Python
Computer Networks
DBMS
for i in range(10,0,-1):
print(i,end=" ")
# 10 9 8 7 6 5 4 3 2 1
Range
function
range(start,stop,step size)
dates = [2000,2010,2020]
N=len(dates)
for i in range(N):
print(dates[i])
2000
2010
2020
for count in range(1, 6):
print(count)
1
2
3
4
5
range: Examples
Program which iterates through integers from 1 to 50 (using for loop).
For an integer that is even, append it to the list even numbers.
For an integer that is odd, append it the list odd numbers
even = []
odd = []
for number in range(1,51):
if number % 2 == 0:
even.append(number)
else:
odd.append(number)
print("Even Numbers: ", even)
print("Odd Numbers: ", odd)
Even Numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50]
Odd Numbers: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]
Write code that will count the number of vowels in the
sentence s and assign the result to the variable
num_vowels. For this problem, vowels are only a, e, i, o,
and u.
s = input()
vowels = ['a','e','i','o','u']
s = list(s)
num_vowels = 0
for i in s:
for j in i:
if j in vowels:
num_vowels+=1
print(num_vowels)
for i in range(1,100,1):
if(i==11):
break
else:
print(i, end=” “)
1 2 3 4 5 6 7 8 9 10
break: example
for i in range(1,11,1):
if i == 5:
continue
print(i, end=” “)
1 2 3 4 6 7 8 9 10
continue: example
function
def square(num):
return num**2
print (square(2))
print (square(3))
def printDict():
d=dict()
d[1]=1
d[2]=2**2
d[3]=3**2
print (d)
printDict() {1: 1, 2: 4, 3: 9}
function: examples
def sum(x,y):
s=0;
for i in range(x,y+1):
s=s+i
print(‘Sum of no’s from‘,x,’to‘,y,’ is ‘,s)
sum(1,25)
sum(50,75)
sum(90,100)
function: Example
def disp_values(a,b=10,c=20):
print(“ a = “,a,” b = “,b,”c= “,c)
disp_values(15)
disp_values(50,b=30)
disp_values(c=80,a=25,b=35)
a = 15 b = 10 c= 20
a = 50 b = 30 c= 20
a = 25 b = 35 c= 80
function: Example
LOCAL AND GLOBAL SCOPE OF A VARIABLE
p = 20 #global variable p
def Demo():
q = 10 #Local variable q
print(‘Local variable q:’,q)
print(‘Global Variable p:’,p)
Demo()
print(‘global variable p:’,p)
Local variable q: 10
Global Variable p: 20
global variable p: 20
a = 20
def Display():
a = 30
print(‘a in function:’,a)
Display()
print(‘a outside function:’,a)
a in function: 30
a outside function: 20
Local and global variable
Write a function calc_Distance(x1, y1, x2, y2) to calculate the distance
between two points represented by Point1(x1, y1) and Point2 (x2, y2).
The formula for calculating distance is:
import math
def EuclD (x1, y1, x2, y2):
dx=x2-x1
dx=math.pow(dx,2)
dy=y2-y1
dy=math.pow(dy,2)
z = math.pow((dx + dy), 0.5)
return z
print("Distance = ",(format(EuclD(4,4,2,2),".2f")))
def factorial(n):
if n==0:
return 1
return n*factorial(n-1)
print(factorial(4))
Recursion: Factorial
def test2():
return 'cse4a', 68, [0, 1, 2]
a, b, c = test2()
print(a)
print(b)
print(c) cse4a
68
[0, 1, 2]
Returning multiple values
def factorial(n):
if n < 1:
return 1
else:
return n * factorial(n-1)
print(factorial(4))
Recursion: Factorial
def power(x, y):
if y == 0:
return 1
else:
return x * power(x,y-1)
power(2,4)
Recursion: power(x,y)
A lambda function is a small anonymous function with no name.
Lambda functions reduce the number of lines of code
when compared to normal python function defined using def
lambda function
(lambda x: x + 1)(2) #3
(lambda x, y: x + y)(2, 3) #5
Miscellaneous slides
Strings
 "hello"+"world" "helloworld" # concatenation
 "hello"*3 "hellohellohello" # repetition
 "hello"[0] "h" # indexing
 "hello"[-1] "o" # (from end)
 "hello"[1:4] "ell" # slicing
 len("hello") 5 # size
 "hello" < "jello" 1 # comparison
 "e" in "hello" 1 # search
 "escapes: n etc, 033 etc, if etc"
 'single quotes' """triple quotes""" r"raw strings"
Functions
 Function: Equivalent to a static method in Java.
 Syntax:
def name():
statement
statement
...
statement
 Must be declared above the 'main' code
 Statements inside the function must be indented
hello2.py
1
2
3
4
5
6
7
# Prints a helpful message.
def hello():
print("Hello, world!")
# main (calls hello twice)
hello()
hello()
Whitespace Significance
 Python uses indentation to indicate blocks, instead of {}
 Makes the code simpler and more readable
 In Java, indenting is optional. In Python, you must indent.
hello3.py
1
2
3
4
5
6
7
8
# Prints a helpful message.
def hello():
print("Hello, world!")
print("How are you?")
# main (calls hello twice)
hello()
hello()
Python’s Core Data Types
 Numbers: Ex: 1234, 3.1415, 3+4j, Decimal, Fraction
 Strings: Ex: 'spam', "guido's", b'ax01c'
 Lists: Ex: [1, [2, 'three'], 4]
 Dictionaries: Ex: {'food': 'spam', 'taste': 'yum'}
 Tuples: Ex: (1, 'spam', 4, 'U')
 Files: Ex: myfile = open('eggs', 'r')
 Sets: Ex: set('abc'), {'a', 'b', 'c'}

Weitere ähnliche Inhalte

Was ist angesagt? (20)

List in Python
List in PythonList in Python
List in Python
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Python list
Python listPython list
Python list
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 
Python
PythonPython
Python
 
PPS_Unit 4.ppt
PPS_Unit 4.pptPPS_Unit 4.ppt
PPS_Unit 4.ppt
 
Inline function
Inline functionInline function
Inline function
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
 
C Pointers
C PointersC Pointers
C Pointers
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
Python list
Python listPython list
Python list
 
C++ Returning Objects
C++ Returning ObjectsC++ Returning Objects
C++ Returning Objects
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Python
PythonPython
Python
 
Python ppt
Python pptPython ppt
Python ppt
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 

Ähnlich wie Python Programming: Unit 2 Decision Statements and Loops

Python programming workshop
Python programming workshopPython programming workshop
Python programming workshopBAINIDA
 
Literary Genre MatrixPart 1 Matrix FictionNon-fiction.docx
Literary Genre MatrixPart 1 Matrix FictionNon-fiction.docxLiterary Genre MatrixPart 1 Matrix FictionNon-fiction.docx
Literary Genre MatrixPart 1 Matrix FictionNon-fiction.docxjeremylockett77
 
Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Ziyauddin Shaik
 
A few solvers for portfolio selection
A few solvers for portfolio selectionA few solvers for portfolio selection
A few solvers for portfolio selectionBogusz Jelinski
 
Leet Code May Coding Challenge - DataStructure and Algorithm Problems
Leet Code May Coding Challenge - DataStructure and Algorithm ProblemsLeet Code May Coding Challenge - DataStructure and Algorithm Problems
Leet Code May Coding Challenge - DataStructure and Algorithm ProblemsSunil Yadav
 
Functions Practice Sheet.docx
Functions Practice Sheet.docxFunctions Practice Sheet.docx
Functions Practice Sheet.docxSwatiMishra364461
 
Python programming workshop session 2
Python programming workshop session 2Python programming workshop session 2
Python programming workshop session 2Abdul Haseeb
 
Answers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
Answers To Selected Exercises For Fortran 90 95 For Scientists And EngineersAnswers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
Answers To Selected Exercises For Fortran 90 95 For Scientists And EngineersSheila Sinclair
 
Programs in array using SWIFT
Programs in array using SWIFTPrograms in array using SWIFT
Programs in array using SWIFTvikram mahendra
 
NPTEL QUIZ.docx
NPTEL QUIZ.docxNPTEL QUIZ.docx
NPTEL QUIZ.docxGEETHAR59
 
Lecture 3 and 4.pptx
Lecture 3 and 4.pptxLecture 3 and 4.pptx
Lecture 3 and 4.pptxMAHAMASADIK
 
Idea for ineractive programming language
Idea for ineractive programming languageIdea for ineractive programming language
Idea for ineractive programming languageLincoln Hannah
 
calculator_new (1).pdf
calculator_new (1).pdfcalculator_new (1).pdf
calculator_new (1).pdfni30ji
 

Ähnlich wie Python Programming: Unit 2 Decision Statements and Loops (20)

Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
Literary Genre MatrixPart 1 Matrix FictionNon-fiction.docx
Literary Genre MatrixPart 1 Matrix FictionNon-fiction.docxLiterary Genre MatrixPart 1 Matrix FictionNon-fiction.docx
Literary Genre MatrixPart 1 Matrix FictionNon-fiction.docx
 
Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )
 
PRACTICAL FILE(COMP SC).pptx
PRACTICAL FILE(COMP SC).pptxPRACTICAL FILE(COMP SC).pptx
PRACTICAL FILE(COMP SC).pptx
 
A few solvers for portfolio selection
A few solvers for portfolio selectionA few solvers for portfolio selection
A few solvers for portfolio selection
 
GE3151_PSPP_UNIT_3_Notes
GE3151_PSPP_UNIT_3_NotesGE3151_PSPP_UNIT_3_Notes
GE3151_PSPP_UNIT_3_Notes
 
1.2 matlab numerical data
1.2  matlab numerical data1.2  matlab numerical data
1.2 matlab numerical data
 
Leet Code May Coding Challenge - DataStructure and Algorithm Problems
Leet Code May Coding Challenge - DataStructure and Algorithm ProblemsLeet Code May Coding Challenge - DataStructure and Algorithm Problems
Leet Code May Coding Challenge - DataStructure and Algorithm Problems
 
Functions Practice Sheet.docx
Functions Practice Sheet.docxFunctions Practice Sheet.docx
Functions Practice Sheet.docx
 
Python programming workshop session 2
Python programming workshop session 2Python programming workshop session 2
Python programming workshop session 2
 
Python Tidbits
Python TidbitsPython Tidbits
Python Tidbits
 
Answers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
Answers To Selected Exercises For Fortran 90 95 For Scientists And EngineersAnswers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
Answers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
 
Programs in array using SWIFT
Programs in array using SWIFTPrograms in array using SWIFT
Programs in array using SWIFT
 
NPTEL QUIZ.docx
NPTEL QUIZ.docxNPTEL QUIZ.docx
NPTEL QUIZ.docx
 
Lecture 3 and 4.pptx
Lecture 3 and 4.pptxLecture 3 and 4.pptx
Lecture 3 and 4.pptx
 
Pseudocode By ZAK
Pseudocode By ZAKPseudocode By ZAK
Pseudocode By ZAK
 
Idea for ineractive programming language
Idea for ineractive programming languageIdea for ineractive programming language
Idea for ineractive programming language
 
calculator_new (1).pdf
calculator_new (1).pdfcalculator_new (1).pdf
calculator_new (1).pdf
 
Data Handling
Data Handling Data Handling
Data Handling
 

Mehr von Sreedhar Chowdam

Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesSreedhar Chowdam
 
Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Sreedhar Chowdam
 
DCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPDCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPSreedhar Chowdam
 
Data Communication and Computer Networks
Data Communication and Computer NetworksData Communication and Computer Networks
Data Communication and Computer NetworksSreedhar Chowdam
 
Data Communication & Computer Networks
Data Communication & Computer NetworksData Communication & Computer Networks
Data Communication & Computer NetworksSreedhar Chowdam
 
PPS Arrays Matrix operations
PPS Arrays Matrix operationsPPS Arrays Matrix operations
PPS Arrays Matrix operationsSreedhar Chowdam
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem SolvingSreedhar Chowdam
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementSreedhar Chowdam
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, RecursionSreedhar Chowdam
 
Programming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture NotesProgramming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture NotesSreedhar Chowdam
 
Data Structures Notes 2021
Data Structures Notes 2021Data Structures Notes 2021
Data Structures Notes 2021Sreedhar Chowdam
 
Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01Sreedhar Chowdam
 
Dbms university library database
Dbms university library databaseDbms university library database
Dbms university library databaseSreedhar Chowdam
 
Er diagram for library database
Er diagram for library databaseEr diagram for library database
Er diagram for library databaseSreedhar Chowdam
 

Mehr von Sreedhar Chowdam (20)

Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture Notes
 
Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)
 
DCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPDCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCP
 
Data Communication and Computer Networks
Data Communication and Computer NetworksData Communication and Computer Networks
Data Communication and Computer Networks
 
DCCN Unit 1.pdf
DCCN Unit 1.pdfDCCN Unit 1.pdf
DCCN Unit 1.pdf
 
Data Communication & Computer Networks
Data Communication & Computer NetworksData Communication & Computer Networks
Data Communication & Computer Networks
 
PPS Notes Unit 5.pdf
PPS Notes Unit 5.pdfPPS Notes Unit 5.pdf
PPS Notes Unit 5.pdf
 
PPS Arrays Matrix operations
PPS Arrays Matrix operationsPPS Arrays Matrix operations
PPS Arrays Matrix operations
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
 
Big Data Analytics Part2
Big Data Analytics Part2Big Data Analytics Part2
Big Data Analytics Part2
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
 
Programming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture NotesProgramming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture Notes
 
Big Data Analytics
Big Data AnalyticsBig Data Analytics
Big Data Analytics
 
Data Structures Notes 2021
Data Structures Notes 2021Data Structures Notes 2021
Data Structures Notes 2021
 
Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01
 
Dbms university library database
Dbms university library databaseDbms university library database
Dbms university library database
 
Er diagram for library database
Er diagram for library databaseEr diagram for library database
Er diagram for library database
 
Dbms ER Model
Dbms ER ModelDbms ER Model
Dbms ER Model
 
DBMS Notes: DDL DML DCL
DBMS Notes: DDL DML DCLDBMS Notes: DDL DML DCL
DBMS Notes: DDL DML DCL
 

Kürzlich hochgeladen

Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 

Kürzlich hochgeladen (20)

Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 

Python Programming: Unit 2 Decision Statements and Loops

  • 1. 8 Apr 2022: Unit 2: Decision statements; Loops PYTHON PROGRAMMING B.Tech IV Sem CSE A
  • 2. Unit 2  Decision Statements: Boolean Type, Boolean Operators, Using Numbers with Boolean Operators, Using String with Boolean Operators, Boolean Expressions and Relational Operators, Decision Making Statements, Conditional Expressions.  Loop Control Statements: while Loop, range() Function, for Loop, Nested Loops, break, continue.  Functions: Syntax and Basics of a Function, Use of a Function, Parameters and Arguments in a Function, The Local and Global Scope of a Variable, The return Statement, Recursive Functions, The Lambda Function.
  • 3. Boolean type Python boolean data type has two values: True and False. Use the bool() function to test if a value is True or False. a = True type(a) <class 'bool'> b = False type(b) <class 'bool'> branch = "CSEA" section = 4 print(bool(branch)) print(bool(section)) True True bool("Welcome") True bool(‘’) False print(bool("abc")) print(bool(123)) print(bool(["app", “bat", “mat"])) True True True
  • 4. Boolean operators  not  and  or A=True B=False A and B False A=True B=False A or B True A=True B=False not A False A=True B=False not B True A=True B=False C=False D= True (A and D) or(B or C) True
  • 5. Write code that counts the number of words in sentence that contain either an “a” or an “e”. sentence=input() words = sentence.split(" ") count = 0 for i in words: if (('a' in i) or ('e' in i)) : count +=1 print(count)
  • 6. BOOLEAN EXPRESSIONS AND RELATIONAL OPERATORS 2 < 4 or 2 True 2 < 4 or [ ] True 5 > 10 or 8 8 print(1 <= 1) print(1 != 1) print(1 != 2) print("CSEA" != "csea") print("python" != "python") print(123 == "123") True False True True False False
  • 7. x = 84 y = 17 print(x >= y) print(y <= x) print(y < x) print(x <= y) print(x < y) print(x % y == 0) True True True False False False x = True y = False print(not y) print(x or y) print(x and not y) print(not x) print(x and y) print(not x or y) True True True False False False
  • 8. Decision statements Python supports the following decision- making statements. if statements if-else statements Nested if statements Multi-way if-elif-else statements
  • 9. if  Write a program that prompts a user to enter two integer values. Print the message ‘Equals’ if both the entered values are equal.  if num1- num2==0: print(“Both the numbers entered are Equal”)  Write a program which prompts a user to enter the radius of a circle. If the radius is greater than zero then calculate and print the area and circumference of the circle if Radius>0: Area=Radius*Radius*pi .........
  • 10.  Write a program to calculate the salary of a medical representative considering the sales bonus and incentives offered to him are based on the total sales. If the sales exceed or equal to 1,00,000 follow the particulars of Column 1, else follow Column 2.
  • 11. Sales=float(input(‘Enter Total Sales of the Month:’)) if Sales >= 100000: basic = 4000 hra = 20 * basic/100 da = 110 * basic/100 incentive = Sales * 10/100 bonus = 1000 conveyance = 500 else: basic = 4000 hra = 10 * basic/100 da = 110 * basic/100 incentive = Sales * 4/100 bonus = 500 conveyance = 500 salary= basic+hra+da+incentive+bonus+conveyance # print Sales,basic,hra,da,incentive,bonus,conveyance,sal
  • 12. Write a program to read three numbers from a user and check if the first number is greater or less than the other two numbers. if num1>num2: if num2>num3: print(num1,”is greater than “,num2,”and “,num3) else: print(num1,” is less than “,num2,”and”,num3)
  • 13. Finding the Number of Days in a Month flag = 1 month = (int(input(‘Enter the month(1-12):’))) if month == 2: year = int(input(‘Enter year:’)) if (year % 4 == 0) and (not(year % 100 == 0)) or (year % 400 == 0): num_days = 29 else: num_days = 28 elif month in (1,3,5,7,8,10,12): num_days = 31 elif month in (4, 6, 9, 11): num_days = 30 else: print(‘Please Enter Valid Month’) flag = 0 if flag == 1: print(‘There are ‘,num_days, ‘days in’, month,’ month’)
  • 14. Write a program that prompts a user to enter two different numbers. Perform basic arithmetic operations based on the choices. ....... if choice==1: print(“ Sum=,”is:”,num1+num2) elif choice==2: print(“ Difference=:”,num1-num2) elif choice==3: print(“ Product=:”,num1*num2) elif choice==4: print(“ Division:”,num1/num2) else: print(“Invalid Choice”)
  • 15. Multi-way if-elif-else Statements: Syntax If Boolean-expression1: statement1 elif Boolean-expression2 : statement2 elif Boolean-expression3 : statement3 - - - - - - - - - - - - - - - - - - - - - - - - - -- - elif Boolean-expression n : statement N else : Statement(s)
  • 16. CONDITIONAL EXPRESSIONS if x%2==0: x = x*x else: x = x*x*x x=x*x if x % 2 == 0 else x*x*x find the smaller number among the two numbers. min=print(‘min=‘,n1) if n1<n2 else print(‘min = ‘,n2)
  • 17. Loop Controlled Statements while Loop range() Function for Loop Nested Loops break Statement continue Statement
  • 18. Multiplication table using while num=int(input("Enter no: ")) count = 10 while count >= 1: prod = num * count print(num, "x", count, "=", prod) count = count - 1 Enter no: 4 4 x 10 = 40 4 x 9 = 36 4 x 8 = 32 4 x 7 = 28 4 x 6 = 24 4 x 5 = 20 4 x 4 = 16 4 x 3 = 12 4 x 2 = 8 4 x 1 = 4
  • 19. num=int(input(“Enter the number:”)) fact=1 ans=1 while fact<=num: ans=ans*fact fact=fact+1 print(“Factorial of”,num,” is: “,ans) Factorial of a given number
  • 20. text = "Engineering" for character in text: print(character) E n g i n e e r i n g courses = ["Python", "Computer Networks", "DBMS"] for course in courses: print(course) Python Computer Networks DBMS
  • 21. for i in range(10,0,-1): print(i,end=" ") # 10 9 8 7 6 5 4 3 2 1 Range function
  • 22. range(start,stop,step size) dates = [2000,2010,2020] N=len(dates) for i in range(N): print(dates[i]) 2000 2010 2020 for count in range(1, 6): print(count) 1 2 3 4 5 range: Examples
  • 23. Program which iterates through integers from 1 to 50 (using for loop). For an integer that is even, append it to the list even numbers. For an integer that is odd, append it the list odd numbers even = [] odd = [] for number in range(1,51): if number % 2 == 0: even.append(number) else: odd.append(number) print("Even Numbers: ", even) print("Odd Numbers: ", odd) Even Numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50] Odd Numbers: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]
  • 24. Write code that will count the number of vowels in the sentence s and assign the result to the variable num_vowels. For this problem, vowels are only a, e, i, o, and u. s = input() vowels = ['a','e','i','o','u'] s = list(s) num_vowels = 0 for i in s: for j in i: if j in vowels: num_vowels+=1 print(num_vowels)
  • 25. for i in range(1,100,1): if(i==11): break else: print(i, end=” “) 1 2 3 4 5 6 7 8 9 10 break: example
  • 26. for i in range(1,11,1): if i == 5: continue print(i, end=” “) 1 2 3 4 6 7 8 9 10 continue: example
  • 28. def square(num): return num**2 print (square(2)) print (square(3)) def printDict(): d=dict() d[1]=1 d[2]=2**2 d[3]=3**2 print (d) printDict() {1: 1, 2: 4, 3: 9} function: examples
  • 29. def sum(x,y): s=0; for i in range(x,y+1): s=s+i print(‘Sum of no’s from‘,x,’to‘,y,’ is ‘,s) sum(1,25) sum(50,75) sum(90,100) function: Example
  • 30. def disp_values(a,b=10,c=20): print(“ a = “,a,” b = “,b,”c= “,c) disp_values(15) disp_values(50,b=30) disp_values(c=80,a=25,b=35) a = 15 b = 10 c= 20 a = 50 b = 30 c= 20 a = 25 b = 35 c= 80 function: Example
  • 31. LOCAL AND GLOBAL SCOPE OF A VARIABLE p = 20 #global variable p def Demo(): q = 10 #Local variable q print(‘Local variable q:’,q) print(‘Global Variable p:’,p) Demo() print(‘global variable p:’,p) Local variable q: 10 Global Variable p: 20 global variable p: 20
  • 32. a = 20 def Display(): a = 30 print(‘a in function:’,a) Display() print(‘a outside function:’,a) a in function: 30 a outside function: 20 Local and global variable
  • 33. Write a function calc_Distance(x1, y1, x2, y2) to calculate the distance between two points represented by Point1(x1, y1) and Point2 (x2, y2). The formula for calculating distance is: import math def EuclD (x1, y1, x2, y2): dx=x2-x1 dx=math.pow(dx,2) dy=y2-y1 dy=math.pow(dy,2) z = math.pow((dx + dy), 0.5) return z print("Distance = ",(format(EuclD(4,4,2,2),".2f")))
  • 34. def factorial(n): if n==0: return 1 return n*factorial(n-1) print(factorial(4)) Recursion: Factorial
  • 35. def test2(): return 'cse4a', 68, [0, 1, 2] a, b, c = test2() print(a) print(b) print(c) cse4a 68 [0, 1, 2] Returning multiple values
  • 36. def factorial(n): if n < 1: return 1 else: return n * factorial(n-1) print(factorial(4)) Recursion: Factorial
  • 37. def power(x, y): if y == 0: return 1 else: return x * power(x,y-1) power(2,4) Recursion: power(x,y)
  • 38. A lambda function is a small anonymous function with no name. Lambda functions reduce the number of lines of code when compared to normal python function defined using def lambda function (lambda x: x + 1)(2) #3 (lambda x, y: x + y)(2, 3) #5
  • 40. Strings  "hello"+"world" "helloworld" # concatenation  "hello"*3 "hellohellohello" # repetition  "hello"[0] "h" # indexing  "hello"[-1] "o" # (from end)  "hello"[1:4] "ell" # slicing  len("hello") 5 # size  "hello" < "jello" 1 # comparison  "e" in "hello" 1 # search  "escapes: n etc, 033 etc, if etc"  'single quotes' """triple quotes""" r"raw strings"
  • 41. Functions  Function: Equivalent to a static method in Java.  Syntax: def name(): statement statement ... statement  Must be declared above the 'main' code  Statements inside the function must be indented hello2.py 1 2 3 4 5 6 7 # Prints a helpful message. def hello(): print("Hello, world!") # main (calls hello twice) hello() hello()
  • 42. Whitespace Significance  Python uses indentation to indicate blocks, instead of {}  Makes the code simpler and more readable  In Java, indenting is optional. In Python, you must indent. hello3.py 1 2 3 4 5 6 7 8 # Prints a helpful message. def hello(): print("Hello, world!") print("How are you?") # main (calls hello twice) hello() hello()
  • 43. Python’s Core Data Types  Numbers: Ex: 1234, 3.1415, 3+4j, Decimal, Fraction  Strings: Ex: 'spam', "guido's", b'ax01c'  Lists: Ex: [1, [2, 'three'], 4]  Dictionaries: Ex: {'food': 'spam', 'taste': 'yum'}  Tuples: Ex: (1, 'spam', 4, 'U')  Files: Ex: myfile = open('eggs', 'r')  Sets: Ex: set('abc'), {'a', 'b', 'c'}