2017-10-11 22 views
1

有一段代碼可將用戶輸入的內容更改爲小寫,我如何將此代碼實現爲我的代碼而不是使用[「a」或「A」]?將用戶輸入更改爲小寫的代碼

def displaymenu(): 
    print("Weather station") 
    print("Please enter the option you would like") 
    optionchoice = input("Please enter A,B,C or D:") 

    if optionchoice in ["a" or "A"]: 
     print("The temperature will be displayed") 
     time.sleep(1) 
     optionA() 

    elif optionchoice in ["b" or "B"]: 
     print("The wind speed will be displayed") 
     time.sleep(1) 
     optionB() 

    elif optionchoice in ["c" or "C"]: 
     print("The day and time will be displayed") 
     time.sleep(1) 
     optionC() 

    elif optionchoice in ["d" or "D"]: 
     print("The Location will be displayed") 
     time.sleep(1) 
     optionD() 

    else: 
     print("Please type a valid input") 
     displaymenu() 
+3

你可以使用'.lower()'強制它小寫 – GreenSaber

+0

我怎樣才能把這個放到我的代碼中,我不完全確定 –

+0

'optionchoice = input(「請輸入A,B,C或D:」)。 ()' –

回答

1

嘗試是這樣的:

optionchoice = input("Please enter A,B,C or D:").lower()

這樣你正迫使輸入任何用戶類型的小寫版本。

0

,如果你使用Python 2,你應該使用raw_input().lower()

0

使用str.lower()方法,你可以更改您的代碼如下所示:

def displaymenu(): 
    print("Weather station") 
    print("Please enter the option you would like") 

    optionchoice = input("Please enter A, B, C or D: ").lower() # Convert input to lowercase. 

    if optionchoice == 'a': 
     print("The temperature will be displayed") 
     time.sleep(1) 
     optionA() 

    elif optionchoice == 'b': 
     print("The wind speed will be displayed") 
     time.sleep(1) 
     optionB() 

    elif optionchoice == 'c': 
     print("The day and time will be displayed") 
     time.sleep(1) 
     optionC() 

    elif optionchoice == 'd': 
     print("The Location will be displayed") 
     time.sleep(1) 
     optionD() 

    else: 
     print("Please type a valid input") 
     displaymenu() 

如果您要堅持你的版本某種原因,驗證像這樣輸入:

if optionchoice in ['a', 'A']: 
相關問題