SlideShare a Scribd company logo
1 of 21
Download to read offline
Instructor: Ebad ullah Qureshi
Email: ebadullah.qureshi@rutgers.edu
N2E Coding Club
Python Workshop
Control Structures
Loops & Conditionals
Python workshop by Ebad ullah Qureshi
Recap
2
In the previous lesson
• Introduction to Python Language
• Output of a Program
• Data types – Integer, Floats, Strings
• Variables
• Operators – Arithmetic, Logical, Comparison and Assignment
In this Lesson
• Program Flow – Algorithms
Python workshop by Ebad ullah Qureshi
Algorithms and Python Scripts
3
Algorithm is a set of steps used by the computer to solve a problem or accomplish a given task.
Features of algorithms
• Sequencing – Execution of instructions step by step
• Iteration – Using a loop, a block of instruction is executed several times
• Decision Making – Using conditional statements, the set of instructions are either executed or
bypassed
To implement algorithms – Python Scripts are written.
• Python scripts allows several lines of Python to be executed
• Python Scripts are written in a Python IDE
To begin writing a Python script, create a Project and a .PY file in Pycharm.
Python workshop by Ebad ullah Qureshi
Getting Input
4
• In python, user is prompted for an input using the input function
• The inputs are always of type string
• The string inputs are converted into different data types when needed
• Python allows multiple inputs at the same time by specifying a delimiter in the split
function
Python workshop by Ebad ullah Qureshi
Getting Input – Example
5
# Taking input
major = input("Enter your Major: “)
no_of_credits = int(input("Enter the number of credits you are enrolled in: "))
year, gpa = input("Enter your Year, GPA: ").split(',')
gpa = float(gpa)
print('You are enrolled in ' + year + ' year in ' + major +
' Major. You have currently taken', no_of_credits,
'credits and your GPA is ' + str(gpa))
Enter your Major: Computer Engineering
Enter the number of credits you are enrolled in: 15
Enter your Year, GPA: Junior, 3.58
You are enrolled in Junior year in Computer Engineering Major. You have currently
taken 15 credits and your GPA is 3.58
A Program that takes Major, Number of credits enrolled, GPA, and the Year of study as input and
then displays that information
Python workshop by Ebad ullah Qureshi
Discount Price Calculator – Problem
6
Shopping during the sales can sometimes be very
confusing. With discounted prices at 10%, 20%, 50% or
even 70%!
For this challenge you are going to write a Python script
that prompts the user to enter a price (e.g. $90) and a
discount rate to apply (e.g. 20%).
Your program will then calculate and display the full
price, the discounted price and the savings.
Python workshop by Ebad ullah Qureshi 7
Discount Price Calculator – Source Code
# Input
price = float(input('Enter the Price of item ($): '))
discount_rate = float(input('Enter the percentage discount (%)'))
# Calculations
savings = price * discount_rate/100
discounted_price = price - savings
# Program Output
print('Original Price: $', price)
print('Discounted Price: $', round(discounted_price, 2))
print('Savings: $', round(savings, 2))
Python workshop by Ebad ullah Qureshi
Decision Making – Conditional Statements
8
# simple if statement
test = 67 < 78
if test:
print('logical value of test is True')
logical value of test is True
• Decision making statements controls which instructions to execute in a program
• Decision structures evaluate expressions which produce True or False as the outcome that
dictates which statements to execute
• Python programming language assumes any non-zero and non-null values as TRUE, and
any zero or null values as FALSE value.
Python workshop by Ebad ullah Qureshi
Conditional Statements – if…else
9
# simple if-else statement
condition = 24 == 56
if condition:
print('Condition is True')
else:
print('Condition is False')
Condition is False
Python workshop by Ebad ullah Qureshi
Conditional Statements – if…elif…else
10
Number is in the range 10 to 19
# if-elif-else statements
number = 12
if (number >= 0) and (number < 10):
print('Number is in the range 0 to 9')
elif (number >= 10) and (number < 20):
print('Number is in the range 10 to 19')
elif (number >= 20) and (number < 30):
print('Number is in the range 20 to 29')
else:
print('Number is negative or greater than 29')
Python workshop by Ebad ullah Qureshi 11
Printing multiple times I
print('Hello World')
print('Hello World')
print('Hello World')
print('Hello World')
print('Hello World')
Print out ‘Hello world’ 5 times
Problem in the above code: Repetition of same code
• To achieve this, programming languages use control structures called loops.
• One cycle of a loop is called iteration
• Loops avoid repeated statements and are useful when the number of iterations depend upon
user’s input
Python workshop by Ebad ullah Qureshi
Loops – loop variables
12
Loop initial value – Specifies the starting value of the loop
Loop end value – Specifies the end value of the loop
Body of the Loop – Statements inside the loop
Loop Condition – Logical value that dictates whether to execute the body of the loop or to exit
out of the loop
Loop Counter – The loop variable that tracks the number of iterations and the current iteration
Loop increment/decrement – The value by which the loop counter increases or decreases in each
iteration
Python workshop by Ebad ullah Qureshi
Loops – For Loop
13
for loop_counter in range(loop_initial_value, loop_end_value, loop_increment):
Statements of the loop body.
End of loop body
• In a for loop, the number of iterations are specified. They can be known or unknown to the
programmer
• The default loop_initial_value is 0
• The default loop_increment is 1
• Loop terminates when loop_counter is equal to (or gets greater than) the loop_end_value
Python workshop by Ebad ullah Qureshi
Loops – While Loop
14
loop_counter = loop_initial_value
while loop_condition:
Statements of the loop body.
End of loop body
loop_counter = loop_increment
• In a while loop, the number of iterations are dependent on the loop condition
• The number of iterations in a while loop can be known or unknown to the programmer
Python workshop by Ebad ullah Qureshi
Printing multiple times II
15
The Problem about printing “Hello World” 5 times can be efficiently coded using loops.
The Loop body would be: print(‘Hello World’)
# for loop
for i in range(5):
print('hello world')
# while loop
count = 0
while count < 5:
print('hello world')
count += 1
 The loop body is executed 5 times
 loop_initial_value = 0
 loop_increment = 1
 To terminate the loop in case of a for loop →
loop_end_value = 5
 To terminate the while loop →
loop_condition = loop_counter < 5
 In both cases, Loop would run for the following values
of loop_counter: 0, 1, 2, 3, 4
Python workshop by Ebad ullah Qureshi
Break & Continue
16
for i in range(5, 10):
print(i)
if i == 8:
break # Break Statement: Program exits out of the loop
5
6
7
8
for i in range(5, 10):
if i == 7 or i == 8:
continue # Continue Statement: skip certain iterations
print(i)
5
6
9
Python workshop by Ebad ullah Qureshi
Staircase – Problem
17
Consider a staircase of size: n = 10
Observe that its base and height are both equal to , and the image is drawn
using # symbols and spaces. The last line is not preceded by any spaces.
Write a program that prints a staircase of size .
Input Format
A single integer, , denoting the size of the staircase.
Constraints
0 < n ≤ 100
Output Format
Print a staircase of size using # symbols and spaces.
Explanation
The staircase is right-aligned, composed of # symbols and
spaces, and has a height and width of n = 10.
Python workshop by Ebad ullah Qureshi
Staircase - Approach
18
#
# #
# # #
# # # #
# # # # #
# # # # # #
# # # # # # #
# # # # # # # #
# # # # # # # # #
# # # # # # # # # #
Observations
input n = number of lines
Iterate through each line such that
 line number (starting from 0) = loop counter
In each line for 10 lines
 number of whitespaces = 9 - loop counter
 number of symbols = loop counter + 1
In each line for n lines
 number of whitespaces = n-1 - loop counter
 number of symbols = loop counter + 1
Python workshop by Ebad ullah Qureshi
Staircase – Source Code
19
lines = int(input('Enter the number of lines to be displayed: '))
for i in range(lines):
print((lines-1-i)*' ' + '#'*(i+1))
Enter the number of lines to be displayed: 5
#
##
###
####
#####
Python workshop by Ebad ullah Qureshi
Further Exploration – Try these Patterns
20
Instructor: Ebad ullah Qureshi
Email: ebadullah.qureshi@rutgers.edu
N2E Coding Club
Python Workshop
Control Structures
Complete

More Related Content

What's hot (20)

Cse115 lecture02overviewofprogramming
Cse115 lecture02overviewofprogrammingCse115 lecture02overviewofprogramming
Cse115 lecture02overviewofprogramming
 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02
 
What is c
What is cWhat is c
What is c
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine Learning
 
Program sba
Program sbaProgram sba
Program sba
 
Introduction to C++
Introduction to C++ Introduction to C++
Introduction to C++
 
Unit ii ppt
Unit ii pptUnit ii ppt
Unit ii ppt
 
C fundamentals
C fundamentalsC fundamentals
C fundamentals
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
C programming Workshop
C programming WorkshopC programming Workshop
C programming Workshop
 
C programming
C programmingC programming
C programming
 
Qust & ans inc
Qust & ans incQust & ans inc
Qust & ans inc
 
Pi j1.2 variable-assignment
Pi j1.2 variable-assignmentPi j1.2 variable-assignment
Pi j1.2 variable-assignment
 
Foundations of Programming Part I
Foundations of Programming Part IFoundations of Programming Part I
Foundations of Programming Part I
 
C operators
C operatorsC operators
C operators
 
Esg111 midterm review
Esg111 midterm reviewEsg111 midterm review
Esg111 midterm review
 
C++ for beginners
C++ for beginnersC++ for beginners
C++ for beginners
 
Unit iv functions
Unit  iv functionsUnit  iv functions
Unit iv functions
 
Programing Fundamental
Programing FundamentalPrograming Fundamental
Programing Fundamental
 

Similar to 02 Control Structures - Loops & Conditions

Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)ExcellenceAcadmy
 
Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)ExcellenceAcadmy
 
