0% found this document useful (0 votes)
4 views

Chapter05. List and loop statements

Chapter 5 covers list and loop statements in Python, explaining how to create and manipulate lists, as well as the use of for and while loops for repetition. It provides examples of dynamically adding items to lists, accessing elements, and implementing loops for tasks such as calculating factorials and generating multiplication tables. The chapter emphasizes the importance of indentation in repeated statements and introduces conditional control loops for user interaction.

Uploaded by

atayasanov1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Chapter05. List and loop statements

Chapter 5 covers list and loop statements in Python, explaining how to create and manipulate lists, as well as the use of for and while loops for repetition. It provides examples of dynamically adding items to lists, accessing elements, and implementing loops for tasks such as calculating factorials and generating multiplication tables. The chapter emphasizes the importance of indentation in repeated statements and introduces conditional control loops for user interaction.

Uploaded by

atayasanov1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Chapter 5.

List and loop statements


List
• List: Collect various data and store them in one bundle.

slist = [ 'English', 'Math', 'Social Studies', 'Science' ]

"Social
"English" "Math" "Science"
Stuies"
Dynamically add items to a list
• After creating an empty list, add values to the list with code.

list = []
list.append(1)
list.append(2)
list.append(6)
list.append(3)

print(list)

[1, 2, 6, 3]
Accessing list elements
slist = [ 'English', 'Math', 'Social Studies', 'Science' ]
print(slist[0])

English

"Social
"English" "Math" "Science"
Stuies"
Lab: Creating a list of friends

• Let's write a program that stores the names of your five


closest friends in a list and then prints them out.

Enter your friend's name : Azamat


Enter your friend's name : Alexander
Enter your friend's name : Nuruбек
Enter your friend's name : Nulian
Enter your friend's name : Aibek

