Подтверждение ввода в python - PullRequest
0 голосов
/ 27 февраля 2020

Я пытаюсь написать программу ножничного типа, где есть выбор 1, 2 и 3. Я хочу проверить ввод, чтобы любой ввод, кроме этих трех, напечатал сообщение о том, что ввод действителен, и спросил пользователь для повторного ввода данных. У меня это несколько работает, однако, даже если я введу 1 2 или 3, он все равно распечатает сообщение и попросит ввести больше.

print("This program simulates a 'rock paper scissor' game.")
print("The rules are as follows: rock beats scissor, paper beats rock, and scissor beats paper. \n")

print("This program simulates a 'rock paper scissor' game.")
print("The rules are as follows: rock beats scissor, paper beats rock, and scissor beats paper. \n")

#get user input
user_choice = input("Please choose from the following:  \n"
                    " 1 for scissor \n"
                    " 2 for rock \n"
                    " 3 for paper. \n")

#validate input so user only enters 1, 2, or 3
while user_choice != 1 or user_choice != 2 or user_choice != 3:
    user_choice = input("Please enter only '1' for scissor, '2' for rock, or '3' for paper: ")

#convert input to int 
int_user_choice = int(user_choice)

Ответы [ 4 ]

1 голос
/ 27 февраля 2020

Ваш неверен, потому что input возвращает тип string, а вы проверяли тип int, поэтому измените тип в l oop. Более того, вы не можете использовать or, если хотите, чтобы он завершился, когда один из случаев верен, в этом случае вы должны использовать and.

print("This program simulates a 'rock paper scissor' game.")
print("The rules are as follows: rock beats scissor, paper beats rock, and scissor beats paper. \n")

print("This program simulates a 'rock paper scissor' game.")
print("The rules are as follows: rock beats scissor, paper beats rock, and scissor beats paper. \n")

#get user input
user_choice = input("Please choose from the following:  \n"
                    " 1 for scissor \n"
                    " 2 for rock \n"
                    " 3 for paper. \n")

#validate input so user only enters 1, 2, or 3

while user_choice != '1' and user_choice != '2' and user_choice != '3':
    user_choice = input("Please enter only '1' for scissor, '2' for rock, or '3' for paper: ")

#convert input to int
int_user_choice = int(user_choice)
1 голос
/ 27 февраля 2020

После того, как вы получите вход, вы можете проверить, является ли оба входа действительным di git и находится ли он в допустимом диапазоне, и если одно из двух условий не выполняется, запросите еще раз

valid_choices = {1,2,3}
while not user_choice.isdigit() and not int(user_choice) in valid_choices:
   user_choice = input("Please enter only '1' for scissor, '2' for rock, or '3' for paper: ")

или более просто

valid_choices = {'1','2','3'}
while not user_choice in valid_choices:
  user_choice = input("Please enter only '1' for scissor, '2' for rock, or '3' for paper: ")
1 голос
/ 27 февраля 2020

Выполните всю подсказку / проверку в одном l oop. Пользователь не может продолжить, пока не будет выполнено условие

print("This program simulates a 'rock paper scissor' game.")
print("The rules are as follows: rock beats scissor, paper beats rock, and scissor beats paper. \n")

print("This program simulates a 'rock paper scissor' game.")
print("The rules are as follows: rock beats scissor, paper beats rock, and scissor beats paper. \n")

#get user input
while True:
    user_choice = input("Please choose from the following:  \n"
                    " 1 for scissor \n"
                    " 2 for rock \n"
                    " 3 for paper. \n")

    #validate input so user only enters 1, 2, or 3
    if user_choice in ["1", "2", "3"]:
        int_user_choice = int(user_choice)
        break
1 голос
/ 27 февраля 2020

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

user_choice = int(input("Please choose from the following:  \n"
                    " 1 for scissor \n"
                    " 2 for rock \n"
                    " 3 for paper. \n"))

и

while user_choice not in [1,2,3]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...