SlideShare uma empresa Scribd logo
1 de 43
Baixar para ler 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'}

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Python list
Python listPython list
Python list
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Python dictionary
Python dictionaryPython dictionary
Python dictionary
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
Python strings
Python stringsPython strings
Python strings
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | EdurekaWhat is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
 
Python programming
Python  programmingPython  programming
Python programming
 
Python in 30 minutes!
Python in 30 minutes!Python in 30 minutes!
Python in 30 minutes!
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
 
F strings
F stringsF strings
F strings
 
Set methods in python
Set methods in pythonSet methods in python
Set methods in python
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 

Semelhante a Python Programming

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
jeremylockett77
 

Semelhante a Python Programming (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
 

Mais de Sreedhar Chowdam

Mais de 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
 

Último

FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
 

Último (20)

Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
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...
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
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...
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 

Python Programming

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