Преобразуване на Целзий и Фаренхайт в Python 3

Получих объркващ проблем с моята програма за преобразуване на температура в Python, объркващ поне за мен, тъй като съм нов в това. Имам две местоположения, Германия и САЩ, една държава, от която е потребителят и където се намира потребителят в момента. Просто се опитвам да преобразувам температурата от температурната скала в страната, в която потребителят се намира в момента, в температурната скала на страната, от която идва потребителят.

Например, потребителят е от Германия, но в момента е в САЩ. Така че в този случай искам програмата да вземе температурата, която потребителят въвежда, за да бъде преобразувана от Целзий във Фаренхайт.

Моят код:

location = input("Where are you from?")

us = ("USA")
ger = ("Germany")

if location == ger:
print("You are from Germany")
elif location == us:
print("You are from the USA")
else:
print("Enter the country Germany or USA")

recentLoc = input("What is your location right now?")

if recentLoc == ger:
print("You are in Germany right now")
elif recentLoc == us:
print("You are in the USA right now")
else:
print("Please enter the country Germany or the USA")

temp = input("What is the temperature outdoor tomorrow?")

def convert_f():
f = float(fahrenheit)
f = (temp*9/5)+32
return(f)

def convert_c():
c = float(celsius)
c = (temp-32)*5/9
return(c)

if recentLoc == ger and location == us:
print("Temperature for tomorrow is " + float(c) + "Celsius or " + float(f) + "Fahrenheit")
elif recentLoc == us and location == ger:
print("Temperature for tomorrow is " + float(f) + "Fahrenheit or " + float(c) + "Celsius")
elif recentLoc == us and location == us:
print("Temperature for tomorrow is " + float(f) + "Fahrenheit")
elif recentLoc == ger and location == ger:
print("Temperature for tomorrow is " + float(c) + "Celsius")
else:
print("Please type in a number")

Съобщение за грешка:

NameError: name 'f' is not defined

person brukestilblizzard    schedule 20.09.2018    source източник
comment
Къде е дефинирано f?   -  person Peter Wood    schedule 20.09.2018


Отговори (4)


вашият оператор define не е стартиран, но не са необходими просто обмен

def convert_f():
    f = float(fahrenheit)
    f = (temp*9/5)+32
    return(f)

def convert_c():
    c = float(celsius)
    c = (temp-32)*5/9
    return(c)

за

f = (temp*9/5)+32
c = (temp-32)*5/9
person jack    schedule 20.09.2018
comment
В кода няма променлива fahrenheit или celsius. Прегледайте внимателно кода отново. - person Sheldore; 20.09.2018

Имаше няколко грешки в кода ви. Ето едно работещо решение. Не показвам началната част от вашия код, която не съм докоснал.

# User input here
# if else statements here

recentLoc = input("What is your location right now?")

temp = float(input("What is the temperature outdoor tomorrow?"))

def convert_f(temp): # The function modified
    f = (temp*9/5)+32
    return(str(f))

def convert_c(temp): # The function modified
    c = (temp-32)*5/9 
    return(str(c))

if recentLoc == ger and location == us:
    print("Temperature for tomorrow is " + convert_c(temp) + "Celsius or " + convert_f(temp) + "Fahrenheit")
elif recentLoc == us and location == ger:
    print("Temperature for tomorrow is " + convert_f(temp) + "Fahrenheit or " + convert_c(temp) + "Celsius")
elif recentLoc == us and location == us:
    print("Temperature for tomorrow is " + convert_f(temp) + "Fahrenheit")
elif recentLoc == ger and location == ger:
    print("Temperature for tomorrow is " + convert_c(temp) + "Celsius")
else:
    print("Please type in a number")
person Sheldore    schedule 20.09.2018

Вие само дефинирахте функциите за преобразуване, но не ги извикахте.

location = input("Where are you from?")

us = ("USA")
ger = ("Germany")

if location == ger:
    print("You are from Germany")
elif location == us:
    print("You are from the USA")
else:
    print("Enter the country Germany or USA")

recentLoc = input("What is your location right now?")

if recentLoc == ger:
    print("You are in Germany right now")
