2016-06-15 112 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