Condition control
if statement
# if 条件表达式:
# 代码块
a = False
if a:
print('True')
if-else statement
a = False
if a:
print('True')
else:
print('False')
if-elif-else statement
value = 30000
if value >= 30000:
print('有钱任性')
elif value >= 20000:
print('有钱真好')
elif value >= 10000:
print('工资还说的过去')
else:
print('苦')
input() function
- This function is used to get user input
- After input() is called, the program will immediately pause, waiting for user input
- After the user enters the content, the program will continue to execute downward after clicking Enter
- After the user's input is completed, the content entered will be returned in the form of return value
Loop control
while statement
# 语法
# while 条件表达式:
# 代码块
# else:
# 代码块
break和continue
- break can be used to immediately exit the loop statement, including the else statement
- continue is used to skip the original loop
operation
Find the number of daffodils within 1000
for i in range(100, 1000):
m = i // 100 #整除获得百位数
n = (i % 100) // 10 #十位数
k = i % 10 #个位数
if m**3 + n ** 3 + k ** 3 == i:
print(i)
Get any number entered by the user and determine whether it is a prime number?
num = int(input("请输入一个数字: "))
is_ok = True
count = 2
if num > 1:
while is_ok:
if count >= num:
is_ok = False
else:
if (num % count) == 0:
print(num, "不是质数")
print(f"{count} 乘于 {num // count} = {num}")
break
count += 1
else:
print(f"{num}是质数")
else:
print(f"{num}不是质数")
Guessing game:
- Punch player: manual input computer: random input
- Judging the winner: the player wins the computer wins the draw
import random
while True:
c = random.randint(1, 3)
c_str = ''
print("**************************************************")
u = int(input("1. 石头、\t2. 剪刀\t3. 布\t0. 退出\t请选择:"))
u_str = ''
if u == 0:
break
else:
if c == 1:
c_str = "石头"
elif c == 2:
c_str = "剪刀"
else:
c_str = "布"
if u == 1:
u_str = "石头"
elif u == 2:
u_str = "剪刀"
else:
u_str = "布"
print(f"电脑: {c_str}")
print(f"玩家: {u_str}")
if c == u:
print("平局")
elif u - c == -1 or u - c == 2:
print("恭喜你赢了")
else:
print("你输了")
input("任意键从来")
print("游戏结束")