presentation_python_11_1569171345_375360.pptx
presentation_python_11_1569171345_375360.pptxpresentation_python_11_1569171345_375360.pptx
presentation_python_11_1569171345_375360.pptxGAURAVRATHORE86
 
While-For-loop in python used in college
While-For-loop in python used in collegeWhile-For-loop in python used in college
While-For-loop in python used in collegessuser7a7cd61
 
Logika dan Algoritma pemrograman
Logika dan Algoritma pemrogramanLogika dan Algoritma pemrograman
Logika dan Algoritma pemrogramanArif Huda
 
Python programming workshop session 2
Python programming workshop session 2Python programming workshop session 2
Python programming workshop session 2Abdul Haseeb
 
csharp repitition structures
csharp repitition structurescsharp repitition structures
csharp repitition structuresMicheal Ogundero
 
Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxAmy Nightingale
 
Help with Pyhon Programming Homework
Help with Pyhon Programming HomeworkHelp with Pyhon Programming Homework
Help with Pyhon Programming HomeworkHelpmeinhomework
 
introduction to python in english presentation file
introduction to python in english presentation fileintroduction to python in english presentation file
introduction to python in english presentation fileRujanTimsina1
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdfjamvantsolanki
 

Similar to 02 Control Structures - Loops & Conditions (20)

Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)
 
Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
presentation_python_11_1569171345_375360.pptx
presentation_python_11_1569171345_375360.pptxpresentation_python_11_1569171345_375360.pptx
presentation_python_11_1569171345_375360.pptx
 
