I have an exercise from the course I study from, but it gives me an error:
"Guess a number between 1 and 100: Traceback (most recent call last):
File "main.py", line 15, in <module>
guess = input("Guess a number between 1 and 100: ")
EOFError: EOF when reading a line"
How can I fix that ?
Have I done the exercise in a right way ? And just to make sure - the "break" breaks the while, right ?
# Write a program that picks a random integer from 1 to 100, and has players guess the number. The rules are:
# If a player's guess is less than 1 or greater than 100, say "OUT OF BOUNDS"
# On a player's first turn, if their guess is #within 10 of the number, return "WARM!"
# further than 10 away from the number, return "COLD!"
# On all subsequent turns, if a guess is
# closer to the number than the previous guess return "WARMER!"
# farther from the number than the previous guess, return "COLDER!"
# When the player's guess equals the number, tell them they've guessed correctly and how many guesses it took!
from random import randint
random_number = randint(1,100)
guess_count = 0
guess = input("Guess a number between 1 and 100: ")
while False:
guess_count += 1
if guess_count == 1:
if guess == random_number:
print(f'Congratulations! You have chose the correct number after the first try!')
break
else:
if abs(guess-random_number) < 11:
print("WARM!")
else:
print("COLD!")
else:
old_guess = guess
guess = input("Guess another number between 1 and 100: ")
if guess == random_number:
print(f'Congratulations! You have chose the correct number after {guess_count} tries!')
break
elif abs(random_number - guess) < abs(random_number - old_guess):
print('WARMER!')
elif abs(random_number - guess) > abs(random_number - old_guess):
print('COLDER!')
input("Press anywhere to exit ")
The reason that you are getting
Traceback (most recent call last): File "main.py", line 15, in guess = input("Guess a number between 1 and 100: ") EOFError: EOF when reading a line"
could be because you have spaces or newline before actual numbers.
Consider evaluating the user input (what if user enters a character? ) before using it. Take a look at How can I read inputs as numbers? as an example.
Also like others have pointed out, change
while False:to while True:
Hope this helps
Related
is the global constant cannot be use in while loops?
EASY_ATTEMP = 10
HARD_ATTEMP = 5
random_number = random.randint(1, 100)
difficulty = "easy"
if difficulty == "easy":
attemp = EASY_ATTEMP
already_finished = False
while not already_finished:
print(f"You have {attemp} attempts reamaining to guess the number") #<--here
guess = int(input("Make a guess: "))
And the its show the error like this:
Traceback (most recent call last):
File "main.py", line 21, in <module>
print(f"You have {attemp} attempts reamaining to guess the number")
NameError: name 'attemp' is not defined
What is going on?
I copied the code and tried run it but got no errors. I don't know what the problem is but I would suggest to make your code neater.
'''
attemp = 5
random_number = random.randint(1, 100)
difficulty = input('Do you want easy difficulty? Y or N?')
if difficulty in "Yy":
attemp = 10
while attemp > 0:
print(f"You have {attemp} attempts reamaining to guess the number") #<--here
guess = int(input("Make a guess: "))
if guess == random_number:
break
attemp -= 1
'''
For example, in the while loop, you can create a boolean with the attempt variable and reduce the number by one for ever iteration. The variable 'attemp' will always evaluate to an easy difficulty because the variable difficulty is always referencing the 'easy' str. I'm not sure how you want the code to run but in the above code I set it so that the user can decide.
I created a guess the number program and used a while loop to allow the user to continue guessing until he/she could get it right, as seen here:
import random
number = random.randrange(1, 6)
print "Guess the number, between 1 and 6"
guess = "yes"
while guess != number:
guess = int(raw_input('>'))
if guess == number:
break
print "Good job! You got it right!"
print number
elif guess > number:
print "Too High"
print number
number = random.randrange(1, 6)
elif guess < number:
print "Too Low"
print number
number = random.randrange(1, 6)
The problem is, when I am trying to guess the number, it will randomly end, whether me guessing the first time, 4 times, or 30 times. Also, I originally had,
guess = int(raw_input('>'))
in place of,
guess = "yes"
and replaced it to get rid of the extra and useless raw_input i'd initially need to add into terminal. Why am i able to make it equal "yes" and why doesn't it matter what I put there?
Example of Bug:
Guess the number, between 1 and 6
>3
Too High
2
>4
Too Low
5
>6
Too High
5
>3
Too High
1
>2
Too High
1
>5
Good job! You got it right!
5
------------------
(program exited with code: 0)
Press return to continue
It worked that time, and now:
Guess the number, between 1 and 6
>3
Too Low
4
------------------
(program exited with code: 0)
Press return to continue
The issue you have is that your while loop is testing if number matched guess after picking a new number value but before getting a new guess. This means that you'll say the player guessed wrong, but they they become right afterwards and the loop will end.
Try this instead:
import random
print "Guess the number, between 1 and 6"
guess = 'y' # the values set here don't actually matter, they just need to be different
number = 'x'
while guess != number:
number = random.randint(1, 6)
guess = int(raw_input('>'))
if guess == number:
print "Good job! You got it right!"
elif guess > number:
print "Too High"
print number
elif guess < number:
print "Too Low"
print number
I've also changed your use of random.randrange to random.randint, which will make it actually return 6s some of the time (randrange excludes the upper bound).
guess = "yes" works because guess != number will always be True on the first check in the while loop, at which point the user is asked for input. Also, in the if block, put the break statement after all the print's.
import random
number = random.randrange(1, 6)
print "Guess the number, between 1 and 6"
guess = "yes"
while guess != number:
guess = int(raw_input('>'))
if guess == number:
break
print "Good job! You got it right!"
print number
break
elif guess > number:
print "Too High"
print number
number = random.randrange(1, 6)
break
elif guess < number:
print "Too Low"
print number
number = random.randrange(1, 6)
break
Can someone please help me understand the following issue...
I'm having problems executing my try/except block in my simple number guessing game. The function containing my error handling works fine if I remove the integer portion of the initial input. But if I do this, the rest of the game doesn't work, because from my understanding Python3 takes input and stores it as a string. So how can I get my exception to execute? Any help is much appreciated.
Thanks,
# number game
import random
print ("Welcome to the guessing number game!\n\n")
winning_number= random.randrange(1, 11)
guess = int(input("Can you guess the lucky number.\nHint it's between 1 and 10!\n"))
def is_number(guess):
try:
int(guess)
except ValueError:
print ('You need to type a number\n')
guess = int((input("Please input a number\n")))
game(guess)
def compare(guess):
if guess > winning_number:
print ("Wrong, you're guess is too high.\n")
guess = int(input("Guess againn\n"))
game(guess)
else:
print ("Wrong, you're guess is too low.\n")
guess = int(input("Guess again\n"))
game(guess)
def game(guess):
is_number(guess)
if guess == winning_number:
print ("You win!, You guessed the number!")
else:
compare(guess)
game(guess)
Here is what I get when I input anything other than an integer...
Welcome to the guessing number game!
Can you guess the lucky number.
Hint it's between 1 and 10!
f
Traceback (most recent call last):
File "C:/Users/mickyj209/PycharmProjects/Practice/NumberGuess.py", line 10, in
guess = int(input("Can you guess the lucky number.\nHint it's between 1 and 10!\n"))
ValueError: invalid literal for int() with base 10: 'f'
Process finished with exit code 1
You forgot to save the value that time (guess = int(guess)), you're not returning anything there, and you're just having the program run the function but not making a decision based on the result. You also have an int(input(... in the exception handling, which could itself generate an exception which won't be caught. The initial guess isn't in a try block, either.
You could refactor this program:
def game():
print ("Welcome to the guessing number game!\n\n")
winning_number = random.randrange(1, 11)
print("Can you guess the lucky number?\nHint: it's between 1 and 10!\n")
while 1:
try:
guess = int(input("Please input a number\n"))
except ValueError:
continue
if guess > winning_number:
print('Wrong - your guess is too high.')
elif guess < winning_number:
print('Wrong - your guess is too low.')
else:
print('You win! You guessed the number!')
break
I try to make a simple guessing game with the "Python programming for absolute beginner" book. Game should generate random number from 0 to 10, then take player's guesses and print "Too high!", if the guessed number is too high, or "Too low!" if the number is too low. After each guess, game adds 1 to the number of guesses. It ends, when the player's guess is correct and displays number of guesses taken.
My code is exactly the same, as code in the book, but when I run it in IDLE, I get "invalid syntax" error on "tries += 1" line. When I delete this line, the error happens on the next line etc. When I run it from file, it just opens and closes immediately. I use Python 3.4.1.
import random
number = random.randint(0,10)
player_guess = int(input("What's your guess?"))
tries = 1
while player_guess != number:
if player_guess > number:
print("Too high!")
else:
print("Too low!")
player_guess = int(input("What's your guess?")
tries += 1
print("Congrats!")
print(tries)
input("\n\nPress any key...")
You're missing a closing parentheses ) on the above line to complete the int conversion.
import random
print"hello what is your name?"
name = raw_input()
print"hello", name
print"wanna play a game? y, n"
choice = raw_input()
if choice =='y':
print'good lets start a number guessing game'
elif choice =='n':
print'maybe next time'
exit()
random.randint(1,10)
number = random.randint(1,10)
print'pick a number between 1-10'
numberofguesses = 0
guess = input()
while numberofguesses < 10:
if guess < number:
print"too low"
elif guess > number:
print"too high"
elif guess == number:
print'your correct the number is', number
break
if guess == number:
print'CONGRATS YOU WIN THE GAME'
when i enter my guess into the program it only gives me one output for example
i enter 8
programs output is "too high"
but when i guess again the output is blank, how do i fix this?
hello what is your name?
ed
hello ed
wanna play a game? y, n
y
good lets start a number guessing game
pick a number between 1-10
2
too low
>>> 5
5
>>> 3
3
>>> 2
2
>>>
I think this is what you want:
numberofguesses = 0
while numberofguesses < 10:
guess = input() #int(raw_input("Pick a number between 1 and 10: ")) would be much better here.
numberofguesses+=1
if guess < number:
print "too low"
elif guess > number:
print "too high"
elif guess == number:
print 'your correct the number is', number
break
With your version of the code, you guess once. If you're wrong, your program tries the same guess over and over again forever (assuming your break was actually supposed to be indented in the elif). You might be typing new guesses into the terminal, but your program never sees them. If the break was actually in the correct place in your code, then you guess once and whether write or wrong it exits the loop right away.
your break is outside of your ifstatement
It will execute while loop one time and break no matter what