这是我正在编写的代码的一部分,我试图让用户输入一个数字来从1-100中选择他们想要的级别,但是当他们输入一个数字时,它会告诉他们它们是哪个整体级别我使用了此代码,但似乎无法使其正常工作。条件是,如果输入以下,上方或文本中的数字,则不能中断,它只需要重新提问即可。
#Ask for level
Level = ""
#make code for it
def number():
while True:
try:
Level = int(input("What is the level in the game? "))
except ValueError:
print("Please enter a valid number")
else:
break
return Level
while True:
if number <=25:
print ("Beginner" )
if number >=26 and number <=75:
print ("Intermediate")
if number >=76 and number <=100:
print ("expert")
break
答案 0 :(得分:0)
您没有调用number()
方法。
答案 1 :(得分:0)
您从循环1退出,但陷入了另一个while
循环中。在第二个循环中,您将number
用作变量,而将其定义为函数,因此应将其用作number()
试试这个简化的代码。
#make code for it
def number():
while True:
try:
Level = int(input("What is the level in the game? "))
if Level <= 25:
print ("Beginner" )
break
elif Level >=26 and Level <=75:
print ("Intermediate")
break
elif Level >=76 and Level <=100:
print ("expert")
break
else:
print("Out Of range(1-100): Please enter a valid number:")
except ValueError:
print("Please enter a valid number")
return Level
num = number() # If you really want to print/get the value entered
如果要使条件不属于主要方法。比这样做,但要记住无论如何根本不需要第二个while
循环。
#make code for it
def number():
Level = 0
while True:
try:
Level = int(input("What is the level in the game? "))
if not 1 <= Level <= 100:
print("Out Of range(1-100): Please enter a valid number:")
else:
break
except ValueError:
print("Please enter a valid number")
return Level
num = number()
if num <=25:
print ("Beginner" )
if num >=26 and number <=75:
print ("Intermediate")
if num >=76 and number <=100:
print ("expert")
答案 2 :(得分:0)
尝试一下
def number():
while True:
num = input('"What is the level in the game? ')
try:
val = int(num)
if val <=25:
print ("Beginner" )
break
if val >=26 and val <=75:
print ("Intermediate")
break
if val >=76 and val <=100:
print ("expert")
break
if val >100:
print("Out Of range(1-100): Please enter a valid number")
except ValueError:
print("Please enter a valid number")
number = number()
答案 3 :(得分:0)
由于您的完整代码未显示,因此我在做一些假设
1>您已用数字替换了Level的值。
2>您实际上是在调用number(),并且正在用Level代替变量数字
3>假设您没有代码将上面返回的级别放置到数字上,我将数字替换为级别
def number():
while True:
try:
Level = int(input("What is the level in the game? "))
except ValueError:
print("Please enter a valid number")
else:
break
if Level > 1:
return Level
while True:
if Level <= 25:
print("Beginner")
break
if Level >= 26 and Level <= 75:
print("Intermediate")
break
if Level >= 76 and Level <= 100:
print("expert")
break