简体   繁体   English

为什么代码无法识别分配的变量?

[英]Why the code doesn't recognize the assigned variable?

I am trying to write a program in Python 3 that takes an int year larger than 1970 as an input and returns the increase in temperature from 1970 until that year. 我正在尝试使用Python 3编写一个程序,该程序需要一个大于1970年的整型年份作为输入,并返回从1970年到该年的温度升高。 The formulas and constants are given. 给出了公式和常数。 Python throws me an error: Python抛出一个错误:

File "4.5.py", line 28, in <module>
    int_years = int_year - 1970
NameError: name 'int_year' is not defined

I am a beginner in Python so I have browsed possible solutions, but could not find any working ones. 我是Python的初学者,所以我浏览了可能的解决方案,但找不到任何可行的解决方案。

def user_input():
    while True:
        int_year = int(input("Please enter a year greater than 1970 " ))
        try:
            if int_year > 1970:
                break
            else:
                print("Please enter a year greater than 1970")
        except ValueError:
            print ("It is not a valid year. Try again. ")
    return int_year

"""CO2 level of January 1970"""
c0 = 325.03

"""Current levels of CO2"""
c1 = 411.97

"""Difference in CO2 levels between 1970 and now"""
differenceCO = c1-c0

"""The average CO2 increase per year since 1970"""
per_year_changedCO = ((differenceCO)/(2019-1970))

"""Diffrence in years between 1970 and user input year"""
int_years = int_year - 1970

"""A projected CO2 level in user input year"""
int_year_changedCO = c0+((int_years)*(per_year_changedCO))

"""A projected RF in any year"""
RF = 5.35*(math.log((int_year_changedCO)/(c0)))

"""Increase in temperature from 1970 to user input year"""
def predict_increase():
  temp_int_year = 0.5 * RF
  return temp_int_year

print(temp_int_year)

I expect the program to recognize the variables I use in functions. 我希望程序能够识别我在函数中使用的变量。 Overall, I will appreciate any comments on the code. 总的来说,我将感谢您对代码的任何评论。

By the time you execute the line int_years = int_year - 1970 , you haven't defined int_year in scope. 在执行int_years = int_year - 1970 ,您尚未在范围内定义int_year The only place you've used it up to that point is within the user_input() function - but variables defined within functions are only defined within the functions - not outside of them. 你已经用它到这一点的唯一地方是内user_input()函数-但是函数中定义的变量在函数定义-不在外面他们。 To get the value of int_year outside of the function, you need to call the function: 要在函数之外获取int_year的值,您需要调用函数:

int_year = user_input()
int_years = int_year - 1970

or simply do them both at once: 或简单地同时做两个:

int_years = user_input() - 1970

The problem is here: 问题在这里:

return int_year

By inserting this instruction, you tell the interpreter to return the value int_year has at that moment . 通过插入此指令,您告诉解释器返回那一刻的 int_year值。 Any further usage of this variable leads to an error, because the variable is no longer defined 对该变量的任何进一步使用都会导致错误,因为不再定义该变量

You define int_year within the scope of the user_input, but that is not accessible outwith that function (more info about that here) 您可以在user_input的范围内定义int_year,但是该函数无法访问该整数(有关此内容的更多信息)

Rather than reference the variable directly you want to get the return value of the function (which is the value of int_year because of the line 'return int_year'): 您不是要直接引用变量,而是要获取函数的返回值(由于行“ return int_year”,它是int_year的值):

int_years = user_input() - 1970

Edit for comment above 在上方编辑以发表评论

def user_input():
    try:
        int_year = int(input("Please enter a year greater than 1970"))
        if int_year < 1970:
            print("Invalid year, please enter a value greater than 1970")
            int_year = user_input()
    except ValueError:
        print("Invalid input. Please enter a number")
        int_year = user_input()
    return int_year

you dont call your functions anywhere, variables temp_int_year and int_year are Local variables of functions and they can't be accessed from outside, when the function call has finished 您不会在任何地方调用函数,变量temp_int_year和int_year是Local variables of functions并且在函数调用完成后无法从外部访问它们

you need to call function and save return value into temp_int_year and int_year: 您需要调用函数并将返回值保存到temp_int_year和int_year中:

int_year = user_input()

temp_int_year = predict_increase()
print(temp_int_year)

NOTE: you have the same mistake with temp_int_year 注意:您与temp_int_year有相同的错误

full code: 完整代码:

import math
def user_input():
    while True:
        int_year = int(input("Please enter a year greater than 1970 " ))
        try:
            if int_year > 1970:
                break
            else:
                print("Please enter a year greater than 1970")
        except ValueError:
            print ("It is not a valid year. Try again. ")
    return int_year

int_year = user_input()


"""CO2 level of January 1970"""
c0 = 325.03

"""Current levels of CO2"""
c1 = 411.97

"""Difference in CO2 levels between 1970 and now"""
differenceCO = c1-c0

"""The average CO2 increase per year since 1970"""
per_year_changedCO = ((differenceCO)/(2019-1970))

"""Diffrence in years between 1970 and user input year"""
int_years = int_year - 1970

"""A projected CO2 level in user input year"""
int_year_changedCO = c0+((int_years)*(per_year_changedCO))

"""A projected RF in any year"""
RF = 5.35*(math.log((int_year_changedCO)/(c0)))

"""Increase in temperature from 1970 to user input year"""
def predict_increase():
  temp_int_year = 0.5 * RF
  return temp_int_year

temp_int_year = predict_increase()
print(temp_int_year)

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

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