SlideShare a Scribd company logo
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

Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
Sreedhar Chowdam
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
Python : Functions
Python : FunctionsPython : Functions
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
Python Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaPython Collections Tutorial | Edureka
Python Collections Tutorial | Edureka
Edureka!
 
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
Edureka!
 
Ch_13_Dictionary.pptx
Ch_13_Dictionary.pptxCh_13_Dictionary.pptx
Ch_13_Dictionary.pptx
HarishParthasarathy4
 
Python Dictionary
Python DictionaryPython Dictionary
Python Dictionary
Soba Arjun
 
Data types in python
Data types in pythonData types in python
Data types in python
RaginiJain21
 
Oops presentation
Oops presentationOops presentation
Oops presentation
sushamaGavarskar1
 
Python Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String FormattingPython Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String Formatting
P3 InfoTech Solutions Pvt. Ltd.
 
Set methods in python
Set methods in pythonSet methods in python
Set methods in python
deepalishinkar1
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
Sreedhar Chowdam
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | Edureka
Edureka!
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
Srinivas Narasegouda
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
Lifna C.S
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
Prof. Dr. K. Adisesha
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
Pooja B S
 

What's hot (20)

Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
Python Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaPython Collections Tutorial | Edureka
Python Collections Tutorial | Edureka
 
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
 
Ch_13_Dictionary.pptx
Ch_13_Dictionary.pptxCh_13_Dictionary.pptx
Ch_13_Dictionary.pptx
 
Python Dictionary
Python DictionaryPython Dictionary
Python Dictionary
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
Python Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String FormattingPython Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String Formatting
 
Set methods in python
Set methods in pythonSet methods in python
Set methods in python
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | Edureka
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 
Sets in python
Sets in pythonSets in python
Sets in python
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
 

Similar to Python Programming

Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
Rakotoarison Louis Frederick
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
BAINIDA
 
1. control structures in the python.pptx
1. control structures in the python.pptx1. control structures in the python.pptx
1. control structures in the python.pptx
DURAIMURUGANM2
 
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
 
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
 
PRACTICAL FILE(COMP SC).pptx
PRACTICAL FILE(COMP SC).pptxPRACTICAL FILE(COMP SC).pptx
PRACTICAL FILE(COMP SC).pptx
AbhinavGupta257043
 
A few solvers for portfolio selection
A few solvers for portfolio selectionA few solvers for portfolio selection
A few solvers for portfolio selection
Bogusz Jelinski
 
GE3151_PSPP_UNIT_3_Notes
GE3151_PSPP_UNIT_3_NotesGE3151_PSPP_UNIT_3_Notes
GE3151_PSPP_UNIT_3_Notes
Asst.prof M.Gokilavani
 
1.2 matlab numerical data
1.2  matlab numerical data1.2  matlab numerical data
1.2 matlab numerical data
TANVIRAHMED611926
 
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
Sunil Yadav
 
Functions Practice Sheet.docx
Functions Practice Sheet.docxFunctions Practice Sheet.docx
Functions Practice Sheet.docx
SwatiMishra364461
 
Python programming workshop session 2
Python programming workshop session 2Python programming workshop session 2
Python programming workshop session 2
Abdul Haseeb
 
Python Tidbits
Python TidbitsPython Tidbits
Python Tidbits
Mitchell Vitez
 
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
Sheila Sinclair
 
Programs in array using SWIFT
Programs in array using SWIFTPrograms in array using SWIFT
Programs in array using SWIFT
vikram mahendra
 
NPTEL QUIZ.docx
NPTEL QUIZ.docxNPTEL QUIZ.docx
NPTEL QUIZ.docx
GEETHAR59
 
Lecture 3 and 4.pptx
Lecture 3 and 4.pptxLecture 3 and 4.pptx
Lecture 3 and 4.pptx
MAHAMASADIK
 
Pseudocode By ZAK
Pseudocode By ZAKPseudocode By ZAK
Pseudocode By ZAK
Tabsheer Hasan
 
Idea for ineractive programming language
Idea for ineractive programming languageIdea for ineractive programming language
Idea for ineractive programming language
Lincoln Hannah
 
calculator_new (1).pdf
calculator_new (1).pdfcalculator_new (1).pdf
calculator_new (1).pdf
ni30ji
 

Similar to 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
 
1. control structures in the python.pptx
1. control structures in the python.pptx1. control structures in the python.pptx
1. control structures in the python.pptx
 
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
 

More from Sreedhar Chowdam

Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
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 Notes
Sreedhar 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 TCP
Sreedhar Chowdam
 
Data Communication and Computer Networks
Data Communication and Computer NetworksData Communication and Computer Networks
Data Communication and Computer Networks
Sreedhar Chowdam
 
DCCN Unit 1.pdf
DCCN Unit 1.pdfDCCN Unit 1.pdf
DCCN Unit 1.pdf
Sreedhar Chowdam
 
Data Communication & Computer Networks
Data Communication & Computer NetworksData Communication & Computer Networks
Data Communication & Computer Networks
Sreedhar Chowdam
 
PPS Notes Unit 5.pdf
PPS Notes Unit 5.pdfPPS Notes Unit 5.pdf
PPS Notes Unit 5.pdf
Sreedhar Chowdam
 
PPS Arrays Matrix operations
PPS Arrays Matrix operationsPPS Arrays Matrix operations
PPS Arrays Matrix operations
Sreedhar Chowdam
 
Big Data Analytics Part2
Big Data Analytics Part2Big Data Analytics Part2
Big Data Analytics Part2
Sreedhar Chowdam
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
Sreedhar Chowdam
 
Programming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture NotesProgramming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture Notes
Sreedhar Chowdam
 
Big Data Analytics
Big Data AnalyticsBig Data Analytics
Big Data Analytics
Sreedhar Chowdam
 
Data Structures Notes 2021
Data Structures Notes 2021Data Structures Notes 2021
Data Structures Notes 2021
Sreedhar Chowdam
 
Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01
Sreedhar Chowdam
 
Dbms university library database
Dbms university library databaseDbms university library database
Dbms university library database
Sreedhar Chowdam
 
Er diagram for library database
Er diagram for library databaseEr diagram for library database
Er diagram for library database
Sreedhar Chowdam
 
Dbms ER Model
Dbms ER ModelDbms ER Model
Dbms ER Model
Sreedhar Chowdam
 
DBMS Notes: DDL DML DCL
DBMS Notes: DDL DML DCLDBMS Notes: DDL DML DCL
DBMS Notes: DDL DML DCL
Sreedhar Chowdam
 
GPREC DBMS Notes 1
GPREC DBMS Notes 1GPREC DBMS Notes 1
GPREC DBMS Notes 1
Sreedhar Chowdam
 

More from Sreedhar Chowdam (20)

Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
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
 
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
 
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
 

Recently uploaded

Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 

Recently uploaded (20)

Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 

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