Python returning untrue values? - python

I'm a newbie to Python, and I was working on a number guessing game in Python. However, when I set up the parameters:
import random
numberchosen = random.randint(0,100)
numberchosenstr = str(numberchosen)
print ("Let's play a number game")
numberguessed = input("Guess a number ")
print ("You guessed " + numberguessed)
if numberguessed > '100':
print ("You guessed too high, choose a number below 100")
if numberguessed < '0':
print ("You guessed too low, choose a number above 0")
if numberguessed != numberchosen:
print ("wrong")
But, when I run the module, and choose the number 5 for instance, or any number that is within the correct range yet not the correct number, it always returns
Let's play a number game
Guess a number 5
You guessed 5
You guessed too high, choose a number below 100
wrong
So, my question is, why does Python return the >100 error, and what are some ways to fix it?

You're comparing strings, which is done lexicographically (i.e. alphabetically, one character at a time). But even if one were an int, strings are always greater than numbers. You need to take the quotes off your comparison number, and call int() on your input, like so:
numberguessed = int(input("Guess a number ")) # convert to int
print ("You guessed {}".format(numberguessed)) # changed this too, since it would error
if numberguessed > 100: # removed quotes
print ("You guessed too high, choose a number below 100")
if numberguessed < 0: # removed quotes
print ("You guessed too low, choose a number above 0")

Related

number guessing game with hints after certain number of tries. python

Thank you for your patience everyone.
Thank you Ben10 for your answer. (posted below with my corrected print statements) My print statements were wrong. I needed to take the parenthesis out and separate the variable with commas on either side.
print("It only took you ", counter, " attempts!")
The number guessing game asks for hints after a certain number of responses as well as the option to type in cheat to have number revealed. One to last hints to to let the person guessing see if the number is divisible by another number. I wanted to have this hint available until the end of the game to help narrow down options of the number.
Again thank you everyone for your time and feedback.
guessing_game.py
import random
counter = 1
random_ = random.randint(1, 101)
print("Random number: ", random_) #Remove when releasing final prduct
divisor = random.randint(2, 6)
cheat = random_
print("I have generated a random number for you to guess (between 1-100)" )
while counter < 10:
if counter == 3:
print("Nope. Do you have what it takes? If not, type in 'cheat' to have the random number revealed. ")
if random_ % divisor == 0:
print("Not it quite yet. The random number can be divided by ", divisor, ". ")
else:
print("Not it quite yet, The random number is NOT divisible by ", divisor, ". ")
guess = input("What is your guess? ")
#If the counter is above 3 then they are allowed to type 'cheat'
if counter <= 3 and guess.lower() == "cheat":
print("The number is ", cheat, ".")
#If the player gets it right
elif int(guess) == random_:
print("You guessed the right number! :)")
print("It only took you ", counter, " attempts!")
#Break out of the while loop
break
#If the user types cheat , then we don't want the lines below to run as it will give us an error, hence the elif
elif int(guess) < random_:
print("Your guess is smaller than the random number. ")
elif int(guess) > random_:
print("Your guess is bigger than the random number. ")
#Spacer to seperate attempts
print("")
counter += 1
#Print be careful as below code will run if they win or lose
if int(guess) != random_:
print("You failed!!!!!!!!!!!!!!!!")
I rewrite the code, to allow it to be more versitile. Noticed quite a few errors, like how you forgot to put a closing bracket at the end of a print statement. Also in the print statements you were doing String concatenation (where you combine strings together) incorrectly.
import random
counter = 1
random_ = random.randint(1, 101)
print("Random number: " + str(random_)) #Remove when releasing final prduct
divisor = random.randint(2, 6)
cheat = random_
print("I have generated a random number for you to guess (between 1-100)" )
while counter < 5:
if counter == 3:
print("Nope. Do you have what it takes? If not, type in 'cheat' to have the random number revealed. ")
if random_ % divisor == 0:
print("Not it quite yet. The random number can be divided by " + str(divisor) + ". ")
else:
print("Not it quite yet, The random number is NOT divisible by " + str(divisor) + ". ")
guess = input("What is your guess? ")
#If the counter is above 3 then they are allowed to type 'cheat'
if counter <= 3 and guess.lower() == "cheat":
print("The number is " + str(cheat) +".")
#If the player gets it right
elif int(guess) == random_:
print("You guessed the right number! :)")
print("It only took you " + str(counter) + " attempts!")
#Break out of the while loop
break
#If the user types cheat , then we don't want the lines below to run as it will give us an error, hence the elif
elif int(guess) < random_:
print("Your guess is smaller than the random number. ")
elif int(guess) > random_:
print("Your guess is bigger than the random number. ")
#Spacer to seperate attempts
print("")
counter += 1
#Print be careful as below code will run if they win or lose
if int(guess) != random_:
print("You failed!!!!!!!!!!!!!!!!")

Checking 2 int variables

