# Loop statement training in Python

Keywords: Python

## Loop and conditional statement training in Python

Loop statements: while loop and for loop (there is a do... While structure in C language, but it is not supported in python)

Conditional statements: if... elif... else statements (can be nested)

1. While format: (parameters in while will not increase automatically)

Format:

while judgment conditions:
Code to loop

example:

• Print 1-10
```#Print 1-10
n = 1
while n <= 10:
print(n,end ='\n')
#Variables must change
n += 1
```
• Find an integer within 1-50 that can be divided by 3
```n = 1
while n <= 50:
if n %3  == 0:
print('%d Can be divided by three'%n)
print('\n')
n += 1
```
• Find the sum of all integers between [35987]
```y = 0
j = 34
while j < 987:
j += 1
y += j
print(y)
```
• Go to the supermarket to buy things, price and quantity, allow to buy multiple goods, and calculate the total amount of all goods
```total = 0  #Total count amount
commodity_num = 0   #Count the total number of goods purchased
while True:
price = float(input('Unit price of goods:'))
number = int(input('Quantity of goods:'))
# Calculate total
total += price * number
# Calculate the total number of goods
commodity_num += number
# Determine whether to continue buying
answer = input('The current total amount of goods is:%.2f，Continue adding items( N Exit)?' % total)
break
print('Total purchase%d Pieces of goods,The total amount of all goods is:%.2f element' % (commodity_num, total))
```
• Number guessing game: you can guess many times until you get it right. If you guess wrong, give appropriate tips to guess whether it is big or small
Requirements: 1) count the total number of guesses
2) If you win at one time, hurry to buy the lottery. You must win 100 million
2-5 times, good luck
6-10 times, average luck
>10 times, what shit luck
```import random2

ran = random2.randint(1, 50)
count = 0  # Used to count the number of guesses
#print(ran)
# Loop multiple guesses
while True:
guess = int(input('Guess a 1-50 Number between:'))  # Note: input is of character type
count += 1
# Guess right and it's over
if guess == ran:
if count == 1:
print('You are a real cow! Hurry to buy the lottery. You must win 100 million!')
elif 2 <= count <= 5:
print('Good luck!')
elif 6 <= count <= 10:
print('Average luck!')
else:
print('What shit luck! Don't go out recently')
break
elif guess > ran:
print('Guess a little big Oh, let's do it again!')
else:
print('Guess a little small Oh, let's do it again!')
```
• Guessing game: with man-machine pk, the number of games is 3 times. Whoever wins more times will win the final victory
```import random2
# The computer should randomly give a number [0,2]
# You need to use the random number module random
# Random. Random (a,b) = = > random integer that can generate [a,b]

n = 3  # Total times
jiqi_num = 0  # Machine wins
hum_num = 0  # Player wins
while n > 0:
computer = random2.randint(0, 2)
# print('computer output: ', computer)
player = int(input('Please enter  (0)scissors  (1)stone  (2) Cloth:'))  # 1 = = the result is False
n -= 1  # Count the number of punches. How many more
# Prompt the user to punch
if player == 0:
print('What you gave was scissors')
if computer == 2:
print('Congratulations, you won this game!!!')
hum_num += 1
elif computer == 1:
print('You trash, you lost this game!')
jiqi_num += 1
else:
print('This game is even!')
elif player == 1:
if computer == 0:
print('Congratulations, you won this game!!!')
hum_num += 1
elif computer == 2:
print('You trash, you lost this game!')
jiqi_num += 1
else:
print('This game is even!')
elif player == 2:
print('What you gave was cloth')
if computer == 1:
print('Congratulations, you won this game!!!')
hum_num += 1
elif computer == 0:
print('You trash, you lost this game!')
jiqi_num += 1
else:
print('This game is even!')
else:
jiqi_num += 1
print("Please don't be blind jb Get out!")
print('You still have%d Second chance' % n)
if n == 0:
print('The number of times is exhausted. Let's look at the outcome:')
print('Robot player wins%d game' % jiqi_num, 'You win%d game' % hum_num)
if hum_num > jiqi_num:
print("You're still a cow!Defeated the machine")
else:
print('Give you a chance. You're useless! Shit!')
else:
print('also%d Game board' % n)

```
1. for loop statement

