首页 > 解决方案 > 华氏或摄氏 Python 程序不断重复

问题描述

我是编码新手,我正在尝试在摄氏度和华氏度之间建立一个简单的转换,但我一直遇到问题。如果我运行程序并键入并按回车键,则不会发生任何事情,否则会出现其他错误。我非常感谢您的帮助,并尽可能多地解释,以便我学习。

#!/usr/bin/python3

def fahrenheitToCelsius(fahrenheit):
     celsius = (fahrenheit - 32.0) * (5.0/9.0)
     return celsius

def celsiusToFahrenheit(celsius):
   fahrenheit = (9.0/5.0) * celsius + 32.0
   return fahrenheit

print('Welcome')

userInput = 0

while userInput != 3 :
   userInput = input('''Main Menu 
   1:Fahrenheit to Celsius
   2:Celsius to Fahrenheit
   3:Exit program
   Please enter 1, 2 or 3:''')

if userInput == 1:
   fahren = input('\nPlease enter degrees Fahrenheit: ')

   try:
       fahren = float(fahren)
   except:
       print('Sorry, %s is not a valid number' % fahren)
       exit(1)
    
cels = fahrenheitToCelsius(fahren)

print('%s degrees Fahrenheit equals %d degrees Celsius' % fahren % cels)

elif userInput == 2:
    cels = input('\nPlease enter degrees Celsius: ')

    try:
        cels = float(cels)
    except:
        print('\nSorry, %s is not a valid number' % cels)
        exit(1)

    fahren = celsiusToFahrenheit(cels)

    else:
        print('Invalid entry')

标签: python-3.x

解决方案


Python 不会自动将接收input()到的值转换为它们各自的类型。(Python 2 做到了这一点,所以混乱可能源于那里)。因此,您收到的号码仍然是str. "3"永远不等于3。最简单的方法是简单地将输入转换为一个数字,方法是将其包装在int函数中:

userInput = int(input('...'))

你应该把它包起来try——except就像你输入温度一样——但一定要添加一个continue语句。(它所做的只是转到循环的开头,有效地“重试”输入)。

try:
    userInput = int(input('...'))
except:
    print('Invalid number!')
    continue

您忘记的一件小事是缩进语句,以 . 开头if userInput == 1。这样,它们将在循环外执行。


推荐阅读