elif recentLoc == us:
    print("You are in the USA right now")
else:
    print("Please enter the country Germany or the USA")

temp = input("What is the temperature outdoor tomorrow?")

def convert_f(temp):
    temp = float(temp)
    f = (temp*9/5)+32
    return(f)

def convert_c(temp):
    temp = float(temp)
    c = (temp-32)*5/9
    return(c)

if recentLoc == ger and location == us:
    print("Temperature for tomorrow is " + temp + "Celsius or " + str(convert_f(temp)) + " Fahrenheit")
elif recentLoc == us and location == ger:
    print("Temperature for tomorrow is " + temp + "Fahrenheit or " + str(convert_c(temp)) + " Celsius")
elif recentLoc == us and location == us:
    print("Temperature for tomorrow is " + temp + "Fahrenheit")
elif recentLoc == ger and location == ger:
    print("Temperature for tomorrow is " + temp + "Celsius")
else:
    print("Please type in a number")
person blhsing    schedule 20.09.2018

Имате няколко грешки в кода си:

  1. Двете функции, които дефинирахте convert_f и convert_c, не могат да използват градуси по Фаренхайт или Целзий, защото не сте ги дефинирали никъде. Предполагам, че искате да предоставите тези стойности като параметри.
def convert_f(fahrenheit):
    f = float(fahrenheit)
    f = (f*9/5)+32
    return(f)

def convert_c(celsius):
    c = float(celsius)
    c = (c-32)*5/9
    return(c)
  1. В последните няколко реда използвате имената на върнатите стойности на convert_f и convert_c. Те са за един, който никога не е създаван, защото никога не извиквате функциите и дори да са били извикани, не могат да бъдат достъпни по този начин. Името на върнатата стойност губи всякакво значение извън функцията. Това, което можете да направите, е нещо подобно:
temp = float(temp)

if recentLoc == ger and location == us:
    print("Temperature for tomorrow is {:.2f} Celsius or {:.2f} Fahrenheit".format(temp, convert_f(temp)))
elif recentLoc == us and location == ger:
    print("Temperature for tomorrow is {:.2f} Fahrenheit or {:.2f} Celsius".format(temp, convert_c(temp)))
elif recentLoc == us and location == us:
    print("Temperature for tomorrow is {:.2f} Fahrenheit".format(temp))
elif recentLoc == ger and location == ger:
    print("Temperature for tomorrow is {:.2f} Celsius".format(temp))
else:
    # Technicaly this is printed when either recentLoc or location are neither ger or us
    print("Please type in a number")    

Използвам temp и изхода на convert_f и convert_c, за да отпечатам изхода. Освен това не можете да добавите низ и float. Можете или да конвертирате float в низ чрез str(), например: "This is a float " + str(float(5)) + "!". Това е малко хакерско и не се счита за чудесен код. В кода по-горе използвах функцията format(), която не само ви дава по-ясен и по-четлив код, но също така може да направи известно форматиране, например в кода по-горе са дадени само 2 точки на точност за всяко число с плаваща запетая, а не всички, които се изчисляват.

  1. Въпросите в началото на кода са малко счупени. Проверявате правилно дали въведеното е Германия или САЩ и отпечатвате съобщение за грешка, ако това не е така, но не повтаряте въпроса си след това. Предлагам да използвате прост цикъл while и да използвате break, когато получите правилен отговор.
location = ""

while location != us and location != ger:
    location = input("Where are you from?")

    if location == ger:
        print("You are from Germany")
        break
    elif location == us:
        print("You are from the USA")
        break
    else:
        print("Enter the country Germany or USA")

recentLoc = ""

while recentLoc != us and recentLoc != ger:
    recentLoc = input("What is your location right now?")

    if recentLoc == ger:
        print("You are in Germany right now")
        break
    elif recentLoc == us:
        print("You are in the USA right now")
        break
    else:
        print("Please enter the country Germany or the USA")


while 1:
    try:
        temp = input("What is the temperature outdoor tomorrow?")
        temp = float(temp)
        break
    except ValueError:
        print("That's not a number!")

Надявам се това да ви помогне малко...

person DerMolly    schedule 20.09.2018