I have 2 int variables. One contains user input, and the other is a computer generated number (0,99).
How can I check if the input variable contains a digit that is also in the computer generated numbers?
For a first example, if the user enters 45 and the computers guess was 54?
Or, if the user guesses one of the digits correctly, like, the user guesses 23, and the computer guess is 35?
Guess = int(input("Please guess a number between 0 to 99:"))
if Guess <= 99 and Guess >= 0:
break
except ValueError:
print("")
RandomNum = random.randint(0,99)
print("Random Generated Number",RandomNum)
if RandomNum == Guess:
print("Jackpot!! You win 100 !")
if RandomNum == Guess[0,1]:
print("Right Digits,wrong order. You win 10")
It appears that you want to check if the user's number contains the same digit as the computer-generated numbers.
If you only ever going to have two digits numbers you can get away with if str(RandomNum) == str(Guess)[::-1]:. This will check if the string value of RandomNum is equal to the string value of Guess in reverse.
If you want a more generalized solution then first you will need to define the desired behavior.

How can i make sure this while loop can rerun my random number code without going forever?

I created a guess the number program and used a while loop to allow the user to continue guessing until he/she could get it right, as seen here:
import random
number = random.randrange(1, 6)
print "Guess the number, between 1 and 6"
guess = "yes"
while guess != number:
guess = int(raw_input('>'))
if guess == number:
break
print "Good job! You got it right!"
print number
elif guess > number:
print "Too High"
print number
number = random.randrange(1, 6)
elif guess < number:
print "Too Low"
print number
number = random.randrange(1, 6)
The problem is, when I am trying to guess the number, it will randomly end, whether me guessing the first time, 4 times, or 30 times. Also, I originally had,
guess = int(raw_input('>'))
in place of,
guess = "yes"
and replaced it to get rid of the extra and useless raw_input i'd initially need to add into terminal. Why am i able to make it equal "yes" and why doesn't it matter what I put there?
Example of Bug:
Guess the number, between 1 and 6
>3
Too High
2
>4
Too Low
5
>6
Too High
5
>3
Too High
1
>2
Too High
1
>5
Good job! You got it right!
5
------------------
(program exited with code: 0)
Press return to continue
It worked that time, and now:
Guess the number, between 1 and 6
>3
Too Low
4
------------------
(program exited with code: 0)
Press return to continue
The issue you have is that your while loop is testing if number matched guess after picking a new number value but before getting a new guess. This means that you'll say the player guessed wrong, but they they become right afterwards and the loop will end.
Try this instead:
import random
print "Guess the number, between 1 and 6"
guess = 'y' # the values set here don't actually matter, they just need to be different
number = 'x'
while guess != number:
number = random.randint(1, 6)
guess = int(raw_input('>'))
if guess == number:
print "Good job! You got it right!"
elif guess > number:
print "Too High"
print number
elif guess < number:
print "Too Low"
print number
I've also changed your use of random.randrange to random.randint, which will make it actually return 6s some of the time (randrange excludes the upper bound).
guess = "yes" works because guess != number will always be True on the first check in the while loop, at which point the user is asked for input. Also, in the if block, put the break statement after all the print's.
import random
number = random.randrange(1, 6)
print "Guess the number, between 1 and 6"
guess = "yes"
while guess != number:
guess = int(raw_input('>'))
if guess == number:
break
print "Good job! You got it right!"
print number
break
elif guess > number:
print "Too High"
print number
number = random.randrange(1, 6)
break
elif guess < number:
print "Too Low"
print number
number = random.randrange(1, 6)
break

Simple Guess My Number Game in Python - invalid syntax

I try to make a simple guessing game with the "Python programming for absolute beginner" book. Game should generate random number from 0 to 10, then take player's guesses and print "Too high!", if the guessed number is too high, or "Too low!" if the number is too low. After each guess, game adds 1 to the number of guesses. It ends, when the player's guess is correct and displays number of guesses taken.
My code is exactly the same, as code in the book, but when I run it in IDLE, I get "invalid syntax" error on "tries += 1" line. When I delete this line, the error happens on the next line etc. When I run it from file, it just opens and closes immediately. I use Python 3.4.1.
import random
number = random.randint(0,10)
player_guess = int(input("What's your guess?"))
tries = 1
while player_guess != number:
if player_guess > number:
print("Too high!")
else:
print("Too low!")
player_guess = int(input("What's your guess?")
tries += 1
print("Congrats!")
print(tries)
input("\n\nPress any key...")
You're missing a closing parentheses ) on the above line to complete the int conversion.

Python - Random number guessing game - Telling user they are close to guessing the number

I have a quick question.
I want to make my number guessing game tell the user if they are 2 numbers away from guessing the random number.
I do not want the program to say how many numbers away the user is.
The way I'm thinking is this. I just can't put this into proper code.
Random_number = 5
guess = 3
print('you are close to guessing the number!')
guess = 7
print('you are close to guessing the number!')
guess = 2 #more than 2 away from the number
print('you are NOT close to guessing the number')
I am going to start by saying my python is rusty and someone please fix it if im off alittle.
All you need to do if use an if statement.
random = 5
guess = 3
if( guess == random ):
print('your right!')
elif ( abs (guess - random) <= 2 ):
print('you are close to guessing the number!')
else:
print('you are not close enough!')
Edited the elseif logic according to #9000's suggestion.
Try this:
for number in range (2):
if guess == Random_number:
print('you guessed the number!')
if guess - number == Random_number or guess + number == Random_number:
print('you are close to guessing the number!)
Here is the explanation. The first line is saying "for the numbers in the range of 0 to 2 set number equal to that number." So the next if part will run 3 times: for number equaling 0, 1, and 2. So, if your guess is within 2 of the random number, it will print you are close to the random number. If you have the correct guess, it will obviously print you guessed it correctly.

Categories