[英]Python Tkinter: I'm not sure how to align the guess input with the question
[英]How can I make sure users are turning in correct input, for Guess game in python 3.5.1?
這是我的代碼:
from random import randint
print("What is your name?")
name=input()
tries=0
number= randint(1,100)
print("Hello, %s guess a number from 0 to 100" % name)
while tries < 8:
print("Take a Guess")
guess=input()
guess=int(guess)
if guess < number:
print("Too Low")
tries += 1
if guess > number:
print("Too High")
tries += 1
if guess == number:
break
if guess == number:
print("You got it, in %s tries" % tries)
if guess != number:
print("Sorry try again!")
但是它給出了一個錯誤:
Traceback (most recent call last):
File "/Users/Zuazua/PycharmProjects/untitled/GuessMyNumber2.py", line 10, in <module>
guess=int(guess)
ValueError: invalid literal for int() with base 10: '23!'
將行guess=int(guess)
更改為此:
guess=int(re.search(r'\d+', guess).group())
嘗試使用guess=int(guess)
解析輸入的值可能導致不同的異常。 修復它的快速而又骯臟的方法-將其包裝在try ... except
塊。 喜歡:
try:
guess=int(guess)
except ValueError:
print("Cannot understand your input. Pls, try again")
continue
此代碼將捕獲在解析期間發生的所有ValueError異常。 您可以在此處找到有關異常的更多信息: https : //docs.python.org/3/tutorial/errors.html#errors-and-exceptions
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.