首页 > 解决方案 > 如何使 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 循环。

标签: pythonpython-3.xfor-loop

解决方案


使用单独的变量然后 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.")
        

推荐阅读