对不起,我对python还是很陌生,我知道这可能很容易解决,但是我已经坚持了很长时间。这是我的代码:CountFromNum = InputNumber("Which number would you like to count down from? ")
print("This is Joe's Multiple Program Loader, hope you enjoy.")
print("Would you like to:")
print("(a) Count down from a certain number.")
print("(b) Print your name a certain amount of times.")
StartQuestion = input("(c) make a list with a custom length. ")
StartQuestionOptions='abc'
while StartQuestion not in StartQuestionOptions :
StartQuestion=input("Please enter the letter a, b or c: ")
if StartQuestion in StartQuestionOptions :
break
else :
StartQuestion=input("Please enter the letter a, b or c: ")
#Module A: P1
if StartQuestion == 'a':
print("You have selected: Option a")
def InputNumber(message):
while True:
try:
Userinput = int(input(message))
except ValueError:
print("Not a number! Please try again.")
continue
else:
return Userinput
break
CountFromNum = InputNumber("Which number would you like to count down from? ")
#Module B: P1
if StartQuestion == 'b':
print("You have selected: Option b")
Username = input("Please enter your name: ")
# Module B: P2
def InputNumber(message):
while True:
try:
Userinput = int(input(message))
except ValueError:
print("Please enter a number, try again.")
continue
else:
return Userinput
break
#Module B: P3
NameRepeatValue = inputNumber("How many times do you want to repeat your name? ")
while NameRepeatValue > 0:
print (Username)
NameRepeatValue -=1
while NameRepeatValue > 0:
exit()
#Module C: P1
if StartQuestion == 'c':
print("You have selected: Option c")
if StartQuestion == 'abc':
print("Stop trying to break my program.")
[我做某事时总是出错,请提供帮助。
主要问题是您在定义函数之前正在尝试使用它。将InputNumber
的定义移到文件顶部;或至少在使用之前。
您应该开始练习的另一种解决方法是将所有代码包装在函数中。理想情况下,您在顶层具有的所有不是函数定义的所有代码都应放入main
函数或类似的东西中。这将在这里解决您的问题,并且在您开始使用REPL进行开发时,也可以简化以后的开发。通过将所有这些代码置于函数之外,您将迫使它在读取文件时运行,这在不是简单测试或玩具的任何代码中都不是最佳选择。
[其他说明:
您在两个不同的位置定义了InputNumber
两次,并且只有在StartQuestion == 'a'
时才出现第一个定义。不要这样有条件地定义变量/函数将使您的代码容易出现NameError
,因为您可以使用未定义的函数。只需在顶部定义一次即可。
[Variable names should be in lower_snake_case. UpperCamelCase保留用于类名。
此代码为有效且完整的,您可以将其发布在Code Review上,人们可以提出进一步的建议。