Chapter05. List and loop statements
Chapter05. List and loop statements
"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
['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.
for i in range(1000):
print("Welcome to our company!")
Repeat count control
Repeat 5
times
and get
out!
Repeat count control
i= 1
i= 2
i= 3
i= 4
i= 5
Let's print out the multiplication table.
9* 1 = 9
9* 2 = 18
9* 3 = 27
9* 4 = 36
9* 5 = 45
range() function
For statement
for i in range(5):
print("Welcome to our company!")
range() function
for loop
Lab: Calculating Factorials
Enter an integer: 10
10! is 3628800.
Solution
fact = 1
for i in range(1, n+1):
fact = fact * i
print(n, "! is", fact, ".")
Conditional Control Loop
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.
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.
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.
tries = 0
guess = 0;
answer = random.randint(1, 100)
print("Guess a number between 1 and 100")
if guess == answer:
print("Congratulations. Number of attempts=", tries)
else:
print("The answer is ", answer)
Challenge Problem
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
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
while Ture:
Repeated sentences
Repeated sentences
if condition :
break;
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.
while True:
name = input("Name: (Enter to exit) ")
if name == "":
sys.exit()
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