简体   繁体   中英

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. If the user enters 1 or 2, another prompt will ask them to enter the degrees they want converted. 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. When I run this code, everything seems to work fine until it gets to the function call 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? 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. 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. The only exception you should worry about catching is the ValueError that float might raise.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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