Simple while loop until break in Python

感情迁移 提交于 2019-12-30 12:36:10

问题


What would a very simple while loop statement be that would continue the below program until the user types "exit"?

For example,

while response = (!'exit')
    continue file
else
    break
    print ('Thank you, good bye!')
#I know this is completely wrong, but it's a try!

My file so far:

#!/usr/bin/python
friends = {'John' : {'phone' : '0401',
        'birthday' : '31 July',
        'address' : 'UK',
        'interests' : ['a', 'b', 'c']},
    'Harry' : {'phone' : '0402',
        'birthday' : '2 August',
        'address' : 'Hungary',
        'interests' : ['d', 'e', 'f']}}
response = raw_input("Please enter search criteria, or type 'exit' to exit the program: ").split()
try:
    print "%s's %s is %s" % (response[0], response[1], friends[response[0]][response[1]])
except KeyError:
    print "Sorry, I don't know about that. Please try again, or type 'exit' to leave the program: "

回答1:


Your while loop will continue until the condition you've set is false. So you want your code to mostly be inside this loop. Once it's finished, you know the user entered 'exit' so you can print the error message.

#!/usr/bin/python
friends = {'John' : {'phone' : '0401',
        'birthday' : '31 July',
        'address' : 'UK',
        'interests' : ['a', 'b', 'c']},
    'Harry' : {'phone' : '0402',
        'birthday' : '2 August',
        'address' : 'Hungary',
        'interests' : ['d', 'e', 'f']}}

response = ['']
error_message = "Sorry, I don't know about that. Please try again, or type 'exit' to leave the program: "

while response[0] != 'exit':
    response = raw_input("Please enter search criteria, or type 'exit' to exit the program: ").split()
    try:
        print "%s's %s is %s" % (response[0], response[1], friends[response[0]][response[1]])
    except KeyError:
        print error_message
    except IndexError:
        print error_message

print ('Thank you, good bye!')

This code is a start to what you want, but it still has some bugs. See if you can restructure it so the error message isn't printed when the user enters 'exit'.




回答2:


continue is a keyword that requires no arguments. It simply tells the current loop to continue immediately to the next iteration. It can be used inside of while and for loops.

Your code should then be placed within the while loop, which will keep going until the condition is met. Your condition syntax is not correct. It should read while response != 'exit':. Because you are using a condition, the continue statement is not needed. It will by design continue as long as the value is not "exit".

Your structure would then look like this:

response = ''
# this will loop until response is not "exit"
while response != 'exit':
    response = raw_input("foo")

If you wanted to make use of continue, it might be used if you were going to do other various operations on the response, and might need to stop early and try again. The break keyword is a similar way to act on the loop, but it instead says we should immediately end the loop completely. You might have some other condition that is a deal breaker:

while response != 'exit':
    response = raw_input("foo")

    # make various checks on the response value
    # obviously "exit" is less than 10 chars, but these
    # are just arbitrary examples
    if len(response) < 10:
        print "Must be greater than 10 characters!"
        continue  # this will try again 

    # otherwise
    # do more stuff here
    if response.isdigit():
        print "I hate numbers! Unacceptable! You are done."
        break



回答3:


#!/usr/bin/python
friends = {
    'John' : {
        'phone' : '0401',
        'birthday' : '31 July',
        'address' : 'UK',
        'interests' : ['a', 'b', 'c']
    },
    'Harry' : {
        'phone' : '0402',
        'birthday' : '2 August',
        'address' : 'Hungary',
        'interests' : ['d', 'e', 'f']
    }
}

def main():
    while True:
        res = raw_input("Please enter search criteria, or type 'exit' to exit the program: ")
        if res=="exit":
            break
        else:
            name,val = res.split()
            if name not in friends:
                print("I don't know anyone called {}".format(name))
            elif val not in friends[name]:
                print("{} doesn't have a {}".format(name, val))
            else:
                print("{}'s {} is {}".format(name, val, friends[name][val]))

if __name__=="__main__":
    main()


来源:https://stackoverflow.com/questions/10458049/simple-while-loop-until-break-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!