【问题标题】:cant get my while loops working the way i want it to无法让我的 while 循环按我想要的方式工作
【发布时间】:2021-04-12 09:12:22
【问题描述】:

我正在尝试使此代码正常工作,如果您输入一个数字,它将使您返回到 name=input 提示,并且一旦您输入字母字符而不是数字字符,它将允许您继续下一个一组代码,但它不断将您返回到 name = input 并且不允许您完成其余代码

def setup():
    global name
    global HP
    global SP
    global MP
    while True:
        try:
            name = input('can you please tell me your name?  ')
            name2=int(name)
            if  not name.isalpha==True and not name2.isdigit==False:
                break
                
                
        except Exception:
                print('please input your name')
                continue
    
    HP = randint(17,20)
    SP = randint(17,20)
    MP = randint(17,20)
    print('welcome ['+name+':]:  to the moon landing expedition')

【问题讨论】:

  • ps这是一个学校项目

标签: python-3.x while-loop


【解决方案1】:

name2=int(name) 存在问题,除非您键入所有数字,否则会导致异常。反过来,这会触发Exception 并永远循环它。您的 while 循环似乎很好。

我认为你应该做什么:

while True:
    name = input('What is your name')
    isnum = False
    for i in name:
        if i.isnumeric():
            isnum = True
            break
    
    if isnum:
        print('Please type your name.')
        continue
    
    break

【讨论】:

  • 但是如果你按一个不存在的数字,我无法让它循环播放
  • 一个不存在的数字? @TristanLauzon
  • 我的意思是当你按下键盘上的数字键输入而没有那段代码时,循环实际上不会循环,它会将输入作为字符串
  • @TristanLauzon 我编辑了这篇文章。希望它有所帮助。
猜你喜欢
  • 2021-11-29
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-19
相关资源
最近更新 更多