Comparing two variables in Python not working? [duplicate] - python

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 months ago.
I'm writing a simple program that compares two variables
from random import randint
result = (randint(1, 6))
guess = input('Guess the number: ')
if guess == result:
print('You got it right')
else:
print('Wrong')
print(result)
The program sets the variable result as a random number, and then the user inputs a number that they guess. However, even when they get the number right, it says that they were wrong.
How can I get it so that when they get the correct number, it says that they are right?
Thanks in advance!

Either make INTEGER type to STRING or vice versa so that comparison can be done. Two different types (INT and STR) can not be compared.
e.g. code 01 [ both compared variables are string]
from random import randint
result = (randint(1, 6))
guess = input('Guess the number: ')
if guess == str(result):
print('You got it right')
else:
print('Wrong')
print(result)
e.g. code 02 [ both compared variables are integer]
from random import randint
result = (randint(1, 6))
guess = input('Guess the number: ')
if int(guess) == result:
print('You got it right')
else:
print('Wrong')
print(result)

Here you are comparing an int to a string due to return type of input() being string. That will always give False.
Change your input guess to :
guess = int(input())
So,
IN : result = 5
IN : guess = 5
OUT : 'You got it right'

change guess = input('Guess the number: ') to guess=int(input(Guess the number : ')
because input() take a string as a user input.

Related

Why do I get IndexError: string index out of range?

I did google it a lot, and I think I figured out what was causing it, but I don't understand why.
When I would try to run this code:
from random import randint
def getNums():
nums = set()
nums = randint(100, 999)
return str(nums)
def askUser():
try:
guess = int(input("Choose 3 digits to play the game: "))
except:
print("Please enter numbers only.")
return guess
def compare(num, guess):
try:
if guess == num:
print("Guessed!")
print(f"The number was {num}")
elif guess[0] in num or guess[1] in num or guess[2] in num:
print("Match")
elif num != guess:
print("Nope")
except IndexError:
pass
#GET RANDOM DIGITS
num = getNums()
#ASK THE USER TO ENTER THEIR GUESS
#GAME
while True:
guess = askUser()
guess = str(guess)
compare(num, guess)
if num == guess:
break
I would get
---> 23 elif guess[0] in num or guess[1] in num or guess[2] in num:
24 print("Match")
25 elif num != guess:
IndexError: string index out of range
When I would try with 0.
Removing the int(input) and casting the int variables to string seems like it fixed it, but I don't know why there was a problem to start with since they had the same length. Thank you
When you enter a number like '012', and you convert it to an int (12), then the resulting string will be '12'.
As you can see, you no longer have a string of length 3 in this example, but of length 2.
So you get an IndexError when accessing guess[2], since that index does not exist (at least you get the IndexError when you remove the try/except statement).
A simple way around this would be to store the user input in the variable without trying to parse as int, and then just use int() without changing guess.
Something like this:
def askUser():
try:
guess = input("Choose 3 digits to play the game: ")
int(guess)
except:
print("Please enter numbers only.")
return guess
There are other things that can be improved, like only returning guess when there's no error (otherwise you'll get an exception), only catching a ValueError instead of all exceptions, and actually testing if the user input is exactly three characters long.
If I am understanding your code and question, when you cast the int to a string, you are able to parse it as a string hence, why it works. If you pass it as an int, you cannot parse an int by positional reference such as guess[0].
To me, you corrected the issue by casting it to a string that allowed for your parsing.
Also, by using the Python "in" keyword, it will check to see if the value is in the string so, you do not need to parse through the string as "in" will return True or another output if you use an "if" statement.

Problem in a number guessing program's while loop [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 years ago.
I'm new to Yython programming. I create a simple program with random module, that ask for number, and person need to guess an number. I got problem with getting the answer. Even if I give the correct answer, program isn't stopping, here's the code:
import random
run = True
answer = random.randint(1,9)
guess = input("Give me an number in 1 to 9: ")
print(answer)
while run:
if guess == answer:
print("Congratulations, you won!\n" * 5)
run = False
else:
guess = input("Try again: ")
print(answer)
The print(answer) line is for me to know what is the answer, and even if I write it down, program isn't stopping.
answer is always an integer:
answer = random.randint(1,9)
and guess is always a string:
guess = input("Give me an number in 1 to 9: ")
thus they can never be equal.
You need to conver the inputted string to an integer:
guess = int(input("Give me an number in 1 to 9: "))
Or better yet, convert the generated random number to a string, to avoid the issue of the program crashing when the user inputs a non digit:
answer = str(random.randint(1,9))
The random function will return an integer and the input function will return a string in python, "1" is not equal to 1. To be able to check if the input is the same, convert the random number to a string by doing guess == str(answer) instead

IF statement will only consider ELIF? [duplicate]

This question already has answers here:
Numeric comparison with user input always produces "not equal" result
(4 answers)
Closed 4 years ago.
whats up? I'm playing around with my mastermind project for school, only recently started dabbling into Python - and I've ran into a problem I simply cannot figure out? I've looked at other people's questions, who seem to have the same problem as me, but it seems to be more selective, and my code is kind of different. Can anyone tell me why whenever I reply to the question, it immediately skips to "Try again!", even if I know for a fact rnumber == tnumber? (Using Python 3.4.2).
#Generates the random number module
import random
#Creates the variable in which I store my random number
rnumber = random.randint(0,9999)
#Delete this code when complete
print (rnumber)
#Number of tries
numot = 0
#Asks for user input, on what they think the number is
tnumber = input("Guess the four digit number. ")
type(tnumber)
#Compares their number to the random number
if tnumber == rnumber:
print ("You win!")
elif rnumber != tnumber:
print ("Try again!")
numot = numot+1
you need to make your input an int so it considers it a number, try this
#Generates the random number module
import random
#Creates the variable in which I store my random number
rnumber = random.randint(0,9999)
#Delete this code when complete
print (rnumber)
#Number of tries
numot = 0
#Asks for user input, on what they think the number is
tnumber = int(input("Guess the four digit number. "))
#Compares their number to the random number
if tnumber == rnumber:
print ("You win!")
else rnumber != tnumber:
print ("Try again!")
numot = numot+1

Loops not working in Python 3

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.")

How to get out of my while loop [duplicate]

This question already has answers here:
how to stop a for loop
(9 answers)
Closed 6 years ago.
So my issue with my code is that even though I have enter the correctly guessed word, my code still reads it as incorrect; therefore, asks me to try again. How do I get out of this loop? Appreciate it.
import random
count = 1
word = ['orange' , 'apple' , 'chicken' , 'python' , 'zynga'] #original list
randomWord = list(random.choice(word)) #defining randomWord to make sure random
choice jumbled = ""
length = len(randomWord)
for wordLoop in range(length):
randomLetter = random.choice(randomWord)
randomWord.remove(randomLetter)
jumbled = jumbled + randomLetter
print("The jumbled word is:", jumbled)
guess = input("Please enter your guess: ").strip().lower()
while guess != randomWord:
print("Try again.")
guess = input("Please enter your guess: ").strip().lower()
count += 1
if guess == randomWord:
print("You got it!")
print("Number of guesses it took to get the right answer: ", count)
randomWord.remove(randomLetter)
This line removes every letter from your variable.
you can use:
randomWord2 = randomWord.copy()
for wordLoop in range(length):
randomLetter = random.choice(randomWord2)
randomWord2.remove(randomLetter)
jumbled = jumbled + randomLetter
This will copy your variable. If you wont do this your result will be two names for the same variable.
And you compare a list with a string try this instead:
while guess != ''.join(randomWord):
It will convert your list back into a string.

Categories

Resources