简体   繁体   English

简单的Python临时脚本

[英]Simple Python Temp Script

I have written a very simple temp script that will prompt the user for input and spit out an answer. 我编写了一个非常简单的临时脚本,该脚本将提示用户输入并吐出答案。 As you can see below, I prompt the user to enter 1,2, or 3. 1 being fah to cel, 2 being cel to feh, and 3 to exit the program. 如您在下面看到的,我提示用户输入1,2或3。1表示Fah到cel,2表示cel到feh,3表示退出程序。 If the user enters 1 or 2, another prompt will ask them to enter the degrees they want converted. 如果用户输入1或2,则另一个提示将要求他们输入要转换的程度。 This entry is saved in variable: 此项保存在变量中:

scale

My functions I have written should calculate the float into the proper conversion and loop back to the main menu after the correct temp is printed. 我编写的函数应该将浮点数计算为正确的转换,并在打印正确的温度后循环回到主菜单。 There is some logic in the try/except statement that will attempt to convert this input into a float, and if it can't, it will print a nasty gram. 在try / except语句中有一些逻辑,它将尝试将此输入转换为浮点数,如果不能,则将输出讨厌的语法。 When I run this code, everything seems to work fine until it gets to the function call fahtoCel: 当我运行这段代码时,一切似乎都可以正常工作,直到进入函数调用fahtoCel为止:

fc = fahtoCel(scale)

I am pretty sure I have all the indenting correct and have studied declaring functions and calling them within the script. 我很确定自己所有缩进都正确,并且已经研究了声明函数并在脚本中调用它们。 My only suspicion would be my function call is within my try/except statement and perhaps that the scope is incorrect? 我唯一的怀疑是我的函数调用在我的try / except语句中,并且范围可能不正确吗? My code: 我的代码:

def fahtoCel(number):
    return(number - 32.0) * (5.0/9.0)

while True:
    x = raw_input("""Please enter 1,2 or 3: """)
    if x == "3":
        exit(0)
    if x == "1":
        scale = raw_input("""Enter degrees in Fah: """)
        try:
            scale = float(scale)
            fc = fahtoCel(scale)
        except:
            print("Invalid Entry")
        continue
    print("%.2f degrees fah equals %.2f degrees Cel" % (scale, fc))
    if x == "2":
    #Do the same for cel to fah#

continue transfers execution to the beginning of the while loop, so you never reach your print statement, regardless of the outcome of the try statement. continue将执行转移到while循环的开始,因此,无论try语句的结果如何,您都永远不会到达print语句。 You need to indent it further: 您需要进一步缩进:

try:
    scale = float(scale)
    fc = fahtoCel(scale)
except Exception:  # Don't use bare except! You don't want to catch KeyboardInterrupt, for example
    print("Invalid entry")
    continue
print("%.2f degrees fah equals %.2f degrees Cel" % (scale, fc))

Really, though, your try statement is too broad. 但是,实际上,您的try语句太宽泛了。 The only exception you should worry about catching is the ValueError that float might raise. 您应该担心的唯一例外是float可能引发的ValueError

try:
    scale = float(scale)
except ValueError:
    print("Invalid entry")
    continue
fc = fahtoCel(scale)
print("%.2f degrees fah equals %.2f degrees Cel" % (scale, fc))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM