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

02 Control Structures - Loops & Conditions

  • 1.
    Instructor: Ebad ullahQureshi Email: ebadullah.qureshi@rutgers.edu N2E Coding Club Python Workshop Control Structures Loops & Conditionals
  • 2.
    Python workshop byEbad 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 byEbad 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 byEbad 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 byEbad 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 byEbad 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 byEbad 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 byEbad 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 byEbad 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 byEbad 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 byEbad 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 byEbad 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 byEbad 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 byEbad 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 byEbad 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 byEbad 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 byEbad 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 byEbad 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 byEbad 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 byEbad ullah Qureshi Further Exploration – Try these Patterns 20
  • 21.
    Instructor: Ebad ullahQureshi Email: ebadullah.qureshi@rutgers.edu N2E Coding Club Python Workshop Control Structures Complete