Python Guessing Game: Prevent Python guessing the same numbers - python

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

Related

Less-than, greater-than not working when different amount of digits [duplicate]

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

python - Lottery Confirmation Program Questions

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

How to check correct digit positioning?

I made a program that generates a random number between 100 and 999. The user needs to input an integer to guess the random number. The game will only end if the user inputs 0 or has 5 incorrect tries.
How would I modify it such that when the user inputs the answer, the program will tell you whether the integer entered is at the correct position or the correct digit at the wrong position? Like in this example: https://imgur.com/a/CSa3ntd
import random
num = random.randint(100,999)
attempts = 1
while attempts < 6:
guess = int(input("Try #{} - Please enter your guess: ".format(attempts)))
if guess == num:
print("Great! You have gotten the correct number!")
else:
print("Your guess is incorrect")
attempts = attempts + 1
else:
print("The correct number is {}, The game has ended.".format(num))
This code will tell the users which position are correct in case the number and the guess are different.
import random
num = random.randint(100,999)
attempts = 1
print(num)
while attempts < 6:
guess = int(input("Try #{} - Please enter your guess: ".format(attempts)))
if guess == num:
print("Great! You have gotten the correct number!")
break
else:
guess_str = str(guess)
for i, val in enumerate(str(num)):
if guess_str[i] == val:
print("The position num {} is correct".format(i + 1))
print("Your guess is incorrect")
attempts = attempts + 1
else:
print("The correct number is {}, The game has ended.".format(num))
You have two ways of doing this. You may convert your input to a string using str(my_num) and check if str(digit) in str(my_num) and to check if it is in the correct position use str(digit) == str(my_num)[correct_position]
The second way is using divisions and modulu. using (my num // (10 ** position)) % 10 will give you the digit in the position so you could easily compare.
Modify your else statement as :
num = str(num)
guess = str(guess)
correct_digit = 0
correct_digit_position = 0
for i in guess:
if i in num:
correct_digit += 1
if num.index('i') == guess.index('i') :
correct_position += 1
correct_digit -= 1
print(f"Try #{attempts} - {correct_position} correct digit and position, {correct_digit} correct digit but wrong position ")

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

Python program that: Generates a random number between 1 and 100

I have tried everything i can still doesn't work. Please any help would be appreciated.
Please i have been able to allow it generate one hint, but i need it to generate 3 different hints the 3 different times the user presses 0 for the hint.
I have it give the hint even OR odd. i need it to give extra 2 hints.
Part 1:
Generates a random number between 1 and 100.
Allows the user 10 tries to guess what the number is.
Validates the user input (if user-input >100 or user-input<0) then this is invalid input and should not cost the user to lose any tries.
Gives feedback for each time the user makes a guess. The feedback tells the user whether the number entered is bigger, smaller, or equal to the number generated (and exits the program).
Tells the user if they lost after he/she consumes all the 10 tries. Gives the user 10 tries to guess the number. If the user exhausts the 10 ties. The user loses.
Part 2:
After 2 unsuccessful tries, the program should start offering hints for the users (by having the user input the number 0).
Each hint should be generated within a function of its own.
Each hint will cost the user two tries (the program should indicate this to the user)
The user is allowed a max of 3 hints only.
The program should randomly pick which hint it is going to use and display to the user.
(example of a hint is : 1- The number is bigger than or equal the square of some X (X is an integer and is the largest integer square that is less than the user input))
Here is my program so far:
import random
guessesTaken = 0
print('WELCOME! What is your name?')
myName = input()
number = random.randint(1, 100)
print('Hello, ' + myName + ', I generated a number between 1 and 100.')
unsuccessful_tries = 0
hint_taken = 0
while guessesTaken < 10:
if unsuccessful_tries > 1 and hint_taken<3:
print('Press 0 to get hint')
need_hint = int(input())
if need_hint == 0:
hint_taken += 1
guessesTaken += 1
if number%2==0:
print('The Generated number is an EVEN number')
else:
print('The Generated number is an ODD number')
print('Take a guess.\t%d Attempts Left'%(10 - guessesTaken))
#10-guessTaken gives the number of tries left
guess = input()
guess = int(guess)
#validating the user's input
if guess >100 or guess<0:
continue
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
unsuccessful_tries+=1
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
Let me nudge you towards solving part two:
You're already keeping track of the user guesses with the guessesTaken variable
A random 'Hint' can be simply randomly choosing through a list of pre-made hints ( if you had 5 pre-made hints, you could just choose a random number between 1-5, and select that one)
'Costing' the user two tries is as evaluating whether they have enough guesses to afford it ( i.e: if they are at guess number 9, they can't afford to give up 2 guesses), and then add two to the guessNumber if they accept a hint.
You can evaluate the amount of hints taken with a counting variable, though given your parameters (they have to have two unsuccessful guesses to receive a hint, with a maximum of 3 hints total), they would not be able to have 3 hints.
This is the most exact answer i can give you, since you haven't provided any code for part 2 that isn't working or that you need help with.
loose example for point #2: choose a random function from a list:
my_list = [func_test_1, func_test_2, func_test_3]
random.choice(my_list)()
You should create variables which keep tracks of the number of unsuccessful tries and hint taken. If the number of unsuccessful tries is greater than 2 and hint taken is less than 3 then you should ask the user if he wants hint.
import random
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 100)
print('Hello, ' + myName + ', I am thinking of a number between 1 and 100.')
unsuccessful_tries = 0
hint_taken = 0
while guessesTaken < 10:
if unsuccessful_tries > 1 and hint_taken<3:
print('Press 0 to get hint')
need_hint = int(input())
if need_hint == 0:
hint_taken += 1
guessesTaken += 1
print('Here is hint')
#Do this by yourself chose a hint and display
print('Take a guess.\t%d Attempts Left'%(10 - guessesTaken))
#10-guessTaken gives the number of tries left
guess = input()
guess = int(guess)
#validating the user's input
if guess >100 or guess<0:
continue
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
unsuccessful_tries+=1
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)

Categories