Go back to a string/line (loop)

This is the place for queries that don't fit in any of the other categories.

Go back to a string/line (loop)

Postby uDylon » Wed Dec 04, 2013 4:01 pm

I am writing a script that converts Fahrenheit to Celsius and Celsius to Fahrenheit I want to put a loop after it says "Invalid Input!" so it goes back to the string "Type". Basically restart but keep line 1. Anyone have any ideas?
Code: Select all
Temp = input("Input temperature.")
Type = input("Press 1 for F to C and press 2 for C to F")

if Type == 1:
    Conversion = (Temp - 32) * 5/9

elif Type == 2:
     Conversion = Temp * 9/5 + 32
if Type == 1:
    print Conversion
    print "°C"

elif Type == 2:
    print Conversion
    print "°F"

    print "Invalid input!"
Last edited by Mekire on Wed Dec 04, 2013 4:11 pm, edited 1 time in total.
Reason: First post lock.
Posts: 1
Joined: Wed Dec 04, 2013 3:57 pm

Re: Go back to a string/line (loop)

Postby Mekire » Wed Dec 04, 2013 4:17 pm

Well firstly, you are using python 2 so you should not be using input. Use raw_input instead.

To answer your question you need while loops to check input is valid.

Consider the following:
Code: Select all
while True:
        temperature = float(raw_input("Input temperature: "))
    except ValueError:
        print("Invalid input.")

User avatar
Posts: 988
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot], puck2020 and 4 guests