输入必须介于100和200之间

时间:2016-10-26 23:12:14

标签: python python-3.x while-loop

我正在创建一个程序,让用户多次输入一个数字,直到所述数字介于100和200之间。如果用户输入字符串或非整数,则会创建错误消息并提示用户再次尝试。目前我遇到了问题:

print("You tried " + guesssesTakenInt + "numbers and " + guessesTakenStr +  
   "non-number to get it right.")

我假设我必须将它变成一个while循环,以便出现以下错误:guessesTakenInt未定义。

##
## a6p2.py
##


def main():
    # this is the code that runs when your program is executed
    guessesTakenInt = 0
    guessesTakenStr = 0
    while True:

        guessesTakenStr += 1
        try:
            userNumber = int(input("Please enter a number between 100 and 200: "))
        except ValueError:
            print("Sorry that is not a number. ")
            continue
        else:
            break

    while userNumber > 0:

        guessesTakenInt += 1ed

        if userNumber > 200:
            userNumber = int(input("This number is too big. Try again: "))
        elif userNumber < 100:
            userNumber = int(input("This number is too low. Try again: "))
        else:
            guessesTakenInt = str(guessesTakenInt)
            guessesTakenStr = str(guessesTakenStr)

                print("That number is just right!")
                print("You tried " + guesssesTakenInt + "numbers and " + guessesTakenStr + " non-number to get it right.")
                break




    return
    print (main())






###############################################################
## DO NOT CHANGE THIS! LEAVE IT AT THE BOTTOM OF YOUR FILE
## calls the main function when this file is run with Python
##
## python stats.py
##
###############################################################
if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:0)

正如JJJ所述,你有一个错字。但这不是全部,您还有两个不同的show

  1. 用于检查用户是否输入了数字
  2. 用于检查数字是否介于100和200之间
  3. 这是您需要做的事情:

    1. 两个while都应合并为一个。
    2. 在将字符串解析为while之前,使用str.isnumeric()来测试字符串是否为NaN
    3. int(str)更改为guesssesTakenInt
    4. guessesTakenInt更改为guessesTakenInt += 1ed
    5. 修复缩进
    6. 我冒昧地改变你的代码。

      guessesTakenInt += 1