The for loop in python refers to the for... In... Loop structure, which is different from the for loop in C language

For statement format: for ele in iterable (variables in the for loop will increase automatically)

Note: for i in range(n):

Where, range(n): the default value is from 0 to n-1

range(start,stop,step): [start, stop) - > open left and close right

Step - > step size. The default value is 1

example:

• Enter the user name and password. If you fail to log in three times, you will be prompted that the account is locked
```# Enter the user name and password. If you fail to log in three times, you will be prompted that the account is locked
for i in range(3):
# Prompt for user name and password
# Determine whether the input is correct admin 12345
break
else:
else:  # If you haven't lost right after three chances, lock it
print('Account locked')
```

Here, pay special attention to the for... Else structure and the while... Else structure. When the for loop is completely traversed, execute the else statement. If the for loop is interrupted, else will not execute. The same is true for while... Else.

1. So when to use the while loop and when to use the for loop?

It is convenient to use for when there are fixed number of cycles and while when there are uncertain number of cycles.

2. Another example is the dice game

Dice game requirements
Two dice: 1-6
1. You should have gold coins to play games. You can't play games without gold coins
2. Play the game and give 1 gold coin as a gift. Recharge to get the gold coin
3. Each recharge is a multiple of 10 yuan, and 10 yuan can recharge 20 gold coins
4. Playing the game costs 5 gold coins
5. Guess the size: if you guess right, you will be encouraged to buy 2 gold coins. If you guess wrong, there will be no gold coins. If two dice exceed 6 points, it will be considered as large, otherwise it will be small
6. End of the game: ① active exit, ② no gold coin exit
7. Print the number of gold coins as long as you exit

```import random

coins = 0  # Number of gold coins

print('Welcome to the head iron king game!')
def recharge():
while True:
global coins  # If you want to change the value of an externally declared variable inside a function, you need to declare a global variable inside the function, and an error will occur when you declare it outside
money = int(input('Enter recharge amount:'))
# The multiple of 10 yuan can be recharged, and 20 gold coins can be recharged for every 10 yuan
if money % 10 == 0:
coins += money * 2
print('Recharge succeeded. The current number of gold coins is:%d' % coins)
choice = input('Continue to recharge?')
if choice == 'Y':
continue
else:
print('End of recharge! The current gold coin balance is:%d' % coins)
break
else:
print('Recharge amount is not a multiple of 10, failed to recharge! Please recharge again!')

# if __name__ == '__main__':
#     recharge()
welcome = True
while welcome:
if coins < 5:
recharge()
else:
choice = input('Start game?')
if choice == 'Y':  # Start the game
print('Welcome to the dice game!')
while True:
# Play a game and deduct 5 gold coins
coins -= 5
# 1 reward for playing one game
coins += 1
# After the dice are cleaned, guess the size
ran1 = random.randint(1, 6)
ran2 = random.randint(1, 6)
# Guess size
guess = input('After shuffling, please guess the size:')
if (guess == 'large' and ran1 + ran2 > 6) or (guess == 'Small' and ran1 + ran2 <= 6):
print("Congratulations, you guessed right! Get 2 rewards!")
coins += 2
choice = input('Continue the game?')
if choice == 'Y':
continue
else:
print('At the end of the game, the current gold coin balance is:%d' % coins)
break
else:
print('Unfortunately, you guessed wrong!')
choice = input('Continue the game?')
if choice == 'Y':
if coins >= 5:
continue
else:
choice =input('Insufficient gold coins, recharge or not:')
if choice == 'Y':
recharge()
else:
print('At the end of the game, the current gold coin balance is:%d' % coins)
welcome = False
break
else:
print('At the end of the game, the current gold coin balance is:%d' % coins)
welcome = False
break

else:
print('Exit the game...\n', 'Successfully quit the game!\n')
break
```

Because the code is written by myself and I just learned Python, I feel I have used if judgment many times. At present, I don't know what good method is, so it's ugly. If the boss sees it, I hope to correct it!

Posted by jmr3460 on Wed, 24 Nov 2021 21:31:02 -0800