Checking 2 int variables - python

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.

Related

Number guessing game will not print the right phrase

I am extremely new to python and this is one of the first things I have tried. There are 3 criteria that I want this game to meet. First is to use the number 0-10 and guess the number 3 which it does correctly. Next is 0-25 when 11 is chosen. This also works correctly.
However this last part has been giving me trouble. When picking from 0-50, it should guess 1 which it does. It should also print the "I'm out of guesses" line when another input is placed as it cannot go higher than one now. What am I doing wrong here?
import random
import math
smaller = int(input("Enter the smaller number: "))
larger = int(input("Enter the larger number: "))
maxTry = math.log(larger - smaller)
count = 0
guess = int((smaller+larger)/2)
while count != maxTry:
count += 1
guess = int((smaller+larger)/2)
print("Your number is ", guess)
help = input("Enter =, <, or >: ")
if help == ">":
smaller = guess +1
elif help == "<":
larger = guess -1
elif help == "=":
print("Hooray, I've got it in", count, "tries")
break
elif count == maxTry:
print("I'm out of guesses, and you cheated")
break
Your maxTry is a log so it is not an integer, therefore it can never be equal to count.
You can either use an int for maxTry (cast it to int maxTry = int(math.log(larger - smaller))) or compute it with something different than log that will return an int.
Alternatively, your condition could be count > maxTry instead of equal. It would actually be a bit better conceptually.
Note: you should not use capital letters in variable names in python but all lowercase with _ max_try. It is only a convention though so won't affect your program directly. You can find more info on conventions in the PEP8 documentation

Python input control loop

Python beginner here. Practicing user input control.
Trying to make user input loop to the beginning if anything but a whole number between 1 and 10 is used. Been trying for hours, tried using Try and Except commands but couldn't do it correctly. What am i doing wrong? Thank you.
Edit:
Thank you very much for your help everyone, however the problem is still not solved (but very close!) I'm trying to figure out how to loop back to the beginning if anything BUT a whole number is typed. Agent Biscuit (above) gave a great answer for floating numbers, but any word or letter that is typed still produces an error. I´m trying to understand how to loop when anything random (except whole numbers between 1 and 10) is typed. None of the above examples produced corrcct results. Thank you for your help
while True:
print("Enter a number between 1 and 10")
number = int(input())
if (number > 0) and (number < 10):
print("Thank you, the end.")
break
else number != (> 0 and < 10):
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
I have identified some problems.
First, the input statement you are using would just raise an error if a float value is entered, because the int at the start requires all elements of the input to be a number, and . is not a number.
Second; your else statement. else is just left as else:, and takes no arguments or parameters afterwards.
Now, how to check if the number is not whole? Try this:
while True:
print("Enter a number between 1 and 10")
number = float(input())
if (number > 0) and (number < 10) and (round(number)==number):
print("Thank you, the end.")
break
else:
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
This accepts a float value, but only accepts it if it is equal to a whole number, hence the (round(number)==number).
Hope that answers your question.
First of all, you can't use a condition in a else statement. Also, you need to use or operator instead of and if one of the conditions is acceptable.
So, your code needs to be like this
while True:
print("Enter a number between 1 and 10")
number = int(input())
if (number > 0) and (number < 10):
print("Thank you, the end.")
break
elif number < 0 or number >10:
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
Thanks to ack (above) for pointing me to a useful link. By studying another thread, I found the solution. It may not be perfect code, but it works 100%:
while True:
try:
print("Enter a number between 1 and 10")
number = float(input())
if (number > 0) and (number < 10) and (round(number)==number):
print("Thank you, the end.")
break
else:
print("\n")
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
print("\n")
continue
except ValueError:
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
print("\n")

Can anyone figure out this code for me?

