【发布时间】:2019-08-13 15:00:36
【问题描述】:
版本:Python 3.7.4
嗨,这是我的第一个代码。如果我正确输入所有内容,它会很好地工作。但是,如果我在某些点输入了错误的值,则会收到错误“NameError: name 'password' is not defined”。此外,如果您可以查看我的代码并向我提供一些关于如何使它变得更好的反馈,以及可能的解决方案,那就太棒了。请指导我尤达大师! :)
我尝试过的解决方案: 1.加括号,去掉括号,去掉冒号,加冒号。 2. 分配变量名。 3.阅读我正在学习的书,但根据书我的代码很好。 4.阅读类似的帖子,但他们的代码更高级,所以我无法理解代码和解决方案。 5.各种缩进。`
此错误发生在: - 如果我输入了错误的用户名值,则第 18 行。 - 第 30 行,如果我输入密码错误(NameError: name 'age' is not defined) - 第 43 行 NameError: name 'ans' is not
我的代码:
#Displays what I have learnt so far : Variable assignment, comparision operators, arithmetic operators, value operators, logical operators,
print('Welcome')
print('Enter Username')
username = input()
if username == 'Evan' :
print('Enter Password')
else:
print('Wrong Username. Program terminated.')
if username == 'Evan' :
password = input()
if password == 'Great' :
print('Additional identification confirmation required.')
else:
print('Wrong password. Program terminated.')
if password == 'Great':
print('What is your age?')
years = (27)
age = int(input())
if age < years :
print('Seriously?')
elif age > years :
print('-_-"')
else:
age == years
print('Welcome Evan!')
if age == years:
print('Name one of the RGB colours.')
rgb = 'Red' or 'Green' or 'Blue'
colours = input()
if colours == rgb :
print('Good')
else:
print('Wrong Answer')
if age == years :
print('Type Rock & Roll.')
answer = 'Rock & Roll'
ans = input()
if ans != answer :
print('Learn to type.')
else:
print('Good job!')
if age == years:
print('Let me show you some math for entertainment :D')
result = '= '
print('2+2')
print(result + str(int(2+2)))
print('')
print('3 - 2')
print(result + str(int(3-2)))
print('')
print('2 x 2')
print(result + str(int(2*2)))
print('')
print('7 / 3')
print(7/3)
print('')
print('3 modulus 7')
print(result + str(int(3%7)))
print('')
print('2 exponent 10')
print(result + str(int(2**10)))
print('')
print('23 floor division 9')
print(result + str(int(23//9)))
【问题讨论】:
-
在 if 或 for 中包含变量时,最好始终使用空值预定义它们。
标签: python python-3.x