Incorrect count in output - python

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.

Related

Trying to create simple guessing game in Python?

I am newer to Python, so please try not to yell at me, haha. I am not sure exactly what I am doing wrong here, and wanted to ask for any pointers or tips. I am trying to create a simple guessing game with Python. It states on line 10 my code has an error, and I am not sure exactly what it is. Sorry I cannot be more specific, I do not know all the basics yet, and I am attempting to figure out how to make programs. Here is my code below.
num = 30
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
while num != guess:
print()
if guess < num:
print("Sorry, but your guess is too low! ")
guess = int(input("Guess the number I am thinking of: "))
elif guess > num:
print("Sorry, but your guess is too high! ")
guess = int(input("Guess the number I am thinking of: "))
else:
print("Wow! You guessed it, good job! ")
if out_of_guesses:
print("Out of guesses, sorry but you lost! ")
Welcome!
Please don't share your code using images. There is an easy way to directly share code as text on stackoverflow. Look here for examples.
As for your question, raw_input was renamed in python 3 to input. See this question.
if guess < num:
Strings and integers cannot be compared using comparison operators. This is because strings and integers are different data types. So in line 2 you should be change
guess = 0 instead of guess = ""
import random
def guess(x):
guess = 1
random_num = random.randint(1,x)
while (guess != random_num) :
guess = int(input(f"Enter number between 1 and {x}: "))
if guess > random_num:
print("Sorry, guess again, Too high number")
elif guess < random_num:
print("Sorry, guess again, Too low number")
elif guess == random_num:
print(f"Congrats,,,, you guessed the number {random_num}" )
guess(20)

Python: why is my print statement not running for my else?

import random
number = random.randint(0,10)
#print (number)
guess = int(input("I'm thinking of a number between 1 and 10. \nPlease guess what it is: "))
#print(guess)
while guess != number:
if guess > number:
print("That is too high!")
guess = int(input())
elif guess < number:
print("That is too low")
guess = int(input())
else:
print("Thats it! You win!")
I'm working out a few python coding examples and I am confused why my else statement isn't printing?
The code objective is to generate a random number, and then have the user input a guess and then depending if the guess is lower or higher than the random number for the computer to notify the user and if the user guess correctly, then to tell the user that they won.
I'm tested this out and when I input the correct number the code just ends and doesn't print out "That's it! You win!". Why is this and how can I get it to print it out?
Guess input prior to the loop will most times be different than the number to guess, therefore the loop will not enter.
You also have other more subtle bugs: for instance, input is taken twice in one loop, creating conditions for improper feedback. Further, your win is confirmed by default, that is if guess not too high, and if guess not too low, then it is a win; a positive assertion such as if guess equals number, is probably safer to declare a win.
Here is a design that segregates each actions in one place in the loop, minimizing the risks of a faulty logic.
import random
number = random.randint(0, 10)
guess = None
while guess != number:
guess = int(input())
if guess > number:
print("That is too high!")
elif guess < number:
print("That is too low")
elif guess == number:
print("Thats it! You win!")
else:
print('that was not supposed to happen')

Guessinggame (replace variable issue)

