【问题标题】:How do i loop my program?我如何循环我的程序?
【发布时间】:2017-04-10 00:35:45
【问题描述】:

我无法弄清楚如何循环我的程序以返回您输入值的起点。任何建议都会有所帮助,我是编程新手。 (python 2.17, 翼 ide 101 6.0)

#This program converts the users temperature in celsius to fahenheit
import math

print "X" * 46
print "Temperature Converter"
print "Press 1 for Celsius to Fahrenheit"
print "Press 2 for Fahrenheit to Celsius"
print "Press 3 for Celsius to Kelvin"
print "Press 4 for Fahrenheit to Kelvin"
print "X" * 46


choice = input("Enter a value ")

#converts celsius to fahrenheit
if choice == 1:
    print "1. Celsius to Fahrenheit"
    CtoF = input("Temperature in Celsius? ")
    tempF = round((CtoF * 1.8) + 32)
    print "Your temperature in Fahrenheit is", tempF, "°"

#converts fahrenheit to celsius
if choice == 2:
    print "2. Fahrenheit to Celsius"
    FtoC = input("Temperature in Celsius? ")
    tempC = round((FtoC - 32) / 1.8)
    print "Your temperature in Celsius is", tempC, "°"

#Converts celsius to kelvin 
if choice == 3:
    print "3. Celsius to Kelvin"
    CtoK = input("Temperature in Celsius? ")
    tempK = round(CtoK + 273.15)
    print "Your temperature in Kelvin is", tempK

#converts fahrenheit to celsius, then to kelvin
if choice == 4:
    print "4. Fahrenheit to Kelvin"
    FtoK = input("Temperature in Fahrenheit? ")
    FtokC = ((FtoK - 32) / 1.8)
    Ftok = round(FtokC + 273.15)
    print "Your temperature in Kelvin is", Ftok

【问题讨论】:

  • 阅读while 循环和for 循环

标签: python python-2.7 loops calculator


【解决方案1】:

例如,您可以在开始消息中添加“输入 0 退出”。
然后,您将从choice = input(...)(包括这一行)开始的所有内容放入while (True): 循环中。
最后在最后加上if choice == 0: break就好了。

【讨论】:

  • @QuintenChokrev-evans 你应该在 while 循环中添加这一行。此外,您当然应该在换行符中写入break另外,别让我猜——写下你的错误。仅供参考,python 代码中可能有超过 9000 个不同的错误。所以下次写错误
【解决方案2】:

像计算机一样处理您的代码:

1) 考虑你想从哪里开始循环

2) 设置你的循环条件。除非你明确地传达它,否则计算机不知道你想要什么;你想让它永远循环吗?直到有事发生?沟通如何、是否以及何时停止。

我建议您阅读有关 While 循环的 python 文档;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-06
    • 2012-01-18
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多