2017-10-11 68 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']: 
相关问题