我是编程新手,我哥帮我写了下面的代码。我很难理解为什么您必须设置“int_input = none”,然后说“如果 int_input 不是 None”,非常感谢您的时间!
name = input('What is your name: ' )
int_input = None
string_or_number = input(' Do you want to type in a string or a number? ' )
if string_or_number.upper() == 'NUMBER':
int_input = int(input(' on a scale of 1-10, how happy are you? ' ))
else:
string_input = (input( 'Are you happy or sad? ' ))
if int_input is not None:
if int_input > 5:
print("I'm glad to hear you are feeling a " + str(int_input) + ' out of 10')
elif int_input <=5:
print("I'm sorry to hear you are feeling a " + str(int_input) + ' out of 10')
else:
if string_input.upper() == 'HAPPY':
print('I am glad you are ' + string_input)
elif string_input.upper() != 'HAPPY':
print('That is too bad ' + name) ```
答案 0 :(得分:2)
您需要初始化 int_input
,因为它后面有 if
语句。
假设您没有初始化 int_input
。那么如果 string_or_number.upper()
不等于 'NUMBER'
,那么变量 int_input
将永远不会被初始化。所以当你试图在下一个 if 语句中访问它时,即 if int_input > 5:
,int_input
不会有值,这会导致 python 解释器抛出一个 NameError
,导致代码崩溃。
答案 1 :(得分:1)
EL15:
通过将 int_input
设置为 None
,它为您提供了一种检查用户输入是否被接受或是否正确的方法(在您的情况下,如果它等于 NUMBER
)。例如,如果用户没有输入任何内容或输入错误,那么 int_input 的默认值是 None
并保持不变,因此 if int_input is not None:
中的代码不会运行,而是else
语句中的代码将被执行。
答案 2 :(得分:1)
添加到其他答案中,这很好地解释了为什么必须在代码中初始化变量;这是你的代码的不同版本,你不需要初始化这个变量,我现在称之为 hapiness_var
,它可以是字符串或整数;但将始终在输入之后定义。
# Input name, remove head/trailing spaces, and turn the first letter into a capital letter.
name = input('What is your name: ' ).strip().capitalize()
# Ask if string or number, remove head/trailing spaces, and then turn into upper cases.
string_or_number = input(' Do you want to type in a string or a number? ' ).strip().upper()
if string_or_number.upper() == 'NUMBER':
hapiness_var = int(input(' on a scale of 1-10, how happy are you? ' ))
else:
hapiness_var = input( 'Are you happy or sad? ' ).strip().upper()
# Try/except to do see if it's a string or an int.
# If it's a string, the if test will fail, and the program will switch to the
# except clause
try:
if hapiness_var > 5:
print (f"I'm glad to hear you are feeling a {hapiness_var} out of 10")
elif hapiness_var <= 5:
print("I'm sorry to hear you are feeling a {hapiness_var} out of 10")
except:
if string_input.upper() == 'HAPPY':
print('I am glad you are ' + hapiness_var)
elif string_input.upper() != 'HAPPY':
print('That is too bad ' + name)