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.
Related
I’m trying to get my game to tell the player how many chances they have left after every other turn. So for example, after the first try say “WARNING: you have x amount of tries left” and then “LAST CHANCE” when the final try comes.
I’m not sure if it’s possible to loop within a loop in the way that I’m trying to do it.
num = 2
guess = ''
guess_count = 0
guess_limit = 3
out_of_guesses = False
#make a loop to tell the player how many chances they have left
while guess != num and not(out_of_guesses):
print("WARNING: You only get THREE chances")
if guess_count < guess_limit :
guess = int(input('Guess a number between 1 and 10: '))
guess_count += 1
else:
out_of_guesses = True
if out_of_guesses:
print('Out of guesses. LOSER!')
else:
print('BINGO! The times the CHARM! WINNER!')
Thanks so much.
enter image description here
So I want the warning to change after every other turn unless the player guesses the correct number.
I hope this makes sense.
If you want the program to print how many guesses are left in the warning, you could do something like this:
print(f"WARNING: You have {guess_limit-guess_count} guesses left")
This uses a feature called 'f strings' which allows you to put the value of a variable inside a string. Here I'm using it to put the result of guess_limit - guess_count inside the string, which should resolve to the number of guesses remaining.
num = 2
guess = ''
guess_count = 3
guess_limit = 0
out_of_guesses = False
#make a loop to tell the player how many chances they have left
while guess != num and not(out_of_guesses):
if guess_count > guess_limit and guess_count!=1:
print("WARNING: You only get {} chances".format(guess_count))
guess = int(input('Guess a number between 1 and 10: '))
guess_count -= 1
elif guess_count==1:
print('LAST CHANCE:') # different method for last chance
guess = int(input('Guess a number between 1 and 10: '))
guess_count -= 1
else:
out_of_guesses = True
if out_of_guesses:
print('Out of guesses. LOSER!')
else:
print('BINGO! The times the CHARM! WINNER!')
#output
WARNING: You only get 3 chances
Guess a number between 1 and 10: 4
WARNING: You only get 2 chances
Guess a number between 1 and 10: 8
LAST CHANCE:
Guess a number between 1 and 10: 6
Out of guesses. LOSER!
Document str.format()
https://python-reference.readthedocs.io/en/latest/docs/str/format.html
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 ")
My son has this project he has to do in python and is stuck.
He needs to make a number guessing game. The code must generate a random secret number between 0 and 10, then give the user 5 attempts to guess that number, each guess if not correct must indicate if it is higher or lower than the secret random number. After each guess the code needs to display text stating what has happened. The code also needs to store all guesses and display them at the end. Needs to be made using loop, if, elif, else and an array or list code.
The attempt so far is below
print("Hi there, lets play a little guessing game. Guess the number between 0 and 10")
from random import randint
x = [randint(0,10)]
counter = 0
guess = input("Enter guess:")
while counter < 5:
print("You have " + str(counter) + " guesses left")
counter = counter +1
if guess == x:
print("Congrats you got it")
break
elif guess > x:
print("Too high")
elif guess < x:
print("Too low")
else:
print("You lost")
break
Any help to correct my sons code would be appreciated as this project is due soon and he cannot access his tutor
This should do it. What the code does is explained in comments below.
You need to do x=randint(0,10) which will assign the random number to a variable, i.e x=4 rather than `x = [randint(0,10)], which assigns the random number to a list ,x=[4]```
Also you need to ask for a guess in the loop, instead of doing it only one before the loop started.
Also you would need to convert the string to an int for comparison i.e. guess = int(input("Enter guess:"))
print("Hi there, lets play a little guessing game. Guess the number between 0 and 10")
#Create a random number
from random import randint
x = randint(0, 10)
counter = 0
won = False
#Run 5 attempts in a loop
while counter<5:
#Get the guess from the user
guess = int(input("Enter guess:"))
counter = counter+1
#Check if the guess is the same, low or high as the random number
if guess == x:
print("Congrats you got it")
won = True
break
elif guess > x:
print("Too high")
elif guess < x:
print("Too low")
print("You have " + str(5 - counter) + " guesses left")
#If you didn't won, you lost
if not won:
print("The number was ", x)
print("You Lost")
So here are the corrections. So x has been initialized as array rather than an integer. So none of the comparisons with guess will be working. Also the counter logic is wrong. Rather than starting from zero, start from 5 which is the maximum number of chances and go from the reverse rather. Then at each if/elif loop append all the guesses and print it in the end.
Here is the corrected code
from random import randint
x = randint(0,10)
print(x)
counter = 5
guesses=[] #initalize an empty list to store all guesses
while counter != 0:
guess = input("Enter guess:")
if guess == x:
print("Congrats you got it")
guesses.append(guess)
break
elif guess > x:
print("Too high")
guesses.append(guess)
elif guess < x:
print("Too low")
guesses.append(guess)
else:
print("You lost")
break
counter = counter-1
print("You have " + str(counter) + " guesses left")
print(guesses)
Edit:
x = [randint(0,10)] wouldn't work as you are creating a list here instead of single guess
print("You have " + str(counter) + " guesses left") is also incorrect. You might instead set counter to 5 and check for counter > 0 and do counter -= 1, that way message can be fixed
Lastly to store all guesses you would need a variable
from random import randint
if __name__ == "__main__":
number_to_guess = randint(0,10)
guesses = []
for c in range(5,0,-1):
guessed = input("Enter guess:")
guessed = guessed.strip()
assert guessed.isnumeric()
guessed = int(guessed)
guesses.append(guessed)
if guessed == number_to_guess:
print("yes")
break
elif guessed > number_to_guess:
print("more")
else:
print("less")
c -= 1
print("pending guesses", c)
print("Expected - ", number_to_guess)
print("All guesses - ", guesses)
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!!!!!!!!!!!!!!!!")
How do I make the loop work so that it will end when you get it right and ask the question again if you get it wrong?
When i guess wrong two or more times it will always say wrong no matter what.
import random;
import sys;
x = random.randint(1, 100);
print(x);
guess = int(input("Guess a number 1 to 100"));
if guess == x:
print("correct");
sys.exit()
while guess != x:
print("wrong");
int(input("Guess a number 1 to 100"));
print(x);
if guess == x:
print("Correct");
sys.exit()
Also what function records the number of times it loops. For example if I guess wrong 10 times then I want to print that I scored a 10.
You have forgotten to assign the second time around to the guess variable
while guess != x:
print("wrong");
guess = int(input("Guess a number 1 to 100")); #look here
print(x);
if guess == x:
print("Correct");
sys.exit()
Missing 'guess=' in the input line in the loop. To record number of times, just increment a variable in the loop.
[ADDENDUM]
import random;
import sys;
x = random.randint(1, 100);
print(x);
count = 1
guess = int(input("Guess a number 1 to 100: "));
while guess != x:
count += 1
guess = int(input("Wrong\nGuess a number 1 to 100: "));
print("Correct - score = "+str(100./count)+"%");
sys.exit(0)
Actually you should change your codes to:
import random
x=random.randint(1,100)
score=0
while True:
guess=int(input("Guess a number 1 to 100: "))
if guess==x:
print ("Correct!")
break
else:
print ("Not correct!")
score+=1
print ("your answers was wrong {} times.".format(score))
Better statements,less codes. Cheers!