Just started learning python earlier today and I can't work out why this code won't end the program if "N" is entered. Also if I change the last if statement to.= "Y" then even if I type Y then it closes which is confusing me so much. I was just trying to make a simple program to convert Fahrenheit to Celcius if prompted without looking up any of the code so if it's badly written that's why.
while True:
def temp_func():
print("Is the temperature you'd like to convert in Fahrenheit or Celcius?")
temp = input()
if temp == "Fahrenheit":
F_temp = int(input("Please write the temperature."))
converted_temp_F = ((F_temp - 32) * 5 / 9)
print(str(converted_temp_F))
elif temp == "Celcius":
C_temp = int(input("Please write the temperature."))
converted_temp_C = ((C_temp * (9 / 5)) + 32)
print(str(converted_temp_C))
temp_func()
print(input("Would you like to convert another temperature? (Y/N) "))
if input == 'Y':
True
if input == 'N':
break
print ("Goodbye")
replace your print(input... and conditions with:
response = input("Would you like to convert another temperature? (Y/N) ").upper()
if response == 'N':
break
You need to store the input value given by the user in a variable for Y/N
. You should move the function out of the while
loop
def temp_func():
print("Is the temperature you'd like to convert in Fahrenheit or Celcius?")
temp = input()
if temp == "Fahrenheit":
F_temp = int(input("Please write the temperature."))
converted_temp_F = ((F_temp - 32) * 5 / 9)
print(str(converted_temp_F))
elif temp == "Celcius":
C_temp = int(input("Please write the temperature."))
converted_temp_C = ((C_temp * (9 / 5)) + 32)
print(str(converted_temp_C))
while True:
temp_func()
Y_N = input("Would you like to convert another temperature? (Y/N) ")
if Y_N == 'N':
break
print ("Goodbye")
Try like this
def temp_func():
print("Is the temperature you'd like to convert in Fahrenheit or Celcius?")
temp = input()
if temp == "Fahrenheit":
F_temp = int(input("Please write the temperature."))
converted_temp_F = ((F_temp - 32) * 5 / 9)
print(str(converted_temp_F))
elif temp == "Celcius":
C_temp = int(input("Please write the temperature."))
converted_temp_C = ((C_temp * (9 / 5)) + 32)
print(str(converted_temp_C))
while True:
temp_func()
x = input("Would you like to convert another temperature? (Y/N) ")
if x.lower() == "n":
break
print ("Goodbye")
On this line:
print(input("Would you like to convert another temperature? (Y/N) "))
Here, if you do -
input("Would you like to convert another temperature? (Y/N) ")
It will do the printing for you, and take an input. now what you need to do is store the value in a variable. For example:
choice = input("Would you like to convert another temperature? (Y/N) ")
Now compare the choice
variable and you are good to go!
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.