SlideShare a Scribd company logo
1 of 43
Download to read offline
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'}

More Related Content

What's hot

Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
PPS Arrays Matrix operations
PPS Arrays Matrix operationsPPS Arrays Matrix operations
PPS Arrays Matrix operationsSreedhar Chowdam
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, RecursionSreedhar Chowdam
 
Exception Handling
Exception HandlingException Handling
Exception HandlingSunil OS
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptxAkshayAggarwal79
 
Variables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaVariables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaEdureka!
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++Neeru Mittal
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ pptKumar
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and ClassesSvetlin Nakov
 

What's hot (20)

Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
Dictionary in python
Dictionary in pythonDictionary in python
Dictionary in python
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
PPS Arrays Matrix operations
PPS Arrays Matrix operationsPPS Arrays Matrix operations
PPS Arrays Matrix operations
 
STL in C++
STL in C++STL in C++
STL in C++
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
 
Java practical
Java practicalJava practical
Java practical
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Python programming
Python  programmingPython  programming
Python programming
 
Python programming : Standard Input and Output
Python programming : Standard Input and OutputPython programming : Standard Input and Output
Python programming : Standard Input and Output
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
 
Variables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaVariables & Data Types In Python | Edureka
Variables & Data Types In Python | Edureka
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Set methods in python
Set methods in pythonSet methods in python
Set methods in python
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
Gui programming
Gui programmingGui programming
Gui programming
 
Python Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String MethodsPython Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String Methods
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
 

Similar to 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
 

Similar to 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
 

More from 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
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem SolvingSreedhar 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
 

More from 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
 
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
 
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
 
GPREC DBMS Notes 1
GPREC DBMS Notes 1GPREC DBMS Notes 1
GPREC DBMS Notes 1
 
Computer Networks Unit 5
Computer Networks Unit 5Computer Networks Unit 5
Computer Networks Unit 5
 
Jp notes
Jp notesJp notes
Jp notes
 

Recently uploaded

Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
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
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
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
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
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
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 

Recently uploaded (20)

Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
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 )
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
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
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
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...
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 

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'}