python - 如何使 if 语句检查每个 for 循环语句的有效输入
问题描述
import random
max_value = input("I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? ")
computer_choice = random.randint(1, int(max_value))
for (computer_choice) in range(1,6):
user_choice = input("What number between 1 and " + max_value + " do you choose? ")
if user_choice == computer_choice:
print("Thank you for playing. ")
失败前需要给用户 5 次机会给 computer_choice。需要 for 循环。
解决方案
使用单独的变量然后 computer_choice 运行 for 循环。还要将 eval 添加到输入语句,因为它提供字符串以将 user_choice 转换为整数,并在 if user_choice == computer_choice 中添加一个 break 语句来结束程序,rest 应该可以正常工作。
import random
max_value = input("I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? ")
computer_choice = random.randint(1, int(max_value))
for (i) in range(1,6):
#input takes string convert choice to int using eval
user_choice = eval(input("What number between 1 and " + max_value + " do you choose? "))
if user_choice == computer_choice:
print("Thank you for playing. ")
break
if(i==5):
print("Sorry, maximum number of tries reached.")
推荐阅读
- scala - Databricks 中的高并发集群
- mysql - 如何水平连接两个不同的表(没有交叉连接)
- google-chrome-devtools - Nativescript-Vue 7 - 创建新项目后,我在 google chrome devtools 中看不到网络活动
- python - GeoPandas 在使用 to_file 时不保存完整的几何图形
- c# - 如何通过存储过程将 GUID 参数传递给 SQL Server?
- c# - wpf中的货币格式
- arrays - 如何在 id 数组中查找相同的集合?
- python-3.x - discord.py 在会员加入时发送 pm
- python - 多处理代码未显示所需结果
- ssl - 读取 SSL PEM 生成的文件以获取证书到期日期