While-For-loop in python used in college
While-For-loop in python used in collegeWhile-For-loop in python used in college
While-For-loop in python used in college
 
Logika dan Algoritma pemrograman
Logika dan Algoritma pemrogramanLogika dan Algoritma pemrograman
Logika dan Algoritma pemrograman
 
Python programming workshop session 2
Python programming workshop session 2Python programming workshop session 2
Python programming workshop session 2
 
Python Control structures
Python Control structuresPython Control structures
Python Control structures
 
csharp repitition structures
csharp repitition structurescsharp repitition structures
csharp repitition structures
 
gdscpython.pdf
gdscpython.pdfgdscpython.pdf
gdscpython.pdf
 
Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptx
 
Chapter08.pptx
Chapter08.pptxChapter08.pptx
Chapter08.pptx
 
CP Handout#5
CP Handout#5CP Handout#5
CP Handout#5
 
Help with Pyhon Programming Homework
Help with Pyhon Programming HomeworkHelp with Pyhon Programming Homework
Help with Pyhon Programming Homework
 
introduction to python in english presentation file
introduction to python in english presentation fileintroduction to python in english presentation file
introduction to python in english presentation file
 
python_p4_v2.pdf
python_p4_v2.pdfpython_p4_v2.pdf
python_p4_v2.pdf
 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdf
 

