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.
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)
I am trying to add an error when a string is entered instead of an integer. I've looked at other similar posts but when I try and implement it into my code it keeps spitting errors out. I have a number guessing game between 1 and 50 here. Can't for the life of me figure out what's wrong.
import random
number = random.randrange(1, 50)
while True:
try:
guess = int ( input("Guess a number between 1 and 50: ") )
break
except ValueError:
print("Please input a number.")**
while guess != number:
if guess < number:
print ("You need to guess higher. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: ") )
else:
print ("You need to guess lower. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: "))
print ("You guessed the number correctly!")
Note that you're asking three times for the exact same input. There is really no need for that and no need for two loops at all. Just set the guess to a default value that will never be equal to the number (None) and use one single input, wrapped with try/except:
import random
number = random.randrange(1, 50)
guess = None
while guess != number:
try:
guess = int(input("Guess a number between 1 and 50: "))
except ValueError:
print("Please input a number.")
else:
if guess < number:
print("You need to guess higher. Try again.")
elif guess > number:
print("You need to guess lower. Try again.")
print("You guessed the number correctly!")
You could try running a while loop for the input statements. Checking if the input(in string format) is numeric and then casting it to int.
Sample code:
a = input()
while not a.isnumeric():
a = input('Enter a valid integer')
a = int(a)
The code executes until the value of a is an int
your code did not work because the indentation is not right
import random
number = random.randrange(1, 50)
while True:
try:
guess = int ( input("Guess a number between 1 and 50: ") ) # here
break # here
except ValueError: # here
print("Please input a number.")
while guess != number:
if guess < number:
print ("You need to guess higher. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: ") )
else:
print ("You need to guess lower. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: "))
print ("You guessed the number correctly!")
Output
Guess a number between 1 and 50: aa
Please input a number.
Guess a number between 1 and 50: 4
You need to guess higher. Try again.
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.
Attempting to generate different responses based on closeness of guess to the randomly generated number. Commented out sections are my attempts at generating a different response for a guess that is within 10 numbers of the random number.
import random
while True:
number = random.randint(1,1000)
guess = 0
tries = 0
while guess != number:
guess = input('Please enter your guess, number must be between 0 and 1000: ')
tries += 1
if guess < number:
if number - 10 <= guess:
print('Getting warm but still too low!')
print('Too Low!')
elif guess > number:
if number + 10 >= guess:
print('Getting warm but still too high!')
print('Too High!')
print("Great Guess! The number was %i and you guessed it in %s tries!") % (number, tries)
again = raw_input("Enter 'y' or 'n' to select to play again: ")
if again == 'n':
break
Yields the below output when within the specified range of the randomly generated number.
Please enter your guess, number must be between 0 and 1000: 256
Getting warm but still too low!
Too Low!
Please enter your guess, number must be between 0 and 1000: 257
Great Guess! The number was 257 and you guessed it in 13 tries!
The problem is due to indentation, as a beginner you should see how basic nested loop work. The code after indentation will yield the correct result. I have added an additional else to handle print "Too Low" and "Too High"
import random
while True:
number = random.randint(1,1000)
guess = 0
tries = 0
while guess != number:
guess = input('Please enter your guess, number must be between 0 and 1000: ')
tries += 1
if guess < number:
if number - 10 <= guess:
print('Getting warm but still too low!')
else:
print('Too Low!')
elif guess > number:
if number + 10 >= guess:
print('Getting warm but still too high!')
else:
print('Too High!')
else:
print("Great Guess! The number was %i and you guessed it in %s tries!") % (number, tries)
again = raw_input("Enter 'y' or 'n' to select to play again: ")
if again == 'n':
break
The problem is because the condition of the first 'if clause' is met first, the others condition will be ignored. You could re-arrange the if clause to show the message as you want:
if number - 10 <= guess:
print('Getting warm but still too low!')
elif guess < number:
print('Too Low!')
elif number + 10 >= guess:
print('Getting warm but still too high!')
elif guess > number:
print('Too High!')
So, I have this program where you have to guess a number and I've coded it so that the program will tell you if the number you guessed was above or below the true number. My issue is that the program ends after it tells the user to guess higher or lower. I want the program to loop such that the program won't end until the number that I preset is guessed.This is my code:
number = 10
guess = int(input("Type in an integer: "))
if guess == number:
print ("Good Job!")
elif guess < number:
print ("The number is higher")
else:
print ("The number is lower")
while guess!= number:
print ("Try Again")
print ("Done")
I tried to use a while loop to loop the program until the number was correctly guessed, but the "Try Again" script was looped forever... Thanks for the help!
Your flow control was not properly designed, but you can fix by wrapping your code in the while loop, and applying break once guess == number. The other cases where guess!=number, the loop just keeps running:
number = 10
while True:
guess = int(input("Type in an integer: "))
if guess == number:
print ("Good Job!")
break
elif guess < number:
print ("The number is higher")
else:
print ("The number is lower")
print ("Done")
You can read more about while loops in python here
while loops don't work that way. It looks like you're expecting some kind of goto where it guesses what you would like it to repeat, but all it will repeat is the content of the block. When it gets to while guess != number:, which is true, it will print that phrase, then check whether guess is not equal to number, which will still be true because it hasn't changed, forever.
Put everything that needs to be repeated into the loop:
number = 10
guess = int(input("Type in an integer: "))
while guess != number:
if guess < number:
print ("The number is higher")
else:
print ("The number is lower")
guess = int(input("Type in an integer: "))
print ("Good Job!")
print ("Done")
Try the following:
number = 10
guess = 9
while guess!= number:
guess = int(input("Type in an integer: "))
if guess == number:
print ("Good Job!")
elif guess < number:
print ("The number is higher")
elif guess > number:
print ("The number is lower")
else:
print ("Try Again")
print ("Done")