I've created a simple program where the user is prompted to guess a number between 1 and 20. Originally my program just prompted the user if their input was too high or low. Later on I added a function that prompted the user when their input is out of range (below 1 or above 20). The program works fine, however I was wondering if my format and syntax are "correct" or "proper".
magic_number = 12
# get input from user
user_number = int(input('What is the magic number between 1 and 20 ? '))
# attempting to create an efficient while loop
while True:
if user_number < 12 and user_number >= 1:
# error message
print('Your number is too low. Please try again.')
# ask for input again
user_number = int(input('What is the magic number between 1 and 20 ? '))
elif user_number > 12 and user_number <= 20:
# error message
print('Your number is too high. Please try again.')
# ask for input again
user_number = int(input('What is the magic number between 1 and 20? '))
elif user_number < 1 or user_number > 20:
# error message
print('Your number is out of range. Please try again.')
# ask for input again
user_number = int(input('What is the magic number between 1 and 20? '))
elif user_number == magic_number:
print('Congratulations! You have guessed the magic number.')
break
If you're interested in the official "Pythonic" way to format your code, that's what the PEP8 specification is all about: https://www.python.org/dev/peps/pep-0008/.
Looking at your code, I have a couple of suggestions to possibly make things a little cleaner and easier to maintain:
Try to avoid hard-coding the same constant value (e.g. 1, 20, 12) in multiple places. That way if you want to change them later, you only have to change it in one place.
Try to avoid repeat logic in multiple places if you can help it (or move it into a function) for the same reason as #1. If you have a bug you only have to fix it in one spot.
There's a lot of things you could do, but here's an example of what it might look like just following those two comments:
magic_number = 12
min_number = 1
max_number = 20
# attempting to create an efficient while loop
while True:
# get input from user
user_number = int(input('What is the magic number between {} and {} ? '.format(min_number, max_number)))
if user_number < magic_number and user_number >= min_number:
print('Your number is too low. Please try again.')
elif user_number > magic_number and user_number <= max_number:
print('Your number is too high. Please try again.')
elif user_number < min_number or user_number > max_number:
print('Your number is out of range. Please try again.')
elif user_number == magic_number:
print('Congratulations! You have guessed the magic number.')
break
Maybe some future things to try out might be figuring out how to handle if the user doesn't enter a number or using the random module to generate a different magic number each time instead of hard-coding it to 12.
Good luck and hope that helps.
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 months ago.
I am coding a guessing game where the user inputs an integer between 1 and 100 to try and guess the correct number (26). I have to count the number of guesses the user takes to get the correct number. I want to use try and except blocks to allow the user to keep trying until they guess it right.
Right now, my code only allows the user to input one ValueError. I don't want this, I want to keep inputting until I guess the number. Attached is my code. Any help is greatly appreciated!
ex:
I want to input errors ("a", 4.20, "hello") and still have them count as guesses until I guess the number
"a" > 4.20 > "hello" > 26 => Guessed it in 3 tries
def guess(n):
secret_number = 26
if n < secret_number:
return print("Too low!")
elif n > secret_number:
return print("Too high!")
def try_exp():
try:
n = int(input("What is your guess? "))
return n
except ValueError:
n = int(input("Bad input! Try again: "))
return n
def counter():
print("Guess the secret number! Hint: it's an integer between 1 and 100... ")
n = try_exp()
i = 0
while n != 26:
guess(n)
i += 1
n = try_exp()
print(f"You guessed it! It took you {i} guesses.")
counter()
Instead of making try_exp like that, you can use a while loop that will first ask for input, and if the input is valid, then it will break out of the while loop. This is one way to implement it:
def try_exp():
first_input = True
while True:
try:
if first_input:
n = int(input("What is your guess? "))
return n
else:
n = int(input("Bad input! Try again: "))
return n
except ValueError:
first_input = False
In this, we go through an infinite loop, and we have a flag that designates whether it is the first guess or if they have already guessed before. If it is the first guess, we ask them for input, and if it is the second guess, we tell them that they gave incorrect input and ask for more input. After receiving correct input, the function returns n. If the input is incorrect which is when it is not an integer, we set first_input as false. Then, the while loop loops again. It will keep on waiting for input until they submit an integer.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
So i'm new to programming and I was trying to make a 'guess the number' program but it stops after 3 wrong guesses. I'm probably doing something really stupid so sorry if the question sounds dumb.
Thanks in advance
from random import *
number = randrange(1,100)
guess = int(input('Guess the number (between 1-100)'))
if guess == number:
print('Well done!')
while guess > number:
print('Lower')
guess = int(input('Try again: '))
while guess < number:
print('Higher')
guess = int(input('Try again: '))
By having the three cases (equal, more than, less than) handled in separated blocks, once you get past one, you don't come back to it. For instance, the program checks for equality only once, and if it fails the first time, then it never checks again. You should put all three in one block.
from random import *
number = randrange(1,100)
max_attempts = 100
for attempt in range(max_attempts):
guess = int(input('Guess the number (between 1-100)'))
if guess == number:
print('Well done!')
break
if guess > number:
print('Lower')
continue
if guess < number
print('Higher')
continue
break means to stop the loop, and continue means to go on to the next iteration of the loop. I used a for-loop since that is guaranteed to halt.
As soon as you break out of a while loop, you can not revisit that loop again. I.E for while guess > number, as soon as the user guesses a number that is <= number then you will break out the loop and the program will move past it.
Instead use this code:
from random import *
number = randrange(1,100)
guess = int(input('Guess the number (between 1-100)'))
while guess != number:
if guess < number:
print('Higher')
else:
print('Lower')
guess = int(input('Try again: '))
print('Well done!')
This program runs the while loop when guess != number. This condition will break when guess != number is False, or in other words, when the user guesses the correct number.
You need to change the while loops to this:
while guess != number:
if guess > number:
print('Higher')
guess = int(input('Try again: '))
elif guess < number:
print('Lower')
guess = int(input('Try again: '))
Basically, previously, if the guess is smaller that the number, it starts the while loop, while guess < number However, when the guess is bigger, the while loop stops because the guess is no longer smaller than the number.
To fix this, create one while loop and, in that, check to see in the guess is bigger or smaller than the number.
You could therefore, remove the guess from each if statement, and put it at the end of the while loop, if that makes sense, like this:
while guess != number:
if guess > number:
print('Lower')
elif guess < number:
print('Higher')
guess = int(input('Try again: ')
Using multiple while loops makes your debugging more complicated without any gain.
I would suggest you to use a single while loop:
from random import *
number = randrange(1,100)
guessed = False
while not guessed:
guess = int(input('Guess the number (between 1-100)'))
if guess > number:
print('Lower')
elif guess < number:
print('Higher')
else:
print('Well done!')
guessed = True
I'm not very much of a programmer neither but I Have been using python regularly lately , although i'm not sure what causes this problem , you can try this alternative code that worked pretty well for me :
from random import *
number = randrange(1,100)
guess = int(input('Guess the number (between 1-100)'))
while True:
if guess > number:
print('Lower')
guess = int(input('Try again: '))
elif guess < number:
print('Higher')
guess = int(input('Try again: '))
else:
print('Well done!')
break
import random
number = random.randint(0,10)
#print (number)
guess = int(input("I'm thinking of a number between 1 and 10. \nPlease guess what it is: "))
#print(guess)
while guess != number:
if guess > number:
print("That is too high!")
guess = int(input())
elif guess < number:
print("That is too low")
guess = int(input())
else:
print("Thats it! You win!")
I'm working out a few python coding examples and I am confused why my else statement isn't printing?
The code objective is to generate a random number, and then have the user input a guess and then depending if the guess is lower or higher than the random number for the computer to notify the user and if the user guess correctly, then to tell the user that they won.
I'm tested this out and when I input the correct number the code just ends and doesn't print out "That's it! You win!". Why is this and how can I get it to print it out?
Guess input prior to the loop will most times be different than the number to guess, therefore the loop will not enter.
You also have other more subtle bugs: for instance, input is taken twice in one loop, creating conditions for improper feedback. Further, your win is confirmed by default, that is if guess not too high, and if guess not too low, then it is a win; a positive assertion such as if guess equals number, is probably safer to declare a win.
Here is a design that segregates each actions in one place in the loop, minimizing the risks of a faulty logic.
import random
number = random.randint(0, 10)
guess = None
while guess != number:
guess = int(input())
if guess > number:
print("That is too high!")
elif guess < number:
print("That is too low")
elif guess == number:
print("Thats it! You win!")
else:
print('that was not supposed to happen')
I wrote this script but it always returns the same answer ("Your guess is too high"), no matter what the user inputs. Any insight would be helpful.
import random
number = random.randint(1, 10)
guess = input("Guess a number between 1 and 10: ")
if type(guess == int):
print(number) # this prints the randint to show the code isn't working
while(number != 0):
if(guess > number):
print("Your guess is too high!")
break
elif(guess < number):
print("That's too low.")
break
elif(guess == number):
print("Thats's right!")
break
else:
print("Please enter a number.")
Your while loop is useless, the problem of testing the input as an int is better handled with a try/except.
All together the correct answer is in Python3 :
import random
number = random.randint(1, 10)
found = False
while not found:
try:
guess = int(input("Guess a number between 1 and 10: "))
if guess > number:
print("Your guess is too high!")
elif guess < number:
print("That's too low.")
elif guess == number:
print("Thats's right!")
found = True
except ValueError:
print("Please enter a number.")
if type(guess == int):
This isn't doing what you expect. It always returns True because it's the equivalent to bool(type(False)). First make sure to convert your input to an int
guess = int(input("Guess a number between 1 and 10: "))
and then remove this if statement:
if type(guess == int):
Your problem is that this code:
if(guess > number)
is always comparing a string to an int, so once you correct that your code will be fixed.
I have just copied and pasted your code and it seems to function mostly correctly. There are some issues with it though. First, it appears that this is written for python 2 based on the way you are using the input function. However this is bad practice as the input() function in python 2 includes an implicit call to the eval() function which could allow for arbitrary code to be run.
In python 2 the better practice would be to use guess = int(raw_input("Guess a number between 1 and 10: ")).
In python 3, raw_input() has been removed and input() replaces it. So in python 3 you would use guess = int(input("Guess a number between 1 and 10: ")).
Your final else block is also indented where it should not be, although if you revise your code to make use of the advice given above, your if...else block is no longer necessary.
That's because input returns a string in Python 3. You need to call int() to make it an integer type:
guess = int(input("Guess a number between 1 and 10: "))
You're also using the type() function incorrectly. You probably want the function isinstance(): if isinstance(guess, int):
Also, in Python, we don't need parentheses like you've used. You can simply do if guess > number:
This is my first time visiting using stackoverflow--I'm new to programming and am taking a beginner's course for Python. Excited to get started!
Our second assignment asks us to create the well-known Guess the Number Game. For those of you who already know this game, I would love some help on an extra piece that's been added to it: we must list off each guess with their respective order. A sample output should look like this:
I'm thinking of an integer, you have three guesses.
Guess 1: Please enter an integer between 1 and 10: 4
Your guess is too small.
Guess 2: Please enter an integer between 1 and 10: 8
Your guess is too big.
Guess 3: Please enter an integer between 1 and 10: 7
Too bad. The number is: 5
I've got the coding down to where I have Guess 1 and Guess 3 appear, but I cannot make Guess 2 appear. I've been reworking and replacing every "while", "if", "elif", and "else" command to fix this, but can't seem to come up with a solution! Here is my code so far:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
attempts = 0
from random import randint
number = randint(0,10)
guess = eval(input("Guess 1: Please enter an integer between 1 and 10: "))
while guess != number and attempts == 0:
if guess < number:
print("Your guess is too small.")
break
if guess > number:
print("Your guess is too big.")
break
elif guess == number:
print("You got it!")
attempts = attempts + 1
if number != guess and attempts == 1:
guess = eval(input("Guess 2: Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
elif guess > number:
print("Your guess is too big.")
while guess == number:
print("You got it!")
attempts = attempts + 1
elif number != guess and attempts == 2:
guess = eval(input("Guess 3: Please enter an integer between 1 and 10: "))
if guess < number:
print("Too bad. The number is: ", number)
elif guess > number:
print("Too bad. The number is: ", number)
while guess == number:
print("You got it!")
This code outputs Guess 1 and then quits. Can anyone help me figure out how to make Guess 2 and 3 appear?? All ideas are welcome--Thanks!
You can shorten you code quite a bit, just move the input in the loop and keep looping for either three attempts using range or the user guesses correctly:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
from random import randint
number = randint(0,10)
# loop three times to give at most three attempts
for attempt in range(3):
# cast to int, don't use eval
guess = int(input("Guess 1: Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
elif guess > number:
print("Your guess is too big.")
else: # not higher or lower so must be the number
print("You got it!")
break
It would be better to use a while with a try/except to verify the user inputs a number, looping until the user has used 3 attempts or guesses correctly:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
attempts = 0
from random import randint
number = randint(0,10)
while attempts < 3:
try:
guess =int(input("Guess 1: Please enter an integer between 1 and 10: "))
except ValueError:
print("That is not a number")
continue
if guess < number:
print("Your guess is too small.")
attempts += 1
elif guess > number:
print("Your guess is too big.")
attempts += 1
else: # if it is a number and not too high or low it must be correct
print("You got it!")
break # break the loop
You cannot just use an if/else if you actually want to give the user feedback on whether their guess was too low or too high.
Also as commented don't use eval. Some good reason why are outlined here
All your while guess!=number and attempts == loops are useless, because you're either breaking out of them or incrementing attempts so their condition evaluates to False after the first iteration.
Guess 2 is never reached because either number equals guess (so number != guess is False) or attempts is still zero.
Guess 3 is never reached for the same reason. However, if guess 2 would be reached, guess 3 would never be reached because you put elif in front.
Try to get rid of the code for guess 2 and guess 3. Write all the code for guess = eval(input()) and if guess < number: ... elif guess > number: ... once and put it inside a loop. Here's a bit of pseudocode to illustrate the idea:
while attempts < 3
ask for user input
if guess equals number
print "you win"
exit the loop
else
print "that's wrong"
I used the "concatenation" method along with some of your helpful response ideas and finally got my code to work!! Thank you all so, so much for the help!! Here is the correct code for this program:
def guess():
from random import randint
number = randint(0,10)
print("I'm thinking of an integer, you have three guesses.")
attempts = 0
while attempts < 2:
guess = eval(input("Guess " + str(attempts + 1) + ": Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
attempts += 1
elif guess > number:
print("Your guess is too big.")
attempts += 1
else:
print("You got it!")
break
else:
attempts == 3
guess = eval(input("Guess 3: Please enter an integer between 1 and 10: "))
if guess < number:
print("Too bad. The number is: ", number)
elif guess > number:
print("Too bad. The number is: ", number)
else:
print("You got it!")
And then ending it with a call to function ("guess()"). Hope this serves well for those who experience this problem in the future. Again, thank you guys!