【问题标题】:Trouble with break statement in While loopWhile循环中的break语句出现问题
【发布时间】:2013-11-17 06:00:57
【问题描述】:

我正在尝试编写一个从用户那里收集信息,然后输出到文本文件的程序。该程序正确收集输入,正如我插入的打印语句告诉我的那样,但是当输入指定值时,break 语句不会中断循环,并且输出文件永远不会更新。你能给出的任何建议都会很有帮助。谢谢!

# 1. Define Greeting:
def greeting():
    print("Welcome, user! Please enter the address data, or type 'quit'.")

# 2. Input
def inputData():
    name = input("Enter the name: ")
    address = input("Enter the address: ")
    city = input("Enter the city: ")
    state = input("Enter the state: ")
    zipCode = input("Enter the zip: ")
    phone = input("Enter the phone number: ")
    addressData = str(name + ", " + address + ", " +
                       city + ", " + state + ", "+ zipCode +
                       ", " + phone)
    print(addressData)
    return(name)

# 3. Write data to text file
def dataWrite():
    f.write(addressData + "\n")

# 4. Display the goodbye message:
def goodbye():
    print("Have a nice day!")

# 5. Define Main function:
def main():    
    greeting()
    while name != "quit":
         inputData()
         if name == "quit":
             break
         else:
             dataWrite()
    f.close()        
    goodbye()
main()

【问题讨论】:

  • 什么是f?你没有在任何地方定义它。在您的 main 函数中,name 未定义 - 您需要在 while 循环 之前 调用 inputData() 方法,然后保存其返回值。所以你需要name = inputData(),然后你可以做while name != 'quit':,然后不要忘记在你的内部,同时你还需要name = inputData()

标签: while-loop break python-3.3


【解决方案1】:
def main():    
    greeting()
    while name != "quit":
         name = inputData()
         if name == "quit":
             break
         else:
             dataWrite()
    f.close()        
    goodbye()

你没有得到inputData()的返回值。

【讨论】:

    猜你喜欢
    • 2016-06-22
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多