Repeating a loop until the right random value is selected - python

I am trying to make a program that randomly selects a number, and then you have to guess that number until you get that number correct. So far it works so that I can guess one time, and then the program ends, i need it to repeat my input until i guess the correct number.
import random
a = random.randint(1,20)
print("My number is somewhere between one and twenty")
b = int(input("What is your guess?: "))
if b == a:
print("You guessed my number!")
elif b > a:
print("You're number is too large")
elif b < a:
print("You're number is too small")
input("\n\nPress the enter key to exit")

You're missing the while loop which will execute until a certain condition is met. In your case, the code would be like this:
import random
a = random.randint(1,20)
print("My number is somewhere between one and twenty")
b = 0 # We create the variable b
while b != a: # This executes while b is not a
b = int(input("What is your guess?: "))
if b > a:
print("Your number is too large")
elif b < a:
print("Your number is too small")
print("You guessed my number!") # At this point, we know b is equal to a
input("\n\nPress the enter key to exit")

It's working
import random
a = random.randint(1,20)
print("My number is somewhere between one and twenty")
while True: #missing the while loop
b = int(input("What is your guess?: "))
if b == a:
print("You guessed my number!")
exit()
elif b > a:
print("You're number is too large")
elif b < a:
print("You're number is too small")

Related

Wrong Output Guess the Number

I'm making a small game that chooses a random number in the given limit and the user tries to guess the number. I tried to add chances so you could try multiple times. Why is it returning the guessed number multiplied by the chance number?
def guessTheNumber():
chances = int(input('How many chances do you want: '))
limit = int(input('Input limits: '))
inputnum = int(input('Input number: '))
x = 1
while x <= chances:
randomnum = randomNum(limit)
if inputnum == randomnum:
print('you won!')
x+=1
continue
else:
print('THe number was {}'.format(randomnum))
replay()
When called it returns:
guessTheNumber():
How many chances do you want: 3
Input limits: 10
Input guess: 4
you won!
you won!
you won!
The number was 4
play again?: no
Goodbye
It loops until you have won 'chances' times. Look at the indent of the various lines.
You have the game backwards. The user is selecting a number once, and then the computer guesses every time through the loop.
You're only incrementing x when the computer guesses right, because x += 1 is in the if block, and you don't stop the loop when the guess is correct. So you'll get chances You won messages, then the loop stops.
The correct code is:
def guessTheNumber():
chances = int(input('How many chances do you want: '))
limit = int(input('Input limits: '))
randomnum = randomNum(limit)
x = 1
while x <= chances:
inputnum = int(input('Input number: '))
if inputnum == randomnum:
print('you won!')
break
x+=1
else:
print('The number was {}'.format(randomnum))
replay()

How to fix guessing game

The objective is to create a simple program that generates a number between 1 and 100, it will then ask the user to guess this, if they guess outside of the number range it should tell them to guess again, if not it should tell them whether their guess was too high or too low, prompting them to guess again. Once they do guess the correct number it should tell them they've won and the number of tries it took for them to guess it correctly.
Here is what I have so far
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
return play_game
else:
print("Invalid number.")
return play_game()
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
play_game()
The issue I'm currently running into is when it checks to see if their guess was between 1-100 instead of moving on to weather or not their number was too how or to low, it stays and loops.
If anyone could help me with this issue and review the code in general I'd appreciate it.
I think the problem is with some indentation and some logical problems in the flow.
When you call play_game() from inside the game, it starts a completely different game
with different random_number.
A good code that satisfies your condition might look like the following
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
else:
print("Invalid number.")
play_game()
You could re-adjust your code:
1. if no. within range, run your high, low, match checks
2. break if guess matches the no
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 0
while True:
count += 1
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
break
else:
print("Invalid number, try again")
play_game()
The issue you are running into is because of incorrect indentation. The if-else statements that check whether the number is within the valid range are at the same indentation level as the while loop and thus are not executed within it. Simply indenting should fix the problem.
Furthermore, you have called play_game without parenthesis, making it incorrect syntax for a function call. However, rather than checking if the number is greater than 0 and lesser than 100, it would more optimal to check whether number is lesser than 0 or greater than 100, and if that is the case, print invalid number and call play_game().
It would look something like this:
while True:
if guess < 0 and guess > 100:
print ("Invalid number.")
return play_game()
The rest of your code looks good. I've also attached the link on the section of indentations of the Python documentation here.

How can I make this python code shorter and more efficient [closed]

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)

Guess Random Number Why i m not able to enter input - python

