如何在python中获取特定输入,例如
variable = input()
if variable == "Specific input":
do stuff
我需要输入为X
或O
答案 0 :(得分:1)
使用特定变量的简单示例: 这是在Inch-to-Cm或Cm-to-Inch之间转换的简单代码:
conv = input("Please Type cm or inch?")
if conv == "cm" :
number = int(input("Please Type Your number: "))
inch = number*0.39370
print(inch)
elif conv == "inch":
number = int(input("Please Type Your Number?"))
cm = number/0.39370
print(cm)
else:
print("Wrong Turn!!")
答案 1 :(得分:0)
定义列表
specific_input = [0, 'x']
等等
if variable in specific_input:
do awesome_stuff
答案 2 :(得分:0)
我更理解关于循环相关输入的问题(正如@ SvbZ3r0在评论中指出的那样)。对于Python中的初学者来说,甚至很难从教程中复制代码,所以:
#! /usr/bin/env python
from __future__ import print_function
# HACK A DID ACK to run unchanged under Python v2 and v3+:
from platform import python_version_tuple as p_v_t
__py_version_3_plus = False if int(p_v_t()[0]) < 3 else True
v23_input = input if __py_version_3_plus else raw_input
valid_ins = ('yes', 'no')
prompt = "One of ({0})> ".format(', '.join(valid_ins))
got = None
try:
while True:
got = v23_input(prompt).strip()
if got in valid_ins:
break
else:
got = None
except KeyboardInterrupt:
print()
if got is not None:
print("Received {0}".format(got))
应该对python v2和v3保持不变(没有任何指示和Python v2中的input()可能不是一个好主意......
在Python 3.5.1中运行上述代码:
$ python3 so_x_input_loop.py
One of (yes, no)> why
One of (yes, no)> yes
Received yes
通过Control-C突破:
$ python3 so_x_input_loop.py
One of (yes, no)> ^C
如果清楚,运行哪个版本,比如python v3,那么代码可能就像这样简单:
#! /usr/bin/env python
valid_ins = ('yes', 'no')
prompt = "One of ({0})> ".format(', '.join(valid_ins))
got = None
try:
while True:
got = input(prompt).strip()
if got in valid_ins:
break
else:
got = None
except KeyboardInterrupt:
print()
if got is not None:
print("Received {0}".format(got))
答案 3 :(得分:0)
最简单的解决方案是:
variable = input("Enter x or y")
acceptedVals = ['x','y']
if variable in acceptedVals:
do stuff
或者,如果您想继续提示用户正确使用while循环
acceptedVals = ['x','y']
while variable not in acceptedVals
variable = input("Enter x or y")
do stuff