I'm working on a three-digit ticket matching program, and it keeps failing and I don't know what it is.
There is a three-digit lottery ticket.
It's supposed to be this way.
import random
theNumber = random.randint(0, 99)
dumberNumber = int(input("Lottery number?(0- 99사이): "))
digit1 = theNumber // 10
digit2 = theNumber % 10
u_digit1 = dumberNumber // 10
u_digit2 = dumberNumber % 10
print("winning number", theNumber )
if (digit1 == u_digit1 and digit2 == u_digit2):
print("100.")
elif (digit1 == u_digit1 or digit2 == u_digit2):
print("50.")
else:
print("no money.")
This is what I don't know.
If the lottery numbers that the user has match all three digits, he or she will receive 10 million won.
If the lottery number that the user has matches the two digits, he or she will receive 3 million won.
If one of the three digits matches, one million won will be given.
If one does not match, there is no prize money.
Write a program that generates a random number of lottery numbers and prints out how much the prize money is based on user input.
Your code does work assuming you have the indentation correct (make sure the statement after an "if" is indented).
Also note that your random number can currently be only 1 digit (E.G 3), which I don't think is a valid lottery number. To fix this I suggest generating each digit seperately so you can control the number better.
I assume that you are looking for help implementing this with 3 digits instead of 2.
Using str() we can convert numbers to "strings", E.G str(123) = "123"
This is helpful for your case, as a string can have its digits "referenced" by the following
my_string = "123"
my_string[0] = "1"
my_string[1] = "2"
my_string[2] = "3"`
I suggest you try to use this knowledge to help in identifying how many matches you have by converting the numbers to strings, it will be easier to compare digits when both your numbers are strings. Below is an example solution, but I suggest you try to understand it yourself.
import random
#seed randoms to make sure they are random, uses current system time to generate random numbers
random.seed()
#get each lottery number digit seperately
lottery1 = str(random.randint(0, 9))
lottery2 = str(random.randint(0, 9))
lottery3 = str(random.randint(0, 9))
#build a string from the digits, E.G 1, 2 and 3 becomes "123"
lottery_num = lottery1 + lottery2 + lottery3
#note that I'm converting the user input to a str() instead of an int() as you did originally
dumberNumber = str(input("Lottery number?(0- 99사이): "))
#guess1 is the first digit, guess 2 is the second etc.
#note that this is not necessary -- you could just reference the string later in code instead of creating a variable
guess1 = dumberNumber[0]
guess2 = dumberNumber[1]
guess3 = dumberNumber[2]
print("winning number", lottery_num)
digits_correct = 0 #number of digits guessed Correctly
if guess1 == lottery1:
digits_correct = digits_correct + 1 #if our digit matches, we increment by one
if guess2 == lottery2:
digits_correct = digits_correct + 1 #if our digit matches, we increment by one
if guess3 == lottery3:
digits_correct = digits_correct + 1 #if our digit matches, we increment by one
if digits_correct == 0:
print("No numbers guessed correctly :(")
elif digits_correct == 1:
print("1 number correct, $50 reward")
elif digits_correct == 2:
print("2 number correct, $100 reward")
elif digits_correct == 3:
print("3 number correct, $1000 reward")
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 12 months ago.
I'm a python beginner in and got an assignment for school to make the simple number guessing "game" where you have to figure out a number by guessing and it either says higher or lower until you guess the correct number. It worked well until i added two player support and the ability to choose the interval that the random number will be in. Now the higher/lower result from the guess is the opposite if the amount of digits in the guess is different from the random unkown number. Lets say that the random number is 50, then guessing a number between 10-49 will give the result "guess higher", guessing a number between 99-51 will give the result "guess lower" like it's supposed to do. However if the guess is a different amount of digits like 0-9 it will say "guess lower" which is the opposite, same if i guess 100 or anything above it will say "guess higher".
The code:
import random
while True:
select = input("En eller två spelare? ")
if select == '1':
y = input("0 - ")
num = str(random.randint(1, int(y)))
while True:
guess = input('Gissa mellan 0 - ' + y+": ")
if guess == num:
print('Rätt nummer: ' + guess)
break
elif guess == "haks":
print(num)
elif guess < num:
print('Högre än ' + guess)
elif guess > num:
print('Lägre än ' + guess)
if select == '2':
spelare1 = input("Spelare 1: ")
spelare2 = input("Spelare 2: ")
y = input("0 - ")
num = str(random.randint(1, int(y)))
spelare = 0
while True:
if spelare%2 == 0:
print(spelare1 + 's tur')
if spelare%2 == 1:
print(spelare2 +'s tur')
guess = input('Gissa mellan 0 - ' + y+": ")
if guess == num:
print('Rätt nummer: ' + guess)
if spelare%2 == 0:
print(spelare1, "vann!")
break
if spelare%2 == 1:
print(spelare2, "vann!")
break
elif guess == "haks":
print(num)
elif guess < num:
print('Högre än ' + guess)
spelare = spelare+1
elif guess > num:
print('Lägre än ' + guess)
spelare = spelare+1
I can't find any logic in this and already spent to much time on trying to fix it. Any help is much appreciated and if there are any questions about the code I'll happily answer them.
The number of digits doesn't matter
There's a difference between inequality comparisons on strings (like you're doing) and on actual numbers.
When used on strings, it's comparing alphabetically, not numerically
You should convert all inputs to numbers, not compare them as strings (the default return type of input function). Similarly, don't cast your random digits to strings
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
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.
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!")
I am working on a guessing game in python, i think i have everything only, i want to make the program to guess between numbers it already guessed for example, if the users number is 5, and it picks 3 the user input '+' and it knows the number is higher, and if the program guess 6 the user input '-' and it knows the number is lower than 6, but sometimes it guesses a 2, its obvious that if the number is higher than 3 it can't possibly be 2 right, so how do i write that? I am a beginner at this and i would appreciate if you could make it simple, below is my code.
print("Hello,")
print("welcome to the guessing game")
print('I shall guess a number between 1 and 99, and then ask you if am right')
print('I have a maximum of 20 chances\n')
import random
guess = random.randint(1,99)
print("Your number is %f, Am i right?" % guess)
print('If I am, enter =, If the number is higher enter (+), if the number is lower enter (-)')
ans = input('Which is it: ')
print("You chose %s" % ans)
minguess = 1
maxguess = 99
count = 0
while (count < 20):
count = count + 1
if ans == '+':
##I am using these prints to keep track of the numbers and if everything is working correctly
maxguess1 = guess + 1
print('THe maxguess is', maxguess1)
newguess = random.randint(maxguess1, maxguess)
print('The newguess is', newguess)
newguess = int(newguess)
print("Is it %d?" % newguess)
print('If I am, enter =, If the number is higher enter (+), if the number is lower enter (-)')
ans = input('Which is it: ')
elif ans == "-":
maxguess2 = guess - 1
print('The minus maxguess is', maxguess2)
newguess = random.randint(minguess, maxguess2)
print('The minus newguess is', newguess)
newguess1 = int(newguess)
print("Is it %d?" % newguess1)
print('If I am, enter =, If the number is higher enter (+), if the number is lower enter (-)')
ans = input('Which is it: ')
if ans == "=":
print('YAAAAAAS MAN')
i wanted it to change the numbers whenever it guessed a new number
guess = newguess
NOTE: This example is in Python 2.7, NOT Python 3, but the concepts are the same.
Break down the problem into its individual elements:
import random
# Possible Range is [1-99], 1 inclusive to 99 inclusive
min_possible = 1
max_possible = 99
# Number of Guesses
max_guesses = 20
# Process
for i in xrange(max_guesses): # Loops through the process 'max_guesses' times
# Program Takes a Guess
guess = random.randint(min_possible, max_possible)
print 'My guess is ' + str(guess)
# Ask for User Feedback
user_feedback = ''
while not user_feedback in ['+', '-', '=']:
user_feedback = raw_input('Is the number higher (+), lower (-), or equal (=) to my guess?')
# Use the User Feedback
if user_feedback == '+':
min_possible = guess + 1 # B/c low end is inclusive
elif user_feedback == '-':
max_possible = guess - 1 # B/c high end is inclusive
else:
print 'I knew the answer was ' + str(guess)
break