Преобразование Цельсия и Фаренгейта в Python 3 - PullRequest
0 голосов
/ 20 сентября 2018

У меня запутанная проблема с моей программой преобразования температуры на 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

Ответы [ 4 ]

0 голосов
/ 20 сентября 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)
В последних нескольких строках вы используете имена возвращаемых значений 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, чтобы напечатать вывод.Кроме того, вы не можете добавить строку и число с плавающей точкой.Вы можете преобразовать число с плавающей точкой в ​​строку через str(), например: "This is a float " + str(float(5)) + "!".Это немного хакерский и не считается отличным кодом.В приведенном выше коде я использовал функцию format(), которая не только дает вам более четкий, более читаемый код, но и может выполнять некоторое форматирование, например, в приведенном выше коде для каждого числа с плавающей запятой даются только 2 точки точности, а не всерассчитывается.

Вопросы в начале кода немного разбиты.Вы правильно проверяете, введены ли данные в Германии или США, и выводите сообщение об ошибке, если это не так, но впоследствии вы не повторяете свой вопрос.Я предлагаю использовать простой цикл 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!")

Надеюсь, это вам немного поможет ...

0 голосов
/ 20 сентября 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")
0 голосов
/ 20 сентября 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")
0 голосов
/ 20 сентября 2018

ваш оператор определения не был выполнен, но не нужен, просто замените

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
...