首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么这段代码不能打破python中的while True循环呢?

为什么这段代码不能打破python中的while True循环呢?
EN

Stack Overflow用户
提问于 2020-07-26 16:07:51
回答 4查看 51关注 0票数 0

今天早些时候刚开始学习python,我不明白如果输入"N“,为什么这段代码不会结束程序。另外,如果我将最后一条if语句改为!= "Y“,那么即使我键入Y,它也会关闭,这让我非常困惑。我只是想做一个简单的程序来转换华氏温度到摄氏度,如果系统提示的话,不需要查看任何代码,所以如果它写得很糟糕,这就是为什么。

代码语言:javascript
复制
while True:
    def temp_func():
        print("Is the temperature you'd like to convert in Fahrenheit or Celcius?")
        temp = input()
        if temp == "Fahrenheit":
            F_temp = int(input("Please write the temperature."))
            converted_temp_F = ((F_temp - 32) * 5 / 9)
            print(str(converted_temp_F))
        elif temp == "Celcius":
            C_temp = int(input("Please write the temperature."))
            converted_temp_C = ((C_temp * (9 / 5)) + 32)
            print(str(converted_temp_C))

    temp_func()
    print(input("Would you like to convert another temperature? (Y/N) "))
    if input == 'Y':
        True
    if input == 'N':
        break
print ("Goodbye")
EN

回答 4

Stack Overflow用户

发布于 2020-07-26 16:14:06

更换您的打印(输入...和条件:

代码语言:javascript
复制
 response = input("Would you like to convert another temperature? (Y/N) ").upper()
 if response == 'N':
    break
票数 1
EN

Stack Overflow用户

发布于 2020-07-26 16:11:36

您需要将用户给定的输入值存储在Y/N的变量中。您应该将该函数移出while循环

代码语言:javascript
复制
def temp_func():
    print("Is the temperature you'd like to convert in Fahrenheit or Celcius?")
    temp = input()
    if temp == "Fahrenheit":
        F_temp = int(input("Please write the temperature."))
        converted_temp_F = ((F_temp - 32) * 5 / 9)
        print(str(converted_temp_F))
    elif temp == "Celcius":
        C_temp = int(input("Please write the temperature."))
        converted_temp_C = ((C_temp * (9 / 5)) + 32)
        print(str(converted_temp_C))

while True:
    temp_func()
    Y_N = input("Would you like to convert another temperature? (Y/N) ")
    if Y_N == 'N':
        break
print ("Goodbye")
票数 0
EN

Stack Overflow用户

发布于 2020-07-26 16:13:58

试着这样做

代码语言:javascript
复制
def temp_func():
    print("Is the temperature you'd like to convert in Fahrenheit or Celcius?")
    temp = input()
    if temp == "Fahrenheit":
        F_temp = int(input("Please write the temperature."))
        converted_temp_F = ((F_temp - 32) * 5 / 9)
        print(str(converted_temp_F))
    elif temp == "Celcius":
        C_temp = int(input("Please write the temperature."))
        converted_temp_C = ((C_temp * (9 / 5)) + 32)
        print(str(converted_temp_C))

while True:

    temp_func()
    x = input("Would you like to convert another temperature? (Y/N) ")
    if x.lower() == "n":
        break
    
print ("Goodbye")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63097644

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档