How to tell user how many attempts left in Python - python

I am trying to make a random number game in python where the computer has to generate a number between 1 and 20 and you have to guess it. I have limited the amount of guesses to 6. How do I print how many guesses the user has left when they get a guess wrong? Here is my code:
import random
attempts = 0
name = input("What is your name? ")
random = random.randint(1, 20)
print(name + ",","I'm thinking of a number between 1 and 20, What is it?")
while attempts < 6:
number = int(input("Type your guess: "))
attempts = attempts + 1
int(print(attempts,"attemps left")) #This is the code to tell the user how many attempts left
if number < random:
print("Too low. Try something higher")
if number > random:
print("Too high. Try something lower")
if number == random:
break
if number == random:
if attempts <= 3:
print("Well done,",name + "! It took you only",attempts,"attempts")
if attempts >= 4:
print("Well done,",name + "! It took you",attempts,"attempts. Athough, next time try to get three attempts or lower")
if number != random:
print("Sorry. All your attempts have been used up. The number I was thinking of was",random)
Thanks, Any help is greatly appreciated!

print('attempts left: ', 6 - attempts)

Your attempts variable counts the number of attempts used. Since 6 is the limit, 6 - attempts is the number of attempts left:
print(6 - attempts, "attempts left")
(No need to wrap this in an int call. I don't know why you did that.)
Incidentally, writing 6 for the maximum attempts all the time may obscure what the 6 means and make it hard to find all the places that need changing if you want to change the limit to, say, 7. It may be worth making a variable with a descriptive name:
max_attempts = 6
...
while attempts < max_attempts:
...
print(max_attempts - attempts, "attempts left")

print(6 - attempts, "attempts left")

I would make four suggestions, which work towards making your code cleaner and simpler:
Factor out the "magic number" 6 and count down from it, rather than up to it;
Use for rather than while, so you don't have to increment/decrement the number of guesses manually, and use the else to determine if the loop breaks (i.e. out of guesses);
Use if: elif: else: rather than separate ifs; and
Use str.format.
This would make the code something like:
attempts = 6
for attempt in range(attempts, 0, -1):
print("You have {0} attempts left.".format(attempt))
number = int(input(...))
if number < random:
# too low
elif number > random:
# too high
else:
if attempt > (attempts // 2):
# great
else:
# OK
break
else:
# out of guesses

Related

How to make random integer reroll each time

I am a beginner to coding in general and am trying to learn python and so I have been learning how to make a few basic games to figure things out and practice my basics... I have made a game to guess the number that is generate at a random interval of 0-100 and give feedback on if you guessed higher or lower to narrow it into your results. I managed to make the game work and I started trying to add a replayability framework so when you guess correct the game restarts automatically and a new number is generated to guess, however I am not able to make a new number generate. Originally I made the number generate outside the loop and made a loop that seemed effective but the number stayed the same, added it into the loop and it changed with every guess. so I tried adding a secondary def and pointing to it and making the number regenerate there but it doesnt seem to be making a new number still, and if I remove the generation outside of def replay def game no longer sees num as a valid variable. I am unsure how to accomplish this, any advise would be helpful....
import random
num = random.randint(0,100)
def Game():
print("Guess the Number: ")
guess = input()
guess = int(guess)
if guess==num:
print ("CORRECT!!!!!")
Replay()
elif guess>num:
print ("Sorry to high... Try again")
Game()
elif guess<num:
print ("Sorry to low... Try Again")
Game()
def Replay():
num = random.randint(0,100)
Game()
Replay()
This is a example of your code written more correctly according to me:
from random import *
def Game():
replay = 0
while replay == 0:
num = randint(0, 100) # if you want the number to revert every time you make a mistake, leave the line as it is otherwise put this assignment before the loop.
guess = int(input("Choose a integer number from 0 to 100: "))
if guess == num:
print(f"{guess} is mysterious number")
replay = 1
elif guess > num:
print(f"Sorry but {guess} is high, the number was {num}, try again if you want (0=yes, 1=no)")
replay = int(input())
elif guess < num:
print (f"Sorry but {guess} is low, the number was {num}, try again if you want (0=yes, 1=no)")
replay = int(input())
Game()

First timer on StackOverflow---Having trouble with recursion. Trying to have the computer recursively guess the user's number

I'm having a little trouble with this program. I'm a newbie to recursion by the way. Anyway I'm running this and i feel like it should work but it just becomes an infinite loop. Error message is "maximum recursion depth exceeded in comparison". I'm just taking a number, upper and lower limit from the user and having the computer guess it recursively. Any help would be greatly appreciated!
game where computer guesses user's number using recursion
import random as rand
def recursionNum(compGuess, magicNum):
#if the number that the user inputs for the computer to
#guess is to low it multiplies the number by 2 and then subtracts 1
#if the number is to high its divided(//) by 2 and then adds 1
if compGuess == magicNum:
print('You guessed right') #basecase
elif compGuess > magicNum:
print('Guess is', compGuess, '...Lower')
return recursionNum(compGuess //2+1, magicNum)
else:
print('Guess is', compGuess,'....Higher')
return recursionNum(compGuess *2-1, magicNum)
userNum =0
lowerLim = 0
upperLim = 0
while userNum not in range(lowerLim, upperLim):
lowerLim = int(input('What your lower limit: '))
upperLim = int(input('What is yor upper limit: '))
userNum = int(input('pick a number within your set limits:'))
compGuess = rand.randint in range(lowerLim, upperLim)
recursionNum(compGuess, userNum)
First of all, you will never print anything because the print statement is after the return. Return returns control back to the calling scope and so lines following a return statement are ignored. Second, there is no reason to use recursion for this. A simple for loop is much better suited for this. If you are just looking for an application to practice recursion on, may I suggest a Fibonacci number generator? It is a fairly popular example for the topic.

Store numbers and compare based on user input

Currently working to learn Python 3.5 from scratch and thoroughly enjoying the process. latest thing is to write a basic program that does the following..
Asks user to think of a number between 1 and 100
Guesses what it is
Asks user to enter '1' if too low, '3' if too high and '2' if
correct
Provides a new number based on that user input
Limits itself to 10 tries before quitting in shame
Celebrates when it gets it right
Now I THINK I've got it all working minus the higher / lower feature. My question is this.
Note This differs from other questions on the topic because I do not want to enter any numbers for the PC to work on. Also want to generate pseudo-random numbers that are limited to within given values for subsequent guesses from the PC. Not increment.
"How can I implement a feature that looks at the var 'guess' and modifies it to be higher or lower based on user input while keeping it above 0 and below 100".
Code:
import random
print("\tWelcome to the psychic computer")
print("\nI want you to think of a number between 1 and 100.")
print("I will try to guess it in 10 or less tries.\n")
print("\n Press 1 for a lower guess, 3 for a higher one and 2 if I get it right\n")
tries = int(1)
guess = random.randint(1, 100)
print("\nI guess ", + guess, " Is this correct?")
while tries < 10:
feedback = int (input("\nEnter 1 if too high, 3 if too low or 2 if bang on\n\n"))
tries += 1
if feedback == 1:
print("Balls! Guess I need to go Higher will", + guess, + "do?")
elif feedback == 3:
print("\nSh*te! Lower it is then...")
elif feedback == 2:
print("YEEAAAHH BOYEEEE! Told you I was phychic.")
input("\nHit enter to quit")
end
elif feedback != (1,2,3):
print("Not a valid guess. Try again.")
break
if tries >= 9:
print("\nSh*t, guess I'm not so psychic after all")
input("\nHit enter to exit")
You could do something like a binary search. Use a low_number and a high_number to calculate a guess by taking the middle value of the two. These can initially be set 0 and 100. You should also keep track of your last guess. If you last guess was too low, you can set your low_number equal to that guess+1. If your last guess was too high, you can set your high_number to that guess-1.
OK this is what I have so far. It works in that it will respond with (semi) random higher or lower guesses based on user input but does not yet store the original guess as a reference. I will look at that tomorrow. Thanks again for the suggestions.
BTW once working I plan to use math and come up with a solution that always gets it right inside x amount of tries..
import random
print("\tWelcome to the psychic computer")
print("\nI want you to think of a number between 1 and 100.")
print("I will try to guess it in 10 or less tries.\n")
print("\n Press 1 for a higher guess, 3 for a lower one and 2 if I get it right\n")
tries = int()
guess = random.randint(1, 100)
high_number = int(100 - guess)
low_number = int(1 + guess)
print("\nI guess ", + guess, " Is this correct?")
while tries < 10:
feedback = int (input("\nEnter 1 to go higher, 3 to go lower or 2 if bang on\n\n"))
tries += 1
if feedback == 1:
guess = random.randint(high_number, 100)
print("Balls! Guess I need to go Higher how about", + guess)
elif feedback == 3:
guess = random.randint(1, low_number)
print("\nSh*te! Lower it is then... what about", + guess)
elif feedback == 2:
print("YEEAAAHH BOYEEEE! Told you I was phychic.")
input("\nHit enter to quit")
end
elif feedback != (1,2,3):
input("Not a valid guess. Try again.")
break
if tries >= 9:
print("\nSh*t, guess I'm not so psychic after all")
input("\nHit enter to exit")

Incorrect count in output

I made a simple guessing game for practice. The program is functioning without an error but the output given is a wrong value.
Here is the code:
import random
welcome_phrase = "Hi there. What's your name?"
print("{:s}".format(welcome_phrase))
user_name = input("Name: ")
print("Hey {:s}, I am Crash. Let's play a game. I am thinking of a number between 1 and 20. Can you guess the number?".format(user_name))
attempts = 5
secret_num = random.randint(1,20)
for attempt in range (attempts):
guess = int(input("Guess the number: "))
if guess > secret_num:
print("Your guess is higher than the number. Try again")
elif guess < secret_num:
print("Your guess is lower than the number. Try again.")
else:
print("Well done! {:d} is the right number.".format(guess))
print("It took you {:d} attempts.".format(attempt))
break
if guess != secret_num:
print("Sorry, you have used up all your chances.")
print("The number was {:d}".format(secret_num))
And here is the output:
As you can see in the image above, even though it is clear that 3 attempts were made to guess the right number, Python only counted 2 attempts. Will anyone please let me know how to solve this?
You can change
for attempt in range (attempts):
to
for attempt in range (1,attempts+1):
to solve this, as range starts from 0.

Python 'Guess Your Age' Remember Last Integer

I am relatively new to programming with python (actually programming in general). I am making this 'Guess My Age' program that only has one problem:
import random
import time
import sys
print("\tAge Guesser!")
print("\t8 tries only!")
name = input("\nWhat's your name? ")
num = 80
min_num = 6
tries = 1
number = random.randint(min_num, num)
print("\nLet me guess... You are", number, "years old?")
guess = input("'Higher', 'Lower', or was it 'Correct'? ")
guess = guess.lower()
while guess != "correct":
if tries == 8:
print("\n I guess I couldn't guess your age....")
print("Closing...")
time.sleep(5)
sys.exit()
elif guess == "higher":
print("Let me think...")
min_num = number + 1 #### Here is my trouble - Don't know how to limit max number
time.sleep(3) # pause
elif guess == "lower":
print("Let me think...")
num = number - 1
time.sleep(3) # pause
number = random.randint(min_num, num) #<- Picks new random number
print("\nLet me guess... You are", number, "years old?")
guess = input("'Higher', 'Lower', or was it 'Correct'? ")
guess = guess.lower() #<- Lowercases
tries += 1 #<- Ups the tries by one
print("\nPfft. Knew it all along.")
time.sleep(10)
As you can see, I have 'num' as the max number for the random integer getting picked, but with:
elif guess == "higher":
print("Let me think...")
min_num = number + 1
it can go back up to however high it wants.
I want it to remember the last integer that 'num' was.
Say the program guessed 50 and I said 'Lower'. Then it said 30 and I said 'Higher'
I know I am probably sounding confusing, but please bear with me.
You need to define a maximum number as well as a minimum number. If they say their age is lower than a given age, you should set that age minus 1 as the maximum.
Of course, you also need to set an initial maximal age.
You might find it more useful to look into recursive functions for this kind of problem. If you define a function which takes min_age, max_age and tries_left as parameters, which comes up with a random number with between min_age and max_age and queries the user, you can then rerun the function (within itself) with a modified min_age, max_age and tries_left - 1. If tries_left is zero, concede defeat. This way you might get a better understanding of the logical flow.
I have left code out of this answer because, as you are a beginner, you will find it a useful exercise to implement yourself.
Cant you split out your guess into something like
max_num = 0
min_num = 0
elif guess =="lower":
max_num = number
if min_num!=0:
number = min_num+(max_num-min_num)/2
else:
number = max_num-1
elif guess =="higher":
min_num = number
if max_num!=0:
number=min_num+(max_num-min_num)/2
else:
number=min_num+1
Sorry it's not meant to be fully rigorous, and its a slight change on the logic you have there, but splitting out your variables so you have a higher and lower cap, that should help a lot?
Cheers
Please let me know if you need more elaboration, and I can try to write out a fully comprehensive version
It seems as though I was wrong in the fact that it did not remember the older integers. Before when running the program it would guess a number higher than the 'num' had specified. I don't know what I changed between then and now? But thank you for the help! #.#
This seems to work.
The only changes I really made:
-Variable names were confusing me, so I changed a couple.
-Note that if you try to mess with it (lower than 5, higher than 3... "Is it 4?" if you say it's higher or lower, you'll get an error).
The first time you set min and max numbers, you do it outside of the loop, so this script does "remember" the last guess and applies it to the new min, max inside of the loop. Each time it runs, the min will get higher or the max will get lower, based on the feedback from when the user checks the guess. If you had stuck the "min_num=6" and the "num=80" inside of the loop, the guesses would never get better.
import random
import time
import sys
print("\tAge Guesser!")
print("\t8 tries only!")
name = input("\nWhat's your name? ")
max_num = 10
min_num = 1
tries = 1
guess = random.randint(min_num, max_num)
print("\nLet me guess... You are", guess, "years old?")
check = raw_input("'Higher', 'Lower', or was it 'Correct'? ")
check = check.lower()
while check != "correct":
if tries == 8:
print("\n I guess I couldn't guess your age....")
print("Closing...")
time.sleep(5)
sys.exit()
elif check == "higher":
print("Let me think...")
min_num = guess + 1
time.sleep(3) # pause
elif check == "lower":
print("Let me think...")
max_num = guess - 1
time.sleep(3) # pause
guess = random.randint(min_num, max_num) # <- Picks new random number
print("\nLet me guess... You are", guess, "years old?")
check = input("'Higher', 'Lower', or was it 'Correct'? ")
check = check.lower() # <- Lowercases
tries += 1 # <- Ups the tries by one
print("\nPfft. Knew it all along.")
time.sleep(10)

Categories

Resources