I was making this simple python game where you guess a random number. I was wondering how you would loop it so it would keep going until you get the correct number. It needs to do that without changing the number while the player is guessing.
import random
print('Welcome to Guess The Number V1.0')
print('the rules are simple guess a number 1-6 and see if youre correct')
number = random.randint(0,7)
#------------------------------------------------------
guess = int(input('Enter a number:'))
print(guess)
#------------------------------------------------------
if guess > number:
print('Your guess was to high')
if guess < number:
print('Your guess was to low')
#-------------------------------------------------------
if guess == number:
print('Correct!')
If you used a while loop you could make it run without needing to stop it and reload the site. it would look like this
while guess != number:
if guess > number:
print('Your guess was to high')
if guess < number:
print('Your guess was to low')
#-------------------------------------------------------
if guess == number:
print('Correct!')
You would use a while loop to repeat the guessing procedure like so:
import random
print('Welcome to Guess The Number V1.0')
print('the rules are simple guess a number 1-6 and see if youre correct')
number = random.randint(0,7)
#------------------------------------------------------
guess = int(input('Enter a number:'))
while guess != number: #Following code only runs if the guess isn't correct
if guess > number:
print('Your guess was to high')
if guess < number:
print('Your guess was to low')
guess = int(input('Enter a number:')) #Need this here to ask for another guess
#and avoid an infinite loop
print('Correct!')
Hope that helps!
Related
My assignment is to make a secret number, which is 26, and make a guessing game saying the guess is either "too low" or "too high". I made two functions, int_guess for if the input is an integer and not_int_guess for when the input is not an integer. The problem that i have though is when im counting the amount of guesses, i dont know how to make both functions share a count of how many guesses they inputted.
print("Guess the secret number! Hint: it's an integer between 1 and 100...")
secret_num = 26
guess = int(input("What is your guess? "))
def int_guess(guess):
count = 0
while guess != 26:
if guess > secret_num:
print("Too high!")
guess = int(input("What is your guess? "))
count += 1
elif guess < secret_num:
print("Too low!")
guess = int(input("What is your guess? "))
count += 1
else:
print("You guessed it! It took you", count, "guesses.")
def not_int_guess(guess,count):
print("Bad input! Try again: ")
guess = int(input("What is your guess? "))
while guess != 26:
if guess > secret_num:
print("Too high!")
guess = int(input("What is your guess? "))
elif guess < secret_num:
print("Too low!")
guess = int(input("What is your guess? "))
else:
print("You guessed it! It took you", count, "guesses.")
try:
int_guess(guess)
except:
not_int_guess(guess,count)
One part of the assignment that i need to have is a try and except, the problem is that the count will reset to zero if the except is used, but i need the count to carry over to the exception case. I tried carrying the "count" variable over to the not_int_guess by placing it like not_int_guess(guess,count) but that doesnt work for a reason i dont understand.
Instead of using two functions, use the try and except within the while loop. That way everything is much neater and more efficient (also good to define functions before any main code):
def int_guess(secret_num):
count = 0
guess = 0 #Just defining it here so everything in the function knows about it
while guess != secret_num:
try:
guess = int(input("What is your guess? "))
except ValueError as err:
print("Not a number! Error:", err)
continue #This will make the program skip anything underneath here!
if guess > secret_num:
print("Too high!")
elif guess < secret_num:
print("Too low!")
count += 1 #Adds to count
#This will run after the while loop finishes:
print("You guessed it! It took you", count, "guesses.")
#Main code:
print("Guess the secret number! Hint: it's an integer between 1 and 100...")
int_guess(26)
Like this, the function will run until the user has guessed the number no matter what they input, while also keeping count through any errors
You can use the count variable outside the functions to use it in both the variables globally.
I have also made some changes to the code to make it work properly
print("Guess the secret number! Hint: it's an integer between 1 and 100...")
secret_num = 26
count = 0
guess = 0
def int_guess(guess):
count = 0
while guess != 26:
guess = int(input("What is your guess? "))
if guess > secret_num:
print("Too high!")
count += 1
elif guess < secret_num:
print("Too low!")
count += 1
else:
print("You guessed it! It took you", count, "guesses.")
def not_int_guess(guess):
print("Bad input! Try again: ")
int_guess(guess)
try:
int_guess(guess)
except:
not_int_guess(guess)
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.
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 am brand new to learning Python and am building a very simple number guessing game. The user guesses a number between 1-100, and are given feedback on whether their guess is too low or too high. When they guess the number correctly, the program tells them how many guesses they took. What I need help with: telling the user when they guessed a duplicate number if they have entered it already. I also want to exclude any duplicate guesses from the final guess count. What is the easiest way to do this?
Here is my game so far:
import random
print("Guess a number between 1-100")
the_number = random.randint(1, 100)
guess = int(input(""))
tries = 0
while guess != the_number:
if guess > the_number:
print("Lower")
if guess < the_number:
print("Higher")
guess = int(input("Guess again: "))
tries += 1
if guess == the_number:
print("You win! The number was", the_number)
print("And it only took you", tries, "tries!\n")
Keep track of the numbers guessed, only increasing if the user has not guessed a number already in our guessed set:
import random
print("Guess a number between 1-100")
the_number = random.randint(1, 100)
tries = 0
# store all the user guesses
guessed = set()
while True:
guess = int(input("Guess a number: "))
# if the guess is in our guesses set, the user has guessed before
if guess in guessed:
print("You already guessed that number!")
continue
# will only increment for unique guessed
tries += 1
if guess == the_number:
print("You win! The number was", the_number)
print("And it only took you", tries, "tries!\n")
break
elif guess > the_number:
print("Lower")
# if it's not == or >, it has to be <
else:
print("Higher")
# add guess each time
guessed.add(guess)
You also had some logic in regard to your ordering like taking a guess outside the loop which could have meant you never entered the loop if the user guessed first time.
this is how you should write the code.
import random
debug = True
def number_guessing():
previous_guesses = set()
tries = 0
print("Guess a number between 1-100")
random_number = random.randint(1, 100)
while True:
guess = int(input())
if guess in previous_guesses:
print("You already tried that number")
continue
previous_guesses.add(guess)
tries += 1
if random_number < guess:
print(f"Lower => previous attempts [{previous_guesses}] tries [{tries}]") if debug is True else None
elif random_number > guess:
print(f"Higher => previous attempts [{previous_guesses}] tries [{tries}]") if debug is True else None
elif guess == random_number:
print("You win! The number was", random_number)
print(f"And it only took you {tries} attempt{'s' if tries>1 else ''}!\n")
break
number_guessing()
I'm new to python and I'm trying to make a simple Guess the number game, and I'm stuck in an if statement in a while loop. here is the code.
I'm experiencing it at the Your guess it too high and the low one. I tried breaking it, but it simply stops the whole things
def guess_the_number():
number = random.randrange(20)
guessesMade = 0
print('Take a guess')
guess = input()
guess = int(guess)
while guessesMade < 6:
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
print'You got it in', guessesMade, 'guess(es)! Congratulaions!'
else:
print'I\'m sorry, the number was', number
You never increment guessesMade so guessesMade < 6 will always be True. You need to modify this value within your loop. You also need to move your prompt for user input into the loop
while guessesMade < 6:
guess = int(input('Take a guess'))
if guess < number:
print('Your guess is too low.')
guessesMade += 1
elif guess > number:
print('Your guess is too high.')
guessesMade += 1
else:
break