简体   繁体   English

为什么我的python程序给出了if / else语句中的变量未定义的错误?

[英]Why is my python program giving me the error that a variable in an if/else statement is undefined?

I'm trying to write a code in Python three that converts temperatures and distances from one unit to another. 我正在尝试用Python 3编写一个代码,用于将温度和距离从一个单元转换为另一个单元。 I'm told that I need to use functions and that the user will input either F (Fahrenheit), C (Celsius), or K (Kelvin) and the temperature will be converted from whatever they choose to F, C or K. So I wrote a function for each scenario. 我被告知我需要使用功能,并且用户将输入F(华氏度),C(摄氏度)或K(开尔文),温度将从他们选择的任何值转换为F,C或K.所以我为每个场景编写了一个函数。 A function for if it's converted from F, another if it's converted from C, and another if it's converted from K. I also did this for inches, feet, yards, and miles. 如果它是从F转换的另一个函数,如果它是从C转换的另一个函数,另一个是从K转换的函数。我也用英寸,英尺,码,英里做了这个。

So after I wrote all of the functions I wrote an if, elif, and else statement which I want to call each function depending on what the user types. 所以在我写完所有函数后,我编写了一个if,elif和else语句,我想根据用户输入的内容调用每个函数。 So if the user inputs "F" I want it to call the convert_from_F() function, or if they put "K" I want it to use the convert_from_K(), or if the user types "inch" I want it to use the convert_from_inch() function. 因此,如果用户输入“F”,我希望它调用convert_from_F()函数,或者如果他们输入“K”我希望它使用convert_from_K(),或者如果用户键入“inch”,我希望它使用convert_from_inch()函数。 I thought that the way to do this would be to use the if, elif, and else statement. 我认为这样做的方法是使用if,elif和else语句。 However, no matter what I type I'm always given the error message: 但是,无论我输入什么,我总是会收到错误消息:

NameError: name 'F' is not defined NameError:未定义名称“F”

I would have thought that the iterations would continue past each statement if it found that the user didn't input that particular instruction. 如果发现用户没有输入该特定指令,我会认为迭代将继续超过每个语句。 It also doesn't work if I (as the user) put 'F.' 如果我(作为用户)放'F',它也不起作用 I'm not sure how to fix this code. 我不知道如何修复此代码。 What am I missing from it? 我错过了什么?

Also, I'm using an online python 3 compiler to write my program: OnlineGDB 另外,我正在使用在线python 3编译器来编写我的程序: OnlineGDB

def convert_from_F():
   F = float(input("Please input the temperature in F: "))
   print("Temperature in F is", F)
   print("Temperature in C is", (F-32)*5/9)
   print("Temperature in K is", (F-32)*5/9 + 273.15)

def convert_from_C():
   C = float(input("Please input the temperature in C: "))
   print("Temperature in F is", (C*9/5) + 32)
   print("Temperature in C is", C)
   print("Temperature in K is", C+273.15)

def convert_from_K():
   K = float(input("Please input the temperature in K: "))
   print("Temperature in F is", (K-273.15)*9/5 + 32)
   print("Temperature in C is", K-273.15)
   print("Temperature in K is", K)

def convert_from_inch():
   inch = float(input("Please input the distance in inches: "))
   print("Distance in inches is:", inch)
   print("Distance in feet is:", inch/12)
   print("Distance in yards is:", inch/36)
   print("Distance in miles is:", inch/63360)

def convert_from_ft():
   ft = float(input("Please input the distance in feet: "))
   print("Distance in inches is:", ft*12)
   print("Distance in feet is:", ft)
   print("Distance in yards is:", ft/3)
   print("Distance in miles is:", ft/5280)

def convert_from_yd():
   yd = float(input("Please input the distance in yards: "))
   print("Distance in inches is:", yd*36)
   print("Distance in feet is:", yd*3)
   print("Distance in yards is:", yd)
   print("Distance in miles is:", yd*1760)

def convert_from_mi():
   mi = float(input("Please input the distance in miles: "))
   print("Distance in inches is:", mi*63360)
   print("Distance in feet is:", mi*5280)
   print("Distance in yards is:", mi*1760)
   print("Distance in miles is:", mi)