import random
print "Welcome to the number guesser program. We will pick a number between 1 and 100 and then ask you to pick a number between 1 and 100. If your number is 10 integers away from the number, you win!"
rand_num = random.randint(1, 100)
user_input = raw_input('Put in your guess:').isdigit()
number = int(user_input)
print number
if abs(rand_num - number) <= 10:
print "Winner"
else:
print "Loser"
Whenever I try to run this code, the computer always generates the number 1. And if I put in a number that is 10 (or less) integers away from one it will still display the else statement. I will have my gratitude to whoever can solve my predicament. I am new to python try to keep your answers simple please.
raw_input returns a string you entered as input. isdigit() checks whether a string is a digit or not and returns True or False.
In your code you're assigning the return value of isdigit to user_input So, you get either True or False. Then you convert it to a number, thus getting either one or zero. This is not what you want.
Let user_input be just a result of raw_input. Then check whether it is a valid number with user_input.isdigit(). If it's not a number, print an error message and exit (or re-ask for input), else convert user_input to an integer and go on.
The problem is product by this sentenc:
user_input = raw_input('Put in your guess:').isdigit().
The return value of isdigit() is True or False. When you enter 1 or any digit number, it will return True(True=1,False=0), so you will always get 1, if you enter digit. You can change like this:
import random
print "Welcome to the number guesser program.
We will pick a number between
1 and 100 and then ask you to pick a number
between 1 and 100. If your number is 10 integers
away from the number, you win!"
rand_num = random.randint(1, 100)
user_input= raw_input('Put in your guess:')
is_digit = user_input.isdigit()
if is_digit==True:
number = int(user_input)
print number
if abs(rand_num - number) &lt= 10:
print "Winner"
else:
print "Loser"
else:
print 'Your input is not a digit.'
Look at this line:
user_input = raw_input('Put in your guess:').isdigit()
The function raw_input gives you user input, but then you call isdigit and as consequence in your variable user_input you get result of isdigit. So, it has boolean value.
Then in
number = int(user_input) you cast it to integer type. In python true is 1 and false is 0. That's why you always get 1.

How to validate an input with a 4-digit number? [duplicate]

This question already has an answer here:
Python Checking 4 digits
(1 answer)
Closed 1 year ago.
I want to write a program that only accepts a 4-digit input from the user.
The problem is that I want the program to accept a number like 0007 but not a number like 7 (because it´s not a 4 digit number).
How can I solve this? This is the code that I´ve wrote so far:
while True:
try:
number = int(input("type in a number with four digits: "))
except ValueError:
print("sorry, i did not understand that! ")
if number > 9999:
print("The number is to big")
elif number < 0:
print("No negative numbers please!")
else:
break
print("Good! The number you wrote was", number)
But if I input 7 to it it will just say Good! The number you wrote was 7
Before casting the user's input into an integer, you can check to see if their input has 4 digits in it by using the len function:
len("1234") # returns 4
However, when using the int function, Python turns "0007" into simple 7. To fix this, you could store their number in a list where each list element is a digit.
If it's just a matter of formatting for print purposes, modify your print statement:
print("Good! The number you wrote was {:04d}", number)
If you actually want to store the leading zeros, treat the number like a string. This is probably not the most elegant solution but it should point you in the right direction:
while True:
try:
number = int(input("Type in a number with four digits: "))
except ValueError:
print("sorry, i did not understand that! ")
if number > 9999:
print("The number is to big")
elif number < 0:
print("No negative numbers please!")
else:
break
# determine number of leading zeros
length = len(str(number))
zeros = 0
if length == 1:
zeros = 3
elif length == 2:
zeros = 2
elif length == 3:
zeros = 1
# add leading zeros to final number
final_number = ""
for i in range(zeros):
final_number += '0'
# add user-provided number to end of string
final_number += str(number)
print("Good! The number you wrote was", final_number)
pin = input("Please enter a 4 digit code!")
if pin.isdigit() and len(pin) == 4:
print("You successfully logged in!")
else:
print("Access denied! Please enter a 4 digit number!")

Python returning untrue values?

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

Categories