Как сделать, если оператор проверяет каждый оператор цикла на наличие допустимых входных данных

#python #python-3.x #for-loop

Вопрос:

 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 до сбоя. Для цикла требуется.

Ответ №1:

Вы можете добавить счетчик, который будет отслеживать количество попыток, сделанных пользователем до сих пор.

Также необходимо преобразовать пользовательский ввод из строки в тип int.

 import random
max_value = int(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))
count = 0
for (computer_choice) in range(1,6):
    user_choice = int(input("What number between 1 and "   max_value   " do you choose? "))
    count  = 1
    if user_choice == computer_choice:
        print("Thank you for playing. ")
    if count==5:
         print("you have reached maximum attempt limit")
         exit(0)
 

Ответ №2:

Запустите цикл for с отдельной переменной, затем computer_choice. Также добавьте eval к оператору ввода, поскольку он дает строку для преобразования user_choice в целое число, и добавьте оператор break, если user_choice == computer_choice для завершения программы, 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.")
        
 

Ответ №3:

Один из подходов:

 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):
    user_choice = input("What number between 1 and "   max_value   " do you choose? ")
    if int(user_choice) == int(computer_choice):
        print("Right choice. Thank you for playing. ")
        break
    elif(i == 5):
        print ("Sorry, maximum attempts reached...")
        break
    else:
        print ("Oops, wrong choice, pls choose again...")
 

Выход:

 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? 5
What number between 1 and 5 do you choose? 1
Oops, wrong choice, pls choose again...
What number between 1 and 5 do you choose? 3
Oops, wrong choice, pls choose again...
What number between 1 and 5 do you choose? 4
Oops, wrong choice, pls choose again...
What number between 1 and 5 do you choose? 5
Oops, wrong choice, pls choose again...
What number between 1 and 5 do you choose? 6
Sorry, maximum attempts reached...