简体   繁体   中英

How do i loop my program?

I am having trouble trying to figure out how to loop my program to return back the the start where you enter a value. Any suggestions will help, I am new to programming. (python 2.17, wing 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

You may for example add "Enter 0 to exit" to the start message.
Then you put everything starting from choice = input(...) (including this line) into a while (True): loop.
Finally, add if choice == 0: break at the end and you're good.

Approach your code like the computer would:

1) Consider where you would like to begin looping

2) Set your loop's condition. A computer doesn't know what you want unless you explicitly communicate it; do you want it to loop forever? Until something happens? Communicate how, if, and when you want it to stop.

I recommend you read the python documentation on While loops ;)

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