python - Number guessing game: How can I accept input that says "guess =" before the number? -
import random guess = input("what guess?") answer = random.randint(0,100) while guess != answer: try: guess = float(guess) if guess > answer: print ("your guess high!") elif guess < answer: print ("your guess low!") elif guess == answer: print ("congratulations!") break guess = input("what guess?") continue except valueerror: print ("bad input. try again!") guess = input("what guess?")
so code works except when enter example: guess = 30, seems input invalid...how can make accepts correct guess?
new python here :) thanks.
i copied , pasted code python 3.5, and....apart needing indent after while statement worked fine.
are inputting number: 30
...or "guess = 30"? because cause problem since it's not number. need input number. :)
if want accept "guess = 30" then:
import random import re ###<-add guess = input("what guess?") answer = random.randint(0,100) while guess != answer: try: guess = re.sub("[^0-9]", "", guess) ###<- add guess = float(guess) if guess > answer: print ("your guess high!") elif guess < answer: print ("your guess low!") elif guess == answer: print ("congratulations!") break guess = input("what guess?") continue except valueerror: print ("bad input. try again!") guess = input("what guess?")
these 2 lines use regular expressions strip input of non numeric characters before processing.
Comments
Post a Comment