【问题标题】:Error prompt instead of prompt to re enter input错误提示而不是提示重新输入输入
【发布时间】:2019-04-01 23:12:54
【问题描述】:

我正在制作一个价格合适的游戏。我目前正在开发一种类似于参赛者行的游戏模式,他们在其中猜测物品的价格。

当它要求您提交投标时,如果您输入一个单词(而不是投标),程序会崩溃并显示以下错误:

"Traceback(最近一次调用最后一次): 文件“C:\Users\alexe\AppData\Local\Programs\Python\Python36\Thepriceisright.py”,第 36 行,在 参赛者() 参赛者行中的文件“C:\Users\alexe\AppData\Local\Programs\Python\Python36\Thepriceisright.py”,第 24 行 protagnum=int(input(propername +", 你的出价是多少?")) ValueError: int() 以 10 为底的无效文字:'alexei'"

这是我的代码:

import random
print(" The Price is Sorta Right - 000776331")
welcomeplayer = True
contestantrow = True
def welcome():
    while True:
        global welcomeplayer
        global propername
        welcomeplayer =  input("Please enter your name using only letters")
        validname = welcomeplayer.isalpha()
        propername = welcomeplayer.capitalize()
        if validname == True:
            print( propername, " ! Come on down! You're the next contestant on the Price is (sorta) right")
            print (" Dew Drop welcomes " ,propername ," to contestants row joining EIMNOT A. HUMAN,ARTHURFICIAL EINTEL , ROBORT")
            return
        else:
            print("Please only write letters on your name tag")
            welcomeplayer = False

def contestantrow():
    while True:

        print("Dew Drop shows the price that you are bidding on")
        protagnum=int(input(propername +", what is your bid?"))
        if protagnum > 0:
            componebid = random.randint(1,1000)
            print("EIMNOT A. HUMAN bids: ",componebid)
            comptwobid = random.randint(1,1000)
            print("ARTHURFICIAL EINTEL bids: ",comptwobid)
            compthreebid =random.randint(1,1000)
            print("ROBORT bids: ",compthreebid)
        else:
            print(" Dew Drop says [Im sorry bids should start at atleast one dollar]")
            contestantrow = False
welcome()
contestantrow()

【问题讨论】:

  • 在该代码块周围使用 Try/Exception 块来捕获异常 ValueError 并请求另一个输入

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


【解决方案1】:
protagnum=int(input(propername +", what is your bid?"))

您正在将 int / string 转换为 int。 “1”会起作用,但“a”会引发 ValueError

while True:
    try:
        protagnum=int(input(propername +", what is your bid?"))
        break
    except ValueError:
        print("Invalid bid, please try again")

【讨论】:

  • 我试过了,当我输入字符串时弹出一个错误。我保留了 if protagnum > 0 部分,因为出价必须至少为 1 美元,而且不能是文本。
猜你喜欢
  • 1970-01-01
  • 2016-10-31
  • 1970-01-01
  • 2017-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多