我的代码应该只接受字母(例如Jack会被接受,而jack1将不被接受)。
它会提示用户输入姓名,然后存储它们。一旦我编写了第一个名字的代码,我就对它进行了测试,看看我是否为第一个名称正确编写了代码,但它一直给我this error。
在答案中,您能否说明如何仅使用数字来完成这项工作?
代码
import random
operators = ["+", "-", "*"]
def greeting(first_name, last_name):
print ("Hello", first_name + " " + last_name)
Play = input('Are you ready to begin?')
if Play == 'yes':
print("Great", first_name + ", lets begin")
else:
greeting(first_name, last_name)
def Players_input():
print ("Welcome to the Arithmetic Quiz")
first_name = input("Please enter your first name: ")
if all(x.isalpha() or x.isspace() for x in first_name):
last_name = input("Please enter your last name: ")
greeting(first_name, last_name)
else:
print("Only alphabetical letters and spaces: no")
Players_input()
score = 0
for i in range(10):
first_number = random.randint(1,12)
second_number = random.randint(1,12)
op = random.choice(operators)
print (first_number, op, second_number, " = ?")
users_answer = int(input())
if op == "+":
right_answer = first_number + second_number
elif op == "-":
right_answer = first_number - second_number
elif op == "*":
right_answer = first_number * second_number
if users_answer == right_answer:
print("Well Done!")
score += 1
else:
print ("Sorry but thats the wrong answer, the right answer is: " + str(right_answer) + ". Better luck next time")
print (first_name, "Your final score in the Arithmetic Quiz is", str(score), "out of 10")
答案 0 :(得分:1)
当您尝试使用它时,first_name变量超出范围。它属于Players_input()函数。
Read this article on scoping to get more of an idea of what is happening
答案 1 :(得分:1)
查看错误。它告诉你$json = Request::json()->all();
return $json;
变量没有定义。这是因为它是first_name
函数中的局部变量,不能在别处使用。在函数内定义的变量被放在内存中的堆栈中,并在堆栈帧被推离堆栈时被销毁。你称之为“超出范围”。
我建议您查找有关变量范围的信息。
答案 2 :(得分:1)
第一个问题的答案:
您从未定义Players_input
的first_name 在之外。该值仅存储在函数内部,之后将被删除。 (更多关于the link added by gjttt1)的内容
有两种方法可以解决这个问题:
global first_name
中的某个位置添加Players_input
(因此,在第一次打印调用之前或之后)return first_name
末尾添加Players_input
,并将Players_input()
替换为first_name = Players_input()
。第二个问题的答案:
只需使用此功能代替int(input())
(将此行替换为int_input()
):
def int_input(prompt="", error_message="You didn't enter an integer!"):
while True: # repeat this until the function returns
inp = input(prompt) # get the input after autputting the prompt.
try: # Try to...
return int(inp) # turn it into an integer. If it works, return it.
except ValueError: # If it didn't work, it raised a ValueError. In this case...
if error_message: # print the error_message if it is not "", false or None.
print(error_message)
然后你有第三个问题:你应该在函数名中使用小写字母,以区别于类。这只是你的风格,但它肯定有助于开发一种良好,清晰的编码风格。
我希望我能提供帮助,
CodenameLambda
答案 3 :(得分:0)
你可以在代码的前面声明first_name =('hi'),然后当你把它作为输入函数调用时,可以像下面这样写:
first_name=str(input('Please enter your first name: '))