2016-06-15 104 views
0

特定输入如何在python获取特定的输入如获取蟒蛇

variable = input() 
if variable == "Specific input": 
    do stuff 

我需要的输入视为两个选项之一说XO

+0

你能更具体地了解你的问题吗?如果您只想在输入是x或o时执行某些操作,则需要检查它们。 –

+0

你的代码有什么问题?它应该工作得很好。你不能强迫用户给你特定的输入。您可以使用'while'循环来检查'variable'是否是'x'和'o'中的一个,否则保持提示输入正确。 – SvbZ3r0

回答

1

其简单的例子来使用特定的变量: 这是简单的代码对于英寸到厘米厘米到英寸之间转换:

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!!") 
0

定义列表

specific_input = [0, 'x'] 

if variable in specific_input: 
    do awesome_stuff 
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)) 

应该要么蟒蛇v2和v3不变的工作(有问题及输入()在Python v2的威力没有迹象不是一个好主意......

在Python 3.5.1运行上面的代码:

$ python3 so_x_input_loop.py 
One of (yes, no)> why 
One of (yes, no)> yes 
Received yes 

通过控制-C突围:

$ python3 so_x_input_loop.py 
One of (yes, no)> ^C 

当它是明确的,在哪个版本,说蟒蛇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)) 
0

最简单的解决办法是:

variable = input("Enter x or y") acceptedVals = ['x','y'] if variable in acceptedVals: do stuff

或者,如果你想不断提示用户正确使用一段时间循环 acceptedVals = ['x','y'] while variable not in acceptedVals variable = input("Enter x or y") do stuff