print("To convert distance input inch, ft, yd, or mi. To convert \ 
temperatures please input F, C, or K. ")
user_input = input("Your input: ")

def user_conversion():
   if user_input == F or f:
       convert_from_F()
   elif user_input == C or c:
       convert_from_C()
   elif user_input == K or k:
       convert_from_K()
   elif user_input == inch:
       convert_from_inch()
   elif user_input == ft:
       convert_from_ft
   elif user_input == yd:
       convert_from_yd()
   elif user_input == mi:
       convert_from_mi()
   else:
       print("Invalid input.")

print(user_conversion())

Edit: I saw that this was marked as a possible duplicate. 编辑:我看到这被标记为可能重复。 The duplicate question doesn't help me, I wasn't trying to make this into a set, I was trying to figure out how I could make an if statement run. 重复的问题对我没有帮助,我没有尝试将其变成一组,我试图找出如何使if语句运行。 The solutions given for my problem aren't like the ones for the other question. 为我的问题提供的解决方案与其他问题的解决方案不同。 However, I'm new to Python so it's entirely possible that I can't make the connections that more experienced people can make. 但是,我是Python的新手,所以我完全有可能无法建立更有经验的人可以建立的联系。 The answers I received here did help me. 我在这里收到的答案对我有帮助。

Your if construct is wrong. 你的if结构是错误的。 It has to be if user_input == 'F' or user_input == 'f': 必须是if user_input == 'F' or user_input == 'f':

Alternatively you can write it shortly as 或者你可以写短信

if user_input in ['F', 'f']:

Or as specified in the comment as 或者在评论中指定为

if user_input.lower() == 'f':

It's reading F etc. as variable names. 它正在读取F等作为变量名称。 To fix this: 解决这个问题:

  1. Rewrite them as "F" etc. 将它们重写为"F"等。
  2. Fix your comparisons; 修正你的比较; or is used for multiple comparisons and can't be used how you're using it. or用于多重比较,不能用于你如何使用它。 Consider using user_input.casefold() == "f" instead. 请考虑使用user_input.casefold() == "f"

You need to quote the value and to fix the test, so 您需要引用该值并修复测试,所以

   if user_input == F or f:

become 成为

   if user_input == "F" or user_input == "f":

same for other lines 对于其他线路也一样

You have to have the condition on both sides of the or. 你必须在或两侧都有条件。 So: 所以:

def user_conversion():
   if user_input == 'F' or user_input == 'f':
       convert_from_F()
...

or you could just use 或者你可以使用

def user_conversion():
   if user_input.lower() == 'f':
       convert_from_F()
...

You want to make sure you're comparing to a string. 你想确保你比较一个字符串。 So, your if-statement would look like: 所以,你的if语句看起来像:

if user_input == "F" or user_input == "f":
    convert_from_F(user_input)

However, this is somewhat verbose. 但是,这有点冗长。 Instead, try: 相反,尝试:

if user_input.lower() == "f":
    convert_from_F(user_input)

This version converts the value of user_input to its lowercase variant, or leaves it alone if it's already lowercase. 此版本将user_input的值转换为其小写变体,如果它已经是小写,则将其user_input为单独。 You could do something similar by saving user_input.upper() == "F" too. 你可以通过保存user_input.upper() == "F"来做类似的事情。

A shorter and simpler version could be 一个更短更简单的版本可能是

if user_input in ["F","f"]:

And so on for the other conditions too. 对于其他条件也是如此。

Reason you are getting that error because the symantics of if statement works onuser boolean True or False. 您收到该错误的原因是因为if语句的语义适用于onuser boolean True或False。

Let us assume the condition on left hand side (LHS) of 'or' and right hand side (RHS) of it to be boolean. 让我们假设它的左侧(LHS)和右侧(RHS)的条件是布尔值。

So in your syntax, LHS is user_input == "F" that returns True or False. 所以在你的语法中,LHS是user_input == "F" ,它返回True或False。 But RHS of or is "f" . 但RHS的或是"f" And here is where problem arise. 这就是出现问题的地方。 RHS is not symatically correct. RHS不是系统正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM