This question already has answers here:
Generate random integers between 0 and 9
(22 answers)
Closed 1 year ago.
So I am coding a simple guessing game in python. I want to make it that you can choose up to what number you want the computer to guess. Starting from one. How do I make it so that the user input of an integer is the last number the computer will guess to? This is the code:
import random
while True:
print("Welcome to odds on. Up to what number would you like to go to?")
num = int(input())
print("Welcome to odds on. Make your choice:")
choice = int(input())
cc = [1, num]
print()
computerchoice = random.choice(cc)
importing python builtin module
import random
let's say
num = 10
random.randint(1,num)
the retuerned integer will be between 1, 10
I hope you had something like this in mind. A guessing game that takes two inputs. Maximum integer and the users number choice and outputs if the user is correct or not. Game doesn't end because of the while-loop.
Working Code:
import random
while True:
try:
print("Welcome to GUESS THE NUMBER. Up to what number would you like to go to?")
maxNum = int(input())
if maxNum <= 1:
print('Number has to be greater than 0')
break
print("Guess the number:")
choice = int(input())
if choice <= 1:
print('Your Choice has to be greater than 0')
break
correctNumber = random.randint(0,maxNum)
if choice == correctNumber:
print('CORRECT')
break
else:
print('WRONG')
except:
ValueError
print('Enter a number, not something else you idiot')
And here the same code but the user only has 3 retries: (The indentations can be wrong if you copy paste my code)
import random
retry = 3
while retry != 0:
try:
print("Welcome to GUESS THE NUMBER. Up to what number would you like to go to?")
maxNum = int(input())
if maxNum <= 1:
print('Number has to be greater than 0')
break
print("Guess the number:")
choice = int(input())
if choice <= 1:
print('Your Choice has to be greater than 0')
break
correctNumber = random.randint(0,maxNum)
if choice == correctNumber:
print('CORRECT')
break
else:
print('WRONG')
retry -= 1
except:
ValueError
print('Enter a number, not something else you idiot')
if retry == 0:
print('You LOOSER')
Related
The following project requires: Your program should implement a simple guessing game with the following requirements:
Generate a random number between 1 and 50 and then have the user guess the number. The program should tell the user whether they have guessed too high or too low and allow them to continue to guess until they guess the number or enter a 0 to quit.
When they guess the number it should tell them how many guesses it took. At the end, the program should ask them if they want to play again.
For example:
Enter a guess 1-50, or 0 to quit: 25
Too high!
Enter a guess 1-50, or 0 to quit: 15
Too low!
Enter a guess 1-50, or 0 to quit: 100
Guess must be between 1 and 50!
Enter a guess 1-50, or 0 to quit: 18
That's it! You took 3 guesses to get the number.
Would you like to play again? (Y/N)
I currently have everything settled except for two issues. I cannot seem to get the play again feature to work and for some reason the first number that is guessed will not say whether it is too low or too high.
My following code:
import random
play = True
randomNum = 45 #random.randrange(1,50)
guesses = 1
num = int(input())
print("Enter a guess 1-50, or 0 to quit:", num)
if num > 50 or num < 1:
print('Guess must be between 1 and 50!')
if num == randomNum:
print("That's it! You took", guesses, "guess to get the number.")
#print("Guess must be between 1 and 50!")
while num != randomNum:
guesses += 1
num = int(input())
print("Enter a guess 1-50, or 0 to quit:", num)
if num == 0:
break
elif num > 50 or num < 1:
print('Guess must be between 1 and 50!')
elif num > randomNum:
print("Too high!")
elif num < randomNum:
print("Too low!")
if num == randomNum:
print("That's it! You took", guesses, "guesses to get the number.")
print("Would you like to play again? (Y/N)")
letter = str(input())
if letter != 'Y':
play = False
I explained above what I have tried. I do believe that the issue is that the first guess does not enter the while loop. Unsure of how to fix this though.
First issue is that your while cycle only lasts until a number is guessed. So that means after you guess the first random number, your program will finish.
In order to avoid that you should declare your $play = True$ boolean on top of the cycle so you can declare your while cycle something like this:
play = True
while play:
# game goes here.
print("Would you like to play again? (Y/N)")
letter = str(input())
if letter != 'Y':
play = False
Then your cycle should continue while letter is Y or play remains True.
Second issue is that you ask for the number outside the cycle. That is not necessary, you can ask it inside after you construct your code like the example above.
I hope this clears things up.
ps. This is my first answer, so please point out if I did something wrong!
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I want to store a list of guesses the user has already made, so that when the user makes the next guess I can check that guess against a list of previous guesses. If the guess the user just made is in that list I want to tell the user to guess again and not count it as a attempt(5 attempts at guessing correct number)
tried using the append method to append the guesses to a blank list but I'm getting a "int obj has no append method" error.
import random
def guess_a_number():
chances = 5
random_number_generation = random.randint(1,21)
while chances != 0:
choice = int(input("Guess a number between 1-20, you only have {} chances left ".format(chances)))
if choice > random_number_generation:
print("Your number is too high, guess lower")
elif choice < random_number_generation:
print("Your number is too low, guess higher")
else:
print("You guessed the correct number!!!")
break
chances -= 1
if chances == 0:
try_again = input("Do you want to try play again? ")
if try_again.lower() == "yes":
guess_a_number()
else:
print("Better luck next time")
guess_a_number()
Try keeping a list of previous guesses and then check if guess in previous_guesses: immediately after the choice. You can use continue to skip the rest and prompt them again.
Just use a set or a list to hold the previously attempted numbers and check for those in the loop.
I think you already tried something similar but by the sound of it you were attempting to append to an int.
import random
while True:
chances = 5
randnum = random.randint(1, 21)
prev_guesses = set()
print("Guess a number between 1-20, you have {} chances ".format(chances))
while True:
try:
choice = int(input("what is your guess? "))
except ValueError:
print('enter a valid integer')
continue
if choice in prev_guesses:
print('you already tried {}'.format(choice))
continue
if choice > randnum:
print("Your number is too high, guess lower")
elif choice < randnum:
print("Your number is too low, guess higher")
else:
print("You guessed the correct number!!!")
break
chances -= 1
prev_guesses.add(choice)
print("you have {} chances left".format(chances))
if chances == 0:
print("You ran out of guesses, it was {}".format(randnum))
break
try_again = input("Do you want to play again? ")
if try_again.lower() not in ("y", "yes"):
print("Better luck next time")
break
I originally wrote this program in python 2, and it worked fine, then I switched over to python 3, and the while loop working.
I don't get any errors when I run the program, but it isnt checking for what the value of i is before or during the run. The while loop and the first if loop will run no matter what.
#imports the random module
import random
#Creates variable that is used later
i = 0
#chooses a random number betweeen 1 - 100
randomNumber = random.randint(1,10)
#prints the number
print (randomNumber)
#Creates while loop that runs the program until number is guessed
while i == 0:
#Creates a variable where the answer will be stored, and then asked the question in the quotes
user_answer = input("Try to guess the magic number. (1 - 10) ")
print ("\n")
if user_answer == randomNumber:
print("You guessed correct")
break
else:
print("Incorrect. Try again.")
Thanks for any help in advance.
You are comparing something like '6' == 6, since you didn't convert the user input to an int.
Replace user_answer = input("Try to guess the magic number. (1 - 10) ") with user_answer = int(input("Try to guess the magic number. (1 - 10) ")).
user_answer will store the input as string and random.randint(1,10) will return an integer. An integer will never be equal to a string. So you need to convert user_input to integer before checking.
#imports the random module
import random
#Creates variable that is used later
i = 0
#chooses a random number betweeen 1 - 100
randomNumber = random.randint(1,10)
#prints the number
print (randomNumber)
#Creates while loop that runs the program until number is guessed
while i == 0:
#Creates a variable where the answer will be stored, and then
asked the question in the quotes
user_answer = input("Try to guess the magic number. (1 - 10) ")
# better use exception handling here
try:
user_answer = int(user_answer)
except:
pass
print ("\n")
if user_answer == randomNumber:
print("You guessed correct")
break
else:
print("Incorrect. Try again.")
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
This is my attempt at doing a higher/lower game.
import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = int(input("Please pick a number between 1 & 100: "))
if choice < number:
print("Higher")
elif choice > number:
print("Lower")
else:
print("Well done!")
while choice != number:
choice = int(input("Pick again: "))
if choice < number:
print("Higher")
elif choice > number:
print("Lower")
else:
print("Well done!")
I'm new to python and I'm just wondering is there a way of shortening the code to make it more efficient? Don't think there is a need for two 'if/elif/else' statements but can't see a way to merge them. Sorry if it's a stupid question!
Updated Code:
import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = ""
while choice != number:
choice = int(input("Please pick a number: "))
if choice < number:
print("Higher")
elif choice > number:
print("Lower")
else:
print("Well done!")
You could do something like this:
import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
while True:
try:
choice = int(input("Please pick a number between 1 & 100: "))
except ValueError:
continue
if choice < number:
print("Higher")
elif choice > number:
print("Lower")
else:
print("Well done!")
break
Here's a suggestion: initialize choice with something that is guaranteed to be unequal number (e.g. a negative number, a "sentinel"). Then you can start with the while loop right away, because the condition will always be true for the first time.
Then you can remove the first if/then/else block and the first call to input() outside the while loop.
BTW, "shorter code" is not always "efficient code" :)
You may try something like this:
import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = int(input("Please pick a number between 1 & 100: "))
while choice != number:
if choice < number:
print("Higher")
elif choice > number:
print("Lower")
choice = int(input("Pick again: "))
print("Well done")
Encapsulating the code that check user input may also be a good idea.
the if/else statements can be put on one line:
import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = ""
while choice != number:
choice = int(input("Please pick a number: "))
s = 'Higher' if choice < number else ('Lower' if choice > number else 'Well done!')
print(s)
If you want to minimize the number of characters, change the var names to just "initials" like:
import random
print("A game of Higher or Lower")
n = random.randint(1, 100)
c = ""
while c != n:
c = int(input("Please pick a number: "))
s = 'Higher' if c < n else ('Lower' if c > n else 'Well done!')
print(s)
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!