Below is my code to generate random number between 0 - 9 and checking with user input whether it is higher lower or equal. When I run the code, it is not taking input and showing
error in 'guessNumber = int(input("Guess a Random number between 0-9")) File "", line 1 '
Can somebody please tell me where I'm making mistake
#Guess Random Number
#Generate a Random number between 0 to 9
import random
turn = 0
def guessRandom():
secretNumber = random.randint(0,9)
guessNumber = int(input("Guess a Random number between 0-9"))
while secretNumber != guessNumber:
if(secretNumber > guessNumber):
input("You have Guessed the number higher than secretNumber. Guess Again!")
turn = turn + 1
elif (secretNumber < guessNumber):
input("You have guessed the number lower than secretNumber. Guess Again! ")
turn = turn + 1
if(secretNumber == guessNumber):
print("you Have Guessed it Right!")
guessRandom()
I think guessRandom() was meant to be outside of the method definition, in order to call the method. The guessNumber variable never changes since the inputs are not assigned to be guessNumber, thus it will continuously check the initial guess. Also, the less than / greater than signs seem to conflict with the intended message. Additionally, turn is outside of the scope of the method.
#Generate a Random number between 0 to 9
import random
def guessRandom():
secretNumber = random.randint(0, 9)
guessNumber = int(input("Guess a Random number between 0-9: "))
i = 0
while secretNumber != guessNumber:
if secretNumber < guessNumber:
print "You have guessed a number higher than secretNumber."
i += 1
elif secretNumber > guessNumber:
print "You have guessed a number lower than secretNumber."
i += 1
else:
print("you Have Guessed it Right!")
guessNumber = int(input("Guess Again! "))
return i
turn = 0
turn += guessRandom()
EDIT: Assuming you're using input in Python3 (or using raw_input in older versions of Python), you may want to except for ValueError in case someone enters a string. For instance,
#Generate a Random number between 0 to 9
import random
def guessRandom():
secretNumber = random.randint(0, 9)
guessNumber = input("Guess a Random number between 0-9: ")
i = 0
while True:
try:
guessNumber = int(guessNumber)
except ValueError:
pass
else:
if secretNumber < guessNumber:
print "You have guessed a number higher than secretNumber."
i += 1
elif secretNumber > guessNumber:
print "You have guessed a number lower than secretNumber."
i += 1
else:
print("you Have Guessed it Right!")
break
guessNumber = input("Guess Again! ")
return i
turn = 0
turn += guessRandom()
I changed the while loop condition to True and added a break because otherwise it would loop indefinitely (comparing an integer to a string input value).

Need to validate user input as an integer

I want to add code so that if the user enters anything other than an integer, it prints something out. On the last line where I wrote
if guess != int I want the program to decide if the guess is anything other than a number.
import random
number = random.randint(1,100)
guess = 0
guesses = 0
while guess != number:
guess = int(input("Guess my number between 1 and 100(inclusive):"))
guesses = guesses + 1
if guess == number:
print("Well done! My number is:"number,"You had",guesses,"guesses"
elif guess < number:
print ('sorry, my number is higher')
elif guess > number:
print ('Sorry, My number is lower')
if guess != int:
print ("Enter a Number!!")
Let's use good old EAFP
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.
guess = input("Guess my number between 1 and 100(inclusive):")
try:
guess = int(guess)
except ValueError:
print ("Enter a Number!!")
else:
if guess == number:
print("Well done! My number is:"number,"You had",guesses,"guesses"
elif guess < number :`
print ('sorry, my number is higher')
else:
print ('Sorry, My number is lower')
After I was kindly warned about raw input always being a string. Perhaps this is what you need
guess =int(input("Guess my number between 1 and 100(inclusive):"))
guesses = guesses + 1
try:
guess = int(guess)
if guess == number:
print("Well done! My number is:", number,"You had",guesses,"guesses")
elif guess < number :
print ('sorry, my number is higher')
elif guess > number:
print ('Sorry, My number is lower')
except:
print("Enter a number!")
Do notice that you don't use guesses anywhere, and that this isn't a loop so it will repeat itself only once and that also you never defined what your number is. Perhaps a more complete example would be this:
guesses = 0
number = 10
while True:
try:
guess =int(input("Guess my number between 1 and 100(inclusive):"))
except:
print("Enter a number!")
continue
guesses = guesses + 1
if guess == number:
print("Well done! My number is:", number,"You had",guesses,"guesses")
break
elif guess < number :
print ('sorry, my number is higher')
elif guess > number:
print ('Sorry, My number is lower')
I like #Nsh's answer - it's more common and probably better in practice. But if you don't like using try-catch statement and a fan of sql...
import random
my_number = random.randint(1,100)
your_number = None
counter = 0
While your_number != my_number:
s = input("Guess my number between 1 and 100(inclusive):")
counter += 1
if all(i in '0123456789' for i in s):
your_number = int(s)
if my_number == your_number: print 'Well done!'
else: print 'sorry, my number is {}'.format('higher' if my_number > your_number else 'lower')
Enjoy.

Categories

Resources