python - 在python中验证输入
问题描述
我正在尝试编写一个石头剪刀布程序,其中选项是 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)
解决方案
如果您想稍后将其与整数进行比较,则需要将输入从字符串转换为整数。如果您想避免一遍又一遍地重复逻辑,您可以使用列表。
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]
推荐阅读
- haskell - Haskell 嵌套循环
- image-processing - 如何通过终端调整图像大小?
- unix - 使用文件名替换复制文件的最简单方法是什么?
- python - 为列表中的每 n 个元素选择 i-to-k 元素的 Pythonic 方法
- c# - 我想删除临时文件
- c++ - 如何在 C++ 中将地图转换为 Vec2f
- javascript - 如何导入/加载整个文件以包含在我的包中?
- html - 如何调整 SVG 标签内的路径大小,如图像
- javascript - 将 ajax 变量传递给其他 php 页面
- python-3.x - 如何创建可供其他用户使用的 Python3 自动化程序?