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 ")
Related
I am making number guesser program and I am trying to figure out how to restart this if you get the number wrong. I have tried while true loops and It just keeps asking the question. I need some help with this thanks (python). EDIT: j1-lee answered question very good!
import random
ask = input("Guess a number between 0 and 10")
r1 = random.randint(0, 1)
print("The number is % s" %(r1))
if int(ask) == r1:
print("right")
else:
print("wrong")
Your while True approach was right. You only need to add break at an appropriate place:
import random
while True:
ask = input("Guess a number between 0 and 10: ")
r1 = random.randint(0, 10)
print(f"The correct number is {r1}.")
if int(ask) == r1:
print("... and you were right!")
break
else:
print("Try again!")
Use a while loop and set a break when user is correct. Also, change you random generator range, you'll only get 0 and 1
if you want the user keep guessing till they find the correct answer, try this:
import random
r1 = random.randint(0, 11)
# print("The number is % s" %(r1))
while True:
ask = input("Guess a number between 0 and 10: ")
if int(ask) < 0 or int(ask) > 10:
print('number you picked is not between 0 and 10')
else:
if int(ask) == r1:
print("correct!")
break
else:
print("try again")
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!!!!!!!!!!!!!!!!")
I'm learning how to program in Python and I found 2 tasks that should be pretty simple, but the second one is very hard for me.
Basically, I need to make a program where computer guesses my number. So I enter a number and then the computer tries to guess it. Everytime it picks a number I need to enter Lower or Higher. I don't know how to do this. Could anyone advise me on how to do it?
For example (number is 5):
computer asks 10?
I write Lower
computer asks 4?
I write Higher
Program:
I already made a program which automatically says Higher or Lower but I want to input Lower or Higher as a user.
from random import randit
number = int(input("Number? "))
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
guess = randint(min,max)
print(guess,"?")
if guess < number:
print("Higher")
min = guess
elif guess > number:
print("Lower")
max = guess
attemps += 1
print("I needed", attempts, "attemps")
You may want to put in a case for if it doesn't match you input, also I think you need a case for when the guess finally equals the number, you may want to allow an input for "Found it!" or something like that.
from random import randint
number = int(input("Number? "))
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
guess = randint(min,max)
print(guess,"?")
answer = str(input("Higher/Lower? "))
if answer == 'Higher':
min = guess
elif answer == 'Lower':
max = guess
attempts += 1
print("I needed", attempts, "attempts")
from random import randit
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
number = int(input("Number? "))
guess = randint(min,max)
print(guess,"?")
if guess < number:
print("Higher")
min = guess
elif guess > number:
print("Lower")
max = guess
attemps += 1
print("I needed", attempts, "attemps")
problem is your using a loop but inputting value once at start of app . just bring input inside the while statement hope this help
from random import randint
print('choos a number in your brain and if guess is true enter y else any key choose time of guess: ')
print("define the range (A,B) :")
A = int(input("A: "))
B = int(input("B: "))
time = int(input("time:"))
while time != 0:
ran = randint(A, B)
inp = input(f"is this {ran} ?")
time -= 1
if inp == "y":
print("bla bla bla computer wins!")
break
print("NOPE!")
if time == 0:
print("computer game over!")
break
from random import *
number = int(input("Number? "))
attempts = 0
guess = 0
min = 0
max = 100
attemps =0
guess = randint(min,max)
while guess != number:
userInput=input(str(guess)+"?")
if userInput.lower()=="lower":
max=guess
elif userInput.lower()=="higher":
min=guess
attemps += 1
guess = randint(min,max)
print("I needed", attemps, "attempts to guess ur number ="+str(guess))
output:
Number? 5
66?lower
63?lower
24?lower
19?lower
18?lower
10?lower
4?higher
9?lower
6?lower
4?higher
I needed 10 attempts to guess ur number =5
I am struggling with some simple algorithm which should make python guess the given number in as few guesses as possible. It seems to be running but it is extremely slow. What am I doing wrong. I have read several topics already concerning this problem, but can't find a solution. I am a beginner programmer, so any tips are welcome.
min = 1
max = 50
number = int(input(("please choose a number between 1 and 50: ")))
total = 0
guessed = 0
while guessed != 1:
guess = int((min+max)/2)
total += 1
if guess == number:
print("The number has been found in ",total," guesses!")
guessed = 1
elif guess > number:
min = guess + 1
elif guess < number:
max = guess - 1
Thanks
ps. I am aware the program does not check for wrong input ;)
Your logic is backwards. You want to lower the max when you guess too high and raise the min when you guess too low. Try this:
if guess == number:
print("The number has been found in ",total," guesses!")
guessed = 1
elif guess > number:
max = guess - 1
elif guess < number:
min = guess + 1
Apart from having the logic backwards, you should not be using min and max as variable names. They are python functions. You can also use while True and break as soon as the number is guessed.
while True:
guess = (mn + mx) // 2
total += 1
if guess == number:
print("The number has been found in {} guesses!".format(total))
break
elif guess < number:
mn = guess
elif guess > number:
mx = guess
You will also see by not adding or subtracting 1 from guess this will find the number in less steps.
from random import randint
print('choose a number in your brain and if guess is true enter y else any key choose time of guess: ')
print("define the range (A,B) :")
A = int(input("A: "))
B = int(input("B: "))
time = int(input("time:"))
while time != 0:
ran = randint(A, B)
inp = input(f"is this {ran} ?")
time -= 1
if inp == "y":
print("bla bla bla python wins!")
break
print("NOPE!")
if time == 0:
print("computer game over!")
break
This game gets the user to guess a 4 digit number and gives feedback straight after the user guesses displaying 'Y' if the user gets the number right and displays 'H' if the guess is at most 3 higher than the number and obviously the opposite of displaying 'L' for at most 3 below the number. but this is my issue, i cant get it to display the 'H' and 'L' at 3 above or below! any help is appreciated.. code is below where i have attempted it.
from random import randint
guessesTaken = 0
randomNumber = [str(randint(1, 9)) for _ in range(4)] # create list of random nums
while guessesTaken < 10:
guesses = list(input("Guess Number: ")) # create list of four digits
check = "".join(["Y" if a==b else "H" if int(a)< 3 int(b) else "L" for a, b in zip(guesses,randomNumber)])
if check == guesses: # if check has four Y's we have a correct guess
print("Congratulations, you are correct, it took you", guessesTaken, "guesses.")
break
else:
guessesTaken += 1 # else increment guess count and ask again
print(check)
if guessesTaken == 10:
print("You lose")
Repaired that, see comments.
from random import randint
guessesTaken = 1 # repaired that. you cannot guess correctly on "0 guesses".
randomNumber = [str(randint(1, 9)) for _ in range(4)]
while guessesTaken < 10:
guesses = list(input("Guess Number: "))
#repaired check cases
check = "".join(["Y" if a == b else "L" if int(a) < int(b) and int(a)+3 >= int(b) else "H" if int(a) > int(b) and int(a)-3 <= int(b) else '?' for a, b in zip(guesses,randomNumber)])
if check == "YYYY": # repaired this check
print("Congratulations, you are correct, it took you", guessesTaken, "guesses.")
break
else:
guessesTaken += 1
print(check)
else: # loop is exhausted
print("You lose")
Guess Number: 4444
?HLH
Guess Number: 2262
?LYL
Guess Number: 7363
LYYY
Guess Number: 8363
LYYY
Guess Number: 9363
Congratulations, you are correct, it took you 5 guesses.
While it works, such a long list comprehension is a PITA to write and maintain.
Better keep your statements short and refactor common things out.