['Azamat','Alexander','Nuruбек','Nulian','Aibek'']
Solution

friend_list = [ ]
friend = input("Enter your friend's name : ")
friend_list.append(friend)
friend = input("Enter your friend's name : ")
friend_list.append(friend)
friend = input("Enter your friend's name : ")
friend_list.append(friend)
friend = input("Enter your friend's name : ")
friend_list.append(friend)
friend = input("Enter your friend's name : ")
friend_list.append(friend)

print(friend_list)
What is loop statements?
• Iteration is a structure that repeats the same sentence multiple times.
• Unlike humans,computers can perform repetitive tasks quickly and
without mistakes.
• This is the greatest advantage of computers.
Why is repetition important?
• As an example, let's say an important guest comes to the company
and the large screen displays "Welcome!" five times.

Welcome to our company!


Welcome to our company!
Welcome to our company!
Welcome to our company!
Welcome to our company!
What if you have to repeat it 1000 times?

Welcome to our company!


Welcome to our company!
Welcome to our company!
Welcome to our company!
Welcome to our company! Copy and paste 1000 times?
...
...
Welcome to our company!
What if you have to repeat it 1000 times?

• You must use a repeating structure.

Structure that repeats 1000 times

for i in range(1000):
print("Welcome to our company!")
Repeat count control

• In Python, controlled repetition is also called a for loop.

for i in [1, 2, 3, 4, 5]: # must have : at the end


print(" Welcome to our company!") # must be indented

print("Welcome to our company!")

Repeat 5
times
and get
out!
Repeat count control

• Let's write a program that stores the names of your five


closest friends in a list and then prints them out.

for i in [1, 2, 3, 4, 5]: # must have : at the end


print(" Welcome to our company!") # must be indented

Welcome to our company!


Welcome to our company!
Welcome to our company! It repeats with i changing from 1 to 5.
Welcome to our company!
Welcome to our company!
Let's print the value of i.

for i in [1, 2, 3, 4, 5]:


print("i=", i)

i= 1
i= 2
i= 3
i= 4
i= 5
Let's print out the multiplication table.

for i in [1, 2, 3, 4, 5]:


print("9*", i, "=", 9*i)

9* 1 = 9
9* 2 = 18
9* 3 = 27
9* 4 = 36
9* 5 = 45
range() function

For statement

Returns a number from 0 to (the end value - 1).

for Variable in range( End value ) :


sentence

Repeated sentences should be indented.


range() function

for i in range(5):
print("Welcome to our company!")

Welcome to our company!


Welcome to our company!
Welcome to our company!
Welcome to our company!
Welcome to our company!
range() function

range() function

It is a starting value. It is an end value, but A range value that


does not include "stop". increases stepwise.

range(start=0, stop, step=1)

for loop
Lab: Calculating Factorials

• Let's calculate the factorial using a for loop.


• Factorial n! means the product of all integers from 1 to n.
• That is, n! = 1×2×3×… … ×(n-1)×n.

Enter an integer: 10
10! is 3628800.
Solution

n = int(input("Enter an integer : "))

fact = 1
for i in range(1, n+1):
fact = fact * i
print(n, "! is", fact, ".")
Conditional Control Loop

• Conditional control loop is a structure that repeats while a certain


condition is satisfied.

reseponse
= input("Mom, are you done?")

response=="No"
response="No" print("Let's eat")

True
False
while statement

while loop
This is the condition for repetition.
If the condition is true, repetition
while condition : continues.

Repeated sentences

It's a repetitive
sentence.
while statement
reseponse
= input("Mom, are you done?")

response=="No"
response="No" print("Let's eat")

True
False

response = "No"
while response == "No":
response = input("Mom, are you done?");
print("Let's eat")
Example

• Let's say the user enters a password and the program checks
whether the password is correct.

Please enter your password: idontknow


Please enter your password: 12345678
Please enter your password: password
Please enter your password: pythonisfun
12345678
Login successful
Example

password = ""
while password != "pythonisfun":
password = input("Please enter your password :")
print("Login successful")

12345678
Example

• For example, let's write an example that calculates the sum from 1 to
10 using a while loop.

The total is 55
Example

count = 1
sum = 0
while count <= 10 :
sum = sum + count
count = count + 1
print("The total is", sum)
Lab: Multiplication table output
• Let's print the 9th multiplication table using a repeating statement. If
we repeat 9*1, 9*2, 9*3, .., 9*9 9 times, we can print it.

The desired section is : 9


9*1=9
9*2=18
9*3=27
9*4=36
9*5=45
9*6=54
9*7=63
9*8=72
9*9=81
Solution

dan = int(input("The desired section is : "))


i=1

while i <= 9:
print("%s*%s=%s" % (dan, i, dan*i))
i=i+1

Challenge problem

Let's modify the above program to print all the numbers from 1 to 9 in the multiplication
table.
Lab: Calculate the sum of numbers entered by the user
• Let's write a program that adds the numbers entered by the user. It
only accepts numbers while the user answers yes.

Enter a number: 10
Continue? (yes/no): yes
Enter a number: 20
Continue? (yes/no): no
Total is: 30
Hint

1. Set total to 0.
2. Set answer to ‘yes’.
3. While answer is ‘yes’, repeat the following:
* Enter a number.
* Add the number to total.
* Ask ‘Continue? yes/no’.
4. Print the value of total.
Solution

total = 0
answer = "yes"
while answer == "yes":
number = int(input("Enter a number: "))
total = total + number
answer = input("Continue? (yes/no): ")
print("Total is: ", total)
Lab: Number Matching Game
• This example is a game where the user guesses the integer that the
program has. When the user provides an answer, the program
compares it to the integer it has stored and simply tells whether the
given integer is higher or lower.

Guess a number between 1 and 100


Enter a number: 50
Low!
Enter a number: 86
Low!
Enter a number: 87
Congratulations. Attempts = 6
Hint

while guess != answer


Get a number from the user as guess.
Increase the number of attempts.
if( guess < answer )
Print if the number is low.
if( guess > answer )
Print if the number is high.
Print "Congratulations" and the number of attempts.
Solution
import random

tries = 0
guess = 0;
answer = random.randint(1, 100)
print("Guess a number between 1 and 100")

while guess != answer:


guess = int(input("Enter a number: "))
trys = tries + 1
if guess < answer:
print("Low!")
elif guess > answer:
print("High!")

if guess == answer:
print("Congratulations. Number of attempts=", tries)
else:
print("The answer is ", answer)
Challenge Problem

• How would I change the above program to limit the number of


attempts to 10?
Lab: Math Problem Generator for Elementary School Students

• Let's write a program that generates arithmetic problems for


elementary school students.

9 + 48 = 57
Good job!!
65 + 11 = 76
Good job!!
91 + 31 = 11
Can you do better next time?
38 + 4 =
Solution
import random

while True:
x = random.randint(1, 100)
y = random.randint(1, 100)
print(x, "+", y, "=", end= " ")
answer = int(input())
if answer == x + y:
print("Good job!!")
else:
print("You can do better next time, right?")
Challenge Problem

• How would I change the above program to limit the number of


attempts to 10?
Lab: Print all types of sandwiches
• Let's say we run a sandwich shop. We want to print out all the
different types of sandwiches available in our shop.

Rye Bread + Mat Ball + Lettuce + Mayonnaise


Rye Bread + Mat Ball + Lettuce + Honey Mustard
Rye Bread + Mat Ball + Lettuce + Chili
Rye Bread + Mat Ball + Tomato + Mayonnaise
Rye Bread + Mat Ball + Tomato + Honey Mustard
Rye Bread + Mat Ball + Tomato + Chili

Solution
breads = ["rye bread", "wheat", "white" ]
meats = ["martball", "sausage", "chicken breast"]
vegis = ["lettuce", "tomato", "cucumber"]
sauces = ["mayonnaise", "honey mustard", "chili"]

for b in breads:
for m in meats:
for v in vegis:
for s in sauces:
print(b+"+"+m+"+"+v+"+"+s)
Infinite loop and break

• In conditional control loops, we sometimes use a loop that repeats


infinitely. This is called an infinite loop.

while Ture:
Repeated sentences
Repeated sentences
if condition :
break;

• The break statement is used to forcefully exit a loop.


Infinite loop and break

• If the repeat conditions are complex, it is a good idea to create an


infinite loop and execute break when a certain condition is met to
exit the infinite loop.

while True:
light = input('Enter the traffic light color')
if light == 'blue':
break
print('Forward!!')
Lab: Fortune-telling game

• Let's write a program that reads a user's fortune when the user asks
a question.

Name: (Enter to exit) Hong Gil-dong


What do you want to know? Will I get a job?
Mr. Hong Gil-dong, you asked about "Will I get a job?"
I'll roll the dice of fate...
Without a single doubt, you are right.
Hint

After generating a random number between 1 and 8, you can use an


if-else structure to produce different answers depending on the value
of the random number.
Solution
import sys
import random

while True:
name = input("Name: (Enter to exit) ")

if name == "":
sys.exit()

question = input("What do you want to know about?")


print(name+ "님" , "\"", question, "\", you asked a question.")
print("I'll roll the dice...")

answers = random.randint(1, 8)
if answers == 1:
print ("Yes, I'm sure.")

elif answers == 2:
print ("It looks like a good prospect.")

elif answers == 3:
print ("You can trust it.")

elif answers == 4:
print ("Well, I don't think so.")

elif answers == 5:
print ("It's right, without a doubt.")

elif answers == 6:
print ("Yes, you made the right choice.")

elif answers == 7:
print ("My answer is No.")

else :
print ("Ask me again later.")
What we learned in this chapter

• Lists can be used to store data.


• To repeatedly execute statements, use for or
while.
• The statements that are repeatedly executed
must be indented.
• The for statement is useful when the
number of repetitions is fixed.
• The while statement is useful when the
repetition condition is fixed.
• The condition is checked at the beginning of
the loop.

You might also like