“笨办法”学Python 3基础篇 - 数据容器与程序结构

7 篇文章 10 订阅

4.1 程序逻辑结构-分支 if、elif、else

4.1.2 让我们来做一个简易口算训练器

1. 用随机数生成口算的操作数；
2. 用随机数和分支结构生成运算符(加法和减法)；
3. 用函数求出正确答案；
4. 提问与等待解答；
5. 分支结构判断口算结果，做出对错决定。

4.1.2.1 随机数 - random用法

• random.random() : 返回生成的一个实数，在[0,1)范围内；
• random.uniform(num1,num2) : 返回生成的一个实数，范围在[num1,num2)之间；
• random.randint(num1,num2): 返回生成的一个整数，范围为num1到num2。

import random

print(random.random())
print(random.random()*100)
print(random.uniform(100,101))
print(random.randint(0,100))


4.1.2.2 生成随机运算符 - if + else + random

if 随机数处于[0,50) :

else :

import random

def gen():
op1 = random.randint(0, 100)
op2 = random.randint(0, 100)
op3 = random.random()*100
if op3 < 50:
elif op3 >= 50 and op1 >= op2:
return sub(op1, op2)
else:
return sub(op2, op1)


4.1.2.3 运算函数

• print 当前算式
• 等待输入口算结果
• 分支结构判断结果
• print 运算结果

from sys import exit

print(f"{augend} + {addend} = ", end = "")
result = int(input())
if result == augend + addend:
print(f"The result is true.")
exit(0)
else:
print(f"The result is false.")
exit(0)

def sub(augend, subend):
print(f"{augend} - {subend} = ", end = "")
result = int(input())
if result == augend - subend:
print(f"The result is true.")
exit(0)
else:
print(f"The result is false.")
exit(0)


4.1.2.4 综合

from sys import exit
import random

def gen():
op1 = random.randint(0, 100)
op2 = random.randint(0, 100)
op3 = random.random()*100
if op3 < 50:
elif op3 >= 50 and op1 >= op2:
return sub(op1, op2)
else:
return sub(op2, op1)

print(f"{augend} + {addend} = ", end = "")
result = int(input())
if result == augend + addend:
print(f"The result is true.")
exit(0)
else:
print(f"The result is false.")
exit(0)

def sub(augend, subend):
print(f"{augend} - {subend} = ", end = "")
result = int(input())
if result == augend - subend:
print(f"The result is true.")
exit(0)
else:
print(f"The result is false.")
exit(0)

print("Welcome! Are you ready to start a math test?")
print("Y/N", end='')
decide = input('> ')
if (decide == 'Y'):
gen()
else:
print("Coward!")


4.2 程序逻辑结构-循环 for 和 while

4.2.1 for + 列表

• hairs = [‘brown’, ‘blond’, ‘red’]

for 变量 in 序列：

else:

hairs = ['brown', 'blond', 'red']

for color in hairs:

for number in range(3):
print(f"My hair is {hairs[number]}, too!")


4.2.2 while + 列表

while(布尔条件)：

else：

hairs = ['brown', 'blond', 'red']
count = 0
while(count < len(hairs)):
print(f"Her hair is {hairs[count]}!")
count += 1


4.2.3 挑战一个更复杂的口算训练器

1. 用户可以设置每次训练的口算题数；
2. 用循环结构重复生成随机口算式子并计分；
3. 打印出最终正确率，并退出程序

from sys import exit
import random

def gen():
op1 = random.randint(0, 100)
op2 = random.randint(0, 100)
op3 = random.random()*100
if op3 < 50:
elif op3 >= 50 and op1 >= op2:
return sub(op1, op2)
else:
return sub(op2, op1)

print(f"{augend} + {addend} = ", end = "")
result = int(input())
if result == augend + addend:
return 1
else:
return 0

def sub(augend, subend):
print(f"{augend} - {subend} = ", end = "")
result = int(input())
if result == augend - subend:
return 1
else:
return 0

print("Welcome! Are you ready to start a math test?")
print("Y/N", end='')
decide = input('> ')
if (decide == 'N'):
print("Coward!")
exit(0)
else:
print("How many exercises do you want to try?", end='')
count = int(input('> '))
score = 0
while count != 0:
score += gen()
count -= 1
print(f"Your final test score is {score}.")
exit(0)


PoweShell的运行结果为：

4.3 更复杂的列表操作

from sys import exit
import random

def gen():
op1 = random.randint(0, 100)
op2 = random.randint(0, 100)
op3 = random.random()*100
if op3 < 50:
elif op3 >= 50 and op1 >= op2:
return sub(op1, op2)
else:
return sub(op2, op1)

print(f"{augend} + {addend} = ", end = "")
result = int(input())
if result == augend + addend:
return 1
else:
return 0

def sub(augend, subend):
print(f"{augend} - {subend} = ", end = "")
result = int(input())
if result == augend - subend:
return 1
else:
mistakes.append(f'{augend} - {subend} = {result}, the right answer is {augend - subend}')
return 0

print("Welcome! Are you ready to start a math test?")
print("Y/N", end='')
decide = input('> ')
if (decide == 'N'):
print("Coward!")
exit(0)
else:
mistakes = []
print("How many exercises do you want to try?", end='')
count = int(input('> '))
success = count
score = 0
while count != 0:
score += gen()
count -= 1
if score == success:
print(f"Congratulations! You got all exercises right!")
exit(0)
else:
print(f"Your final test score is {score}.")
print("Here is your wrong record: ")
for var in mistakes:
print(var)
exit(0)


结语

• 3
点赞
• 1
收藏
觉得还不错? 一键收藏
• 11
评论
05-28
12-27 485
02-07 1313
03-23 884
07-05 991
10-23 2692
07-05 359
10-12
04-20 391
04-17 354

“相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。