while循环使用python中的if语句

时间:2015-03-21 05:02:13

标签: loops

print ("Selection of the mode\n Easy \n Moderate \n tough")
selection = int(input("Please enter the right Choice!! > "))

while selection != '':
    if selection == 1:
        print("\ngoodluck")
    elif selection == 2:
        print('\nyou are brave')
    elif selection == 3:
        print ('\nyou must be kidding')
    selection = int(input("Please enter the right Choice!!! > "))

我正在创建一个小程序,对python是新的,所以有一些理解问题,需要知道我的错误,当用户输入正确的选择,如1或2或3时,它应该进入循环并运行如果声明。一旦完成,它应该退出。但显然这种方法并不完美。

print ("Selection of the mode\n Easy \n Moderate \n tough")
selection = input("Please enter the right Choice!! > ")

while selection != '':
    if selection == '1':
        print("\ngoodluck")
        break
    elif selection == '2':
        print('\nyou are brave')
        break
    elif selection == '3':
        print ('\nyou must be kidding')
        break
    selection = input("Please enter the right Choice!!! > ")

我现在正在执行此操作,但会查看所有if语句,但我只想在第一个选择正确的if语句后退出。

1 个答案:

答案 0 :(得分:0)

试试这个

print ("Selection of the mode\n Easy \n Moderate \n tough")
selection = int(input("Please enter the right Choice!! > "))

while selection != '':
    if selection == 1:
        print("\ngoodluck")
        break
    elif selection == 2:
        print('\nyou are brave')
        break
    elif selection == 3:
        print ('\nyou must be kidding')
        break
    selection = input("Please enter the right Choice!!! > ")

此外,多次不需要input()

print ("Selection of the mode\n Easy \n Moderate \n tough")
while True:
    selection = int(input("Please enter the right Choice!!! > "))
    if selection == 1:
        print("\ngoodluck")
        break
    elif selection == 2:
        print('\nyou are brave')
        break
    elif selection == 3:
        print ('\nyou must be kidding')
        break