so doing this for my stage 1 computer science paper. following code is what i've written atm. Line 16 (while statement) is giving a syntax error. The book asks us to
1) prompt the user to enter a guess and store the value in the "guess" variable,
2) if guess is greater than goal print...
3) if guess is lower than goal... print...
4) if guess is same as goal, print...
Unsure how to fix this. Any help will be greatly appreciated. Code as below.
#Author: Anuj Saluja
#Date: 17 October 2016
import random
goal = random.randint(1,100)
guess = 0
print ("The object of this game is to")
print ("guess a number between 1 and 100")
print()
inputguess = int(input("Please guess the number: ")
while (guess != goal):
if inputguess > goal
print ("Too high, try again.")
if inputguess < goal
print ("Too low, try again.")
if inputguess == goal:
break
if inputguess == goal:
print ("Well done!")
print ("See you later.")
The code is only asking for a guess once before the while loop. You need to update the guess variable inside the while loop by asking for input again.
I think you are looking for this. hope this will work.
import random
goal = random.randint(1,100)
guess = 0
print ("The object of this game is to")
print ("guess a number between 1 and 100")
inputguess = int(input("Please guess the number: "))
while True:
if inputguess > goal:
inputguess = int(input("Too high, try again: "))
elif inputguess < goal:
inputguess = int(input("Too low, try again: "))
elif inputguess == goal:
print ("Well done!")
print ("See you later.")
break
Put this line :
inputguess = int(input("Please guess the number: ")
inside the while loop. The code is only asking the user input once, user input must be in the loop.
Have you read your stack trace in detail? It's very easy to just skim over them, but stack traces can actually provide a lot of very useful information. For instance, the message is probably complaining that it was expecting a closing parenthesis. The line:
inputguess = int(input("Please guess the number: ")
should actually be
inputguess = int(input("Please guess the number: "))
The stack trace says the error is on line 16 because that's where the interpreter realized something was wrong. More often than not, the buggy code will be in the last line of code before the line it gives you.
also as other people stated, you need to put the input statement within the while loop in order to update the variable.
You should also consider replacing tab characters with 4 spaces so it displays consistently no matter where you read it. Usually the text editor or IDE will have tab settings that you can change when you hit tab, it will type 4 spaces. A quick Google search along the lines of "{text editor} change tab settings" will usually bring up results on how to change it, where {text editor} is the name of the editor/IDE you're using.
You should also consider indenting the code within your if statements as it improves readability
So I had someone help me irl and this works perfectly for anyone interested. Thanks everyone for help. :) Appreciate it.
goal = random.randint(1,100)
guess = 0
print ("The object of this game is to")
print ("guess a number between 1 and 100")
print()
while guess != goal:
guess = int(input("Please guess the number: "))
if guess > goal:
print ("Too high, try again.")
if guess < goal:
print ("Too low, try again.")
if guess == goal:
break
if guess == goal:
print ("Well done!")
print ("See you later.")

Guess the Number Game with Different Guess Names

This is my first time visiting using stackoverflow--I'm new to programming and am taking a beginner's course for Python. Excited to get started!
Our second assignment asks us to create the well-known Guess the Number Game. For those of you who already know this game, I would love some help on an extra piece that's been added to it: we must list off each guess with their respective order. A sample output should look like this:
I'm thinking of an integer, you have three guesses.
Guess 1: Please enter an integer between 1 and 10: 4
Your guess is too small.
Guess 2: Please enter an integer between 1 and 10: 8
Your guess is too big.
Guess 3: Please enter an integer between 1 and 10: 7
Too bad. The number is: 5
I've got the coding down to where I have Guess 1 and Guess 3 appear, but I cannot make Guess 2 appear. I've been reworking and replacing every "while", "if", "elif", and "else" command to fix this, but can't seem to come up with a solution! Here is my code so far:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
attempts = 0
from random import randint
number = randint(0,10)
guess = eval(input("Guess 1: Please enter an integer between 1 and 10: "))
while guess != number and attempts == 0:
if guess < number:
print("Your guess is too small.")
break
if guess > number:
print("Your guess is too big.")
break
elif guess == number:
print("You got it!")
attempts = attempts + 1
if number != guess and attempts == 1:
guess = eval(input("Guess 2: Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
elif guess > number:
print("Your guess is too big.")
while guess == number:
print("You got it!")
attempts = attempts + 1
elif number != guess and attempts == 2:
guess = eval(input("Guess 3: Please enter an integer between 1 and 10: "))
if guess < number:
print("Too bad. The number is: ", number)
elif guess > number:
print("Too bad. The number is: ", number)
while guess == number:
print("You got it!")
This code outputs Guess 1 and then quits. Can anyone help me figure out how to make Guess 2 and 3 appear?? All ideas are welcome--Thanks!
You can shorten you code quite a bit, just move the input in the loop and keep looping for either three attempts using range or the user guesses correctly:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
from random import randint
number = randint(0,10)
# loop three times to give at most three attempts
for attempt in range(3):
# cast to int, don't use eval
guess = int(input("Guess 1: Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
elif guess > number:
print("Your guess is too big.")
else: # not higher or lower so must be the number
print("You got it!")
break
It would be better to use a while with a try/except to verify the user inputs a number, looping until the user has used 3 attempts or guesses correctly:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
attempts = 0
from random import randint
number = randint(0,10)
while attempts < 3:
try:
guess =int(input("Guess 1: Please enter an integer between 1 and 10: "))
except ValueError:
print("That is not a number")
continue
if guess < number:
print("Your guess is too small.")
attempts += 1
elif guess > number:
print("Your guess is too big.")
attempts += 1
else: # if it is a number and not too high or low it must be correct
print("You got it!")
break # break the loop
You cannot just use an if/else if you actually want to give the user feedback on whether their guess was too low or too high.
Also as commented don't use eval. Some good reason why are outlined here
All your while guess!=number and attempts == loops are useless, because you're either breaking out of them or incrementing attempts so their condition evaluates to False after the first iteration.
Guess 2 is never reached because either number equals guess (so number != guess is False) or attempts is still zero.
Guess 3 is never reached for the same reason. However, if guess 2 would be reached, guess 3 would never be reached because you put elif in front.
Try to get rid of the code for guess 2 and guess 3. Write all the code for guess = eval(input()) and if guess < number: ... elif guess > number: ... once and put it inside a loop. Here's a bit of pseudocode to illustrate the idea:
while attempts < 3
ask for user input
if guess equals number
print "you win"
exit the loop
else
print "that's wrong"
I used the "concatenation" method along with some of your helpful response ideas and finally got my code to work!! Thank you all so, so much for the help!! Here is the correct code for this program:
def guess():
from random import randint
number = randint(0,10)
print("I'm thinking of an integer, you have three guesses.")
attempts = 0
while attempts < 2:
guess = eval(input("Guess " + str(attempts + 1) + ": Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
attempts += 1
elif guess > number:
print("Your guess is too big.")
attempts += 1
else:
print("You got it!")
break
else:
attempts == 3
guess = eval(input("Guess 3: Please enter an integer between 1 and 10: "))
if guess < number:
print("Too bad. The number is: ", number)
elif guess > number:
print("Too bad. The number is: ", number)
else:
print("You got it!")
And then ending it with a call to function ("guess()"). Hope this serves well for those who experience this problem in the future. Again, thank you guys!

Whats wrong with this guess the number game code?

#Guess my number
import random
print ("Welcome to the guess my number game")
print ("***********************************")
print ("You will choose a random number between 1-100")
print ("and the computer must guess what it is.")
print ()
number = int(input("Please choose a number between 1-100: "))
guesses = 0
guess = 0
while guess != number:
guess = ("My guess is: ",random.randint(1,100))
guesses=guesses+1
if guess > number:
print("Lower...")
continue
elif guess < number:
print ("Higher...")
else:
print ("Well done you have guessed my number and it took you") print ("guesses,"guesses!")
Basically you choose a number and the computer has to keep guessing until it gets it right but I can't seem to get it to work.
You should learn basic debugging skills. The simplest way to debug this program would be to add print() statements to see what values are in your variables.
Your basic problem is that you set guess to a tuple with two values: the string "My guess is: " and a random number from 1 to 100. You probably intended to set guess to just the number.
You probably want something like this:
guess = random.randint(1,100)
print("My guess is: {}".format(guess))
This will get you one step closer. Then you will need to figure out how to change the program so that it narrows down the guess range. If you have trouble with that, maybe you should find someone to tutor you a bit.

Categories

Resources