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.")
Related
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)
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')
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.
#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.
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"