Recently uploaded

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 

Recently uploaded (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

02 Control Structures - Loops & Conditions

  • 1. Instructor: Ebad ullah Qureshi Email: ebadullah.qureshi@rutgers.edu N2E Coding Club Python Workshop Control Structures Loops & Conditionals
  • 2. Python workshop by Ebad ullah Qureshi Recap 2 In the previous lesson • Introduction to Python Language • Output of a Program • Data types – Integer, Floats, Strings • Variables • Operators – Arithmetic, Logical, Comparison and Assignment In this Lesson • Program Flow – Algorithms
  • 3. Python workshop by Ebad ullah Qureshi Algorithms and Python Scripts 3 Algorithm is a set of steps used by the computer to solve a problem or accomplish a given task. Features of algorithms • Sequencing – Execution of instructions step by step • Iteration – Using a loop, a block of instruction is executed several times • Decision Making – Using conditional statements, the set of instructions are either executed or bypassed To implement algorithms – Python Scripts are written. • Python scripts allows several lines of Python to be executed • Python Scripts are written in a Python IDE To begin writing a Python script, create a Project and a .PY file in Pycharm.
  • 4. Python workshop by Ebad ullah Qureshi Getting Input 4 • In python, user is prompted for an input using the input function • The inputs are always of type string • The string inputs are converted into different data types when needed • Python allows multiple inputs at the same time by specifying a delimiter in the split function
  • 5. Python workshop by Ebad ullah Qureshi Getting Input – Example 5 # Taking input major = input("Enter your Major: “) no_of_credits = int(input("Enter the number of credits you are enrolled in: ")) year, gpa = input("Enter your Year, GPA: ").split(',') gpa = float(gpa) print('You are enrolled in ' + year + ' year in ' + major + ' Major. You have currently taken', no_of_credits, 'credits and your GPA is ' + str(gpa)) Enter your Major: Computer Engineering Enter the number of credits you are enrolled in: 15 Enter your Year, GPA: Junior, 3.58 You are enrolled in Junior year in Computer Engineering Major. You have currently taken 15 credits and your GPA is 3.58 A Program that takes Major, Number of credits enrolled, GPA, and the Year of study as input and then displays that information
  • 6. Python workshop by Ebad ullah Qureshi Discount Price Calculator – Problem 6 Shopping during the sales can sometimes be very confusing. With discounted prices at 10%, 20%, 50% or even 70%! For this challenge you are going to write a Python script that prompts the user to enter a price (e.g. $90) and a discount rate to apply (e.g. 20%). Your program will then calculate and display the full price, the discounted price and the savings.
  • 7. Python workshop by Ebad ullah Qureshi 7 Discount Price Calculator – Source Code # Input price = float(input('Enter the Price of item ($): ')) discount_rate = float(input('Enter the percentage discount (%)')) # Calculations savings = price * discount_rate/100 discounted_price = price - savings # Program Output print('Original Price: $', price) print('Discounted Price: $', round(discounted_price, 2)) print('Savings: $', round(savings, 2))
  • 8. Python workshop by Ebad ullah Qureshi Decision Making – Conditional Statements 8 # simple if statement test = 67 < 78 if test: print('logical value of test is True') logical value of test is True • Decision making statements controls which instructions to execute in a program • Decision structures evaluate expressions which produce True or False as the outcome that dictates which statements to execute • Python programming language assumes any non-zero and non-null values as TRUE, and any zero or null values as FALSE value.
  • 9. Python workshop by Ebad ullah Qureshi Conditional Statements – if…else 9 # simple if-else statement condition = 24 == 56 if condition: print('Condition is True') else: print('Condition is False') Condition is False
  • 10. Python workshop by Ebad ullah Qureshi Conditional Statements – if…elif…else 10 Number is in the range 10 to 19 # if-elif-else statements number = 12 if (number >= 0) and (number < 10): print('Number is in the range 0 to 9') elif (number >= 10) and (number < 20): print('Number is in the range 10 to 19') elif (number >= 20) and (number < 30): print('Number is in the range 20 to 29') else: print('Number is negative or greater than 29')
  • 11. Python workshop by Ebad ullah Qureshi 11 Printing multiple times I print('Hello World') print('Hello World') print('Hello World') print('Hello World') print('Hello World') Print out ‘Hello world’ 5 times Problem in the above code: Repetition of same code • To achieve this, programming languages use control structures called loops. • One cycle of a loop is called iteration • Loops avoid repeated statements and are useful when the number of iterations depend upon user’s input
  • 12. Python workshop by Ebad ullah Qureshi Loops – loop variables 12 Loop initial value – Specifies the starting value of the loop Loop end value – Specifies the end value of the loop Body of the Loop – Statements inside the loop Loop Condition – Logical value that dictates whether to execute the body of the loop or to exit out of the loop Loop Counter – The loop variable that tracks the number of iterations and the current iteration Loop increment/decrement – The value by which the loop counter increases or decreases in each iteration
  • 13. Python workshop by Ebad ullah Qureshi Loops – For Loop 13 for loop_counter in range(loop_initial_value, loop_end_value, loop_increment): Statements of the loop body. End of loop body • In a for loop, the number of iterations are specified. They can be known or unknown to the programmer • The default loop_initial_value is 0 • The default loop_increment is 1 • Loop terminates when loop_counter is equal to (or gets greater than) the loop_end_value
  • 14. Python workshop by Ebad ullah Qureshi Loops – While Loop 14 loop_counter = loop_initial_value while loop_condition: Statements of the loop body. End of loop body loop_counter = loop_increment • In a while loop, the number of iterations are dependent on the loop condition • The number of iterations in a while loop can be known or unknown to the programmer
  • 15. Python workshop by Ebad ullah Qureshi Printing multiple times II 15 The Problem about printing “Hello World” 5 times can be efficiently coded using loops. The Loop body would be: print(‘Hello World’) # for loop for i in range(5): print('hello world') # while loop count = 0 while count < 5: print('hello world') count += 1  The loop body is executed 5 times  loop_initial_value = 0  loop_increment = 1  To terminate the loop in case of a for loop → loop_end_value = 5  To terminate the while loop → loop_condition = loop_counter < 5  In both cases, Loop would run for the following values of loop_counter: 0, 1, 2, 3, 4
  • 16. Python workshop by Ebad ullah Qureshi Break & Continue 16 for i in range(5, 10): print(i) if i == 8: break # Break Statement: Program exits out of the loop 5 6 7 8 for i in range(5, 10): if i == 7 or i == 8: continue # Continue Statement: skip certain iterations print(i) 5 6 9
  • 17. Python workshop by Ebad ullah Qureshi Staircase – Problem 17 Consider a staircase of size: n = 10 Observe that its base and height are both equal to , and the image is drawn using # symbols and spaces. The last line is not preceded by any spaces. Write a program that prints a staircase of size . Input Format A single integer, , denoting the size of the staircase. Constraints 0 < n ≤ 100 Output Format Print a staircase of size using # symbols and spaces. Explanation The staircase is right-aligned, composed of # symbols and spaces, and has a height and width of n = 10.
  • 18. Python workshop by Ebad ullah Qureshi Staircase - Approach 18 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Observations input n = number of lines Iterate through each line such that  line number (starting from 0) = loop counter In each line for 10 lines  number of whitespaces = 9 - loop counter  number of symbols = loop counter + 1 In each line for n lines  number of whitespaces = n-1 - loop counter  number of symbols = loop counter + 1
  • 19. Python workshop by Ebad ullah Qureshi Staircase – Source Code 19 lines = int(input('Enter the number of lines to be displayed: ')) for i in range(lines): print((lines-1-i)*' ' + '#'*(i+1)) Enter the number of lines to be displayed: 5 # ## ### #### #####
  • 20. Python workshop by Ebad ullah Qureshi Further Exploration – Try these Patterns 20
  • 21. Instructor: Ebad ullah Qureshi Email: ebadullah.qureshi@rutgers.edu N2E Coding Club Python Workshop Control Structures Complete