Whats wrong with this guess the number game code? - python

#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.

Related

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

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.

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

Guessing game in python

I have only just started to learn to program following http://learnpythonthehardway.org.
After learning about loops and if-statements I wanted to try to make a simple guessing game.
The problem is:
If you make an incorrect guess it gets stuck and just keeps repeating either "TOO HIGH" or "TOO LOW" until you hit crtl C.
I have read about while loops and have read other peoples code but I simply dont want to just copy the code.
print ''' This is the guessing game!
A random number will be selected from 1 to 10.
It is your objective to guess the number!'''
import random
random_number = random.randrange(1, 10)
guess = input("What could it be? > ")
correct = False
while not correct:
if guess == random_number:
print "CONGRATS YOU GOT IT"
correct = True
elif guess > random_number:
print "TOO HIGH"
elif guess < random_number:
print "TOO LOW"
else:
print "Try something else"
You have to ask the user again.
Add this line at the end (indented by four spaces to keep it within the while block):
guess = input("What could it be? > ")
This is just a quick hack. I would otherwise follow the improvement proposed by #furins.
Moving the request inside the while loop does the trick :)
print ''' This is the guessing game!
A random number will be selected from 1 to 10.
It is your objective to guess the number!'''
import random
random_number = random.randrange(1, 10)
correct = False
while not correct:
guess = input("What could it be? > ") # ask as long as answer is not correct
if guess == random_number:
print "CONGRATS YOU GOT IT"
correct = True
elif guess > random_number:
print "TO HIGH"
elif guess < random_number:
print "TO LOW"
else:
print "Try something else"

Categories

Resources