Guessing game in python - 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"

Related

Determinate loop and Indeterminate Loops in Python

I need to show "Determinate loop" and "Indeterminate Loops" on this code. (nested)
This is a simple code, pick a random number, and gives you 2 opportunities to guess the number, if you can't, it will let you know what the magic number was and start the game again.
questions:
is there any other way to make the game start over? like a while or nested loop.
can I get an opinion if it is enough?
the problem with the code is, every time you make a guess, it prints
"Can you guess the magic number?"
how can it print that only at the beginning of the code and then only prints:
"try a lower number"
"try a higher number"
I feel like the code is not nested enough, anyway I can make it more professional?
repeat_the_game = True
def start():
import random
magic_number = random.randint(1, 10)
trying = 0
limit = 2
while trying < limit:
guess = int(input("can you guess the magic number?"))
trying += 1
if guess > magic_number:
print("try a lower number")
elif guess < magic_number:
print("try a higher number")
elif guess == magic_number:
print("wow, you are right")
break
else:
print("sorry, the magic number was", magic_number)
while repeat_the_game:
start()
Move the text out of the loop to a print statement. Then you can still keep fetching the input inside the loop:
repeat_the_game = True
def start():
import random
magic_number = random.randint(1, 10)
trying = 0
limit = 2
print("can you guess the magic number?")
while trying < limit:
trying += 1
guess = int(input())
if guess > magic_number:
print("try a lower number")
elif guess < magic_number:
print("try a higher number")
elif guess == magic_number:
print("wow, you are right")
break
else:
print("sorry, the magic number was", magic_number)
while repeat_the_game:
start()
However, if the second guess is still wrong you probably don't want to print "try a lower/higher number". If you guess it right the second time you do want to print "wow, you're right". I'd put the "try a lower/higher number" after an additional check of whether all tries have been used up already. You can move the "wow, you're right" part before that check:
while trying < limit:
guess = int(input())
trying += 1
if guess == magic_number:
print("wow, you are right")
break
if trying == limit:
continue
if guess > magic_number:
print("try a lower number")
elif guess < magic_number:
print("try a higher number")
else:
print("sorry, the magic number was", magic_number)

What can I do to fix my simple computer-player game code? Syntax Error

I'm new to Python and I wanted to practice doing loops because I’ve been having the most trouble with them. I decided to make a game where the user will pick a number from 0-100 to see if they can win against the computer.
What I have going right now is only the beginning. The code isn’t finished. But trying out the code I got a Syntax error where the arrow pointed at the colon on the elif function.
How do I fix this? What can I do?
I accept any other additional comments on my code to make it better.
Here’s my code:
import random
min = 0
max = 100
roll_again = "yes"
quit = "no"
players_choice = input()
computer = random.randint
while roll_again == "yes":
print("Pick a number between 1-100: ")
print(players_choice)
if players_choice >= 0:
print("Your number of choice was: ")
print(players_choice)
print("Your number is high.")
if computer >= 0:
print("Computers number is: ")
print(computer)
print("Computers number is high.")
if computer >= players_choice:
print("Computer wins.")
print("You lose.")
print("Would you like to play again? ", +roll_again)
elif:
print(quit)
end
Goal:
Fix computer-player game while learning more about python. Providing additional documentation on where to start would be helpful.
The reason you are getting an error pointing to elif is because elif needs a condition to check. You need to use if elif and else like this:
if a == b:
print('A equals B!')
elif a == c:
print('A equals C!')
else:
print('A equals nothing...')
Also, Python relies on indentation to determine what belongs to what, so make sure you are paying attention to your indents (there is no end).
Your code has more errors after you fix the if statements and indentation, but you should be able to look up help to fix those.
There are a lot of problems with your code. Here is a working version, hope it helps you understand some of the concepts.
If not, feel free to ask
import random
# min and max are names for functions in python. It is better to avoid using
# them for variables
min_value = 0
max_value = 100
# This will loop forever uless something 'breaks' the loop
while True:
# input will print the question, wait for an anwer and put it in the
# 'player' variable (as a string, not a number)
player = input("Pick a number between 1-100: ")
# convert input to a number so we can compare it to the computer's value
player = int(player)
# randint is a function (it needs parentheses to work)
computer = random.randint(min_value, max_value)
# print what player and computer chose
print("Your choice: ", player)
print("Computer's choice: ", computer)
# display the results
if computer >= player:
print("Computer wins. You loose")
else:
print("you win.")
# Determine if user wants to continue playing
choice = raw_input("Would you like to play again? (yes/No) ")
if choice != 'yes':
# if not
break
There are a lot of indentiation issues and the if and elif statements are used incorrectly. Also take a look at how while loops work.
Based on the code you provided here is a working solution, but there are many other ways to implement this.
Here is some helpful tutorials for you on if/else statements as well as other beginner topics:
Python IF...ELIF...ELSE Statements
import random
minval = 0
maxval = 100
roll_again = "yes"
quit_string = "no"
while True:
players_choice = int(input("Pick a number between 1-100:\n"))
computer = random.randint(minval,maxval)
#checks if players choice is between 0 and 100
if players_choice >= 0 and players_choice <= 100:
print("Your number of choice was: ")
print(players_choice)
#otherwise it is out of range
else:
print("Number out of range")
#check if computers random number is in range from 0 to 100
if computer >= 0 and computer <= 100:
print("Computers number is: ")
print(computer)
# if computer's number is greater than players number, computer wins
if computer > players_choice:
print("Computer wins.")
print("You lose.")
#otherwise if players number is higher than computers, you win
elif computer < players_choice:
print("You won.")
#if neither condition is true, it is a tie game
else:
print("Tied game")
#ask user if they want to continue
play_choice = input("Would you like to play again? Type yes or no\n")
#checks text for yes or no use lower method to make sure if they type uppercase it matches string from roll_again or quit_string
if play_choice.lower() == roll_again:
#restarts loop
continue
elif play_choice.lower() == quit_string:
#breaks out of loop-game over
break

Show me the way to calling my function

So I'm learning to code and I started with Python.
I've learned the very basics of programming in python, like what are variables, operators, some functions etc.
I have this code:
def guessGame():
import random
guesses = 0
randomNo = random.randint(0, 100)
print "I think of a number between 0 and 100, you have 10 guesses to get it right!"
while guesses < 10:
guess = input("Take a guess ")
guess = int(guess)
guesses += 1
if guess < randomNo:
print "The number is higher than your guess"
if guess > randomNo:
print "The number is lower than your guess"
if guess == randomNo:
break
if guess == randomNo:
guesses = str(guesses)
print "You got it in %s guesses!" % guesses
if guess != randomNo:
print "You failed to guess!"
guessGame()
when I run the code in cmd it just ends before the function gets "recalled".
cmd output
You called the game only once in your main program -- which consists of the last line only. It runs the game once and quits. There is no second call in your code. Perhaps you want a classic "play again?" loop:
play = True
while play:
guessGame()
play = lower(raw_input("Play again?")[0]) == 'y'
after each game, you ask the player for input. If that input begins with the letter 'y' (upper or lower case), then you continue playing; otherwise, play becomes False and you drop out of the loop.
Is that what you wanted?

Error with my game?

from random import randint
random_number = randint(1, 10)
guesses_left = 3
# Start of the game
while guesses_left != 0:
def guess():
guess = int(input("What is your guess?"))
if guess > 10:
print ("Insert value between 1 and 10")
guesses_left += 1
guess()
if guess == random_number:
print ("You win")
break
guesses_left -= 1
else:
print ("You lose")
I am making this game where random numbers are formed and the user guesses the random number to win the game. However, I want to implement a safety that if the guess goes over 10, then it will print "enter value from 1 to 10" (see the code) and also add 1 to the guess left. I made this into a function so that the print message keeps displaying itself until the user puts all his guesses from 1 to 10. I am getting an error in that function itself :(
Also, how can I keep displaying the print message without functions? I know how to do it with while loop but is there a better way to do it?
You don't need the function at all, since you don't call it more than once.
A good way to think about the problem is that the program starts with a state of not knowing what the players guess is. You can represent this as 0. Then the while loop checks to see if the guess is >=1 AND <=20. Since the first time around, it's not, the loop would ask for a guess between 1 and 10.
Several notes here:
1) Remove the definition of the guess function outside of the while loop.
2) Watch the indentation. It's meaningful in Python
3) I merged the guess function with the main code, and it's still pretty readable
4) You can avoid having to increment guesses_left by 1 if you don't decrement it
5) I really hope you're trying to learn programming, and not having us complete your homework for you. Python can be very powerful, please continue to learn about it.
from random import randint
random_number = randint(1, 10)
guesses_left = 3
# Start of the game
win=False
while guesses_left>0:
guess=int(input("What is your guess?"))
if guess==random_number:
win=True
break
elif guess>10:
print("Insert value between 1 and 10")
continue
else:
guesses_left -= 1
if win:
print("You win")
else:
print("You lose")
from random import randint
random_number = 10 # randint(1, 10)
guesses_left = 3
# Start of the game
while guesses_left != 0:
guess = int(input("Guess a number between 1 and 10: "))
if guess > 10:
print "(error: insert a value between 1 and 10)"
guesses_left = guesses_left - 1 #add if you want to dock them a guess for not following instructions :)
else:
if guess is random_number:
print ("You win!")
break
else:
print "Nope!"
guesses_left = guesses_left - 1
if guesses_left is 0:
print "Wah Wah. You lose."
My code is probably more verbose than it needs to be but it does the trick. There are a couple problems with the way you wrote the script.
Like Hack Saw said, I don't think you need the function.
Indentation is off. This matters a lot to python
Good luck in class! :)

Loop until entry matches a predetermined value

I want to have a user try a guessing game. The program should loop until the user guesses right.
How can I compare the values? Right now its going through the else part every time, even when the user guesses right.
Here is the code;
import sys
from random import randint
secret_number = randint(0, 100)
num_guesses = 0
guess = 0
while guess != secret_number:
guess = raw_input("Enter a number: ")
if (guess < secret_number):
print "Your guess is too low. Please try again."
else:
print "Your guess is too high. Please try again."
num_guesses = num_guesses + 1
print "Thank you, you guessed right"
print guess
You need to convert the string that raw_input returns into an integer using int, so the comparison operator works the way you expect it to:
guess = int(raw_input("Enter a number: "))
raw_input will return string, you compare string with int and nothing works
also you will never guess the number:
your code hav 2 options: too low or too high
also you never compare tries with max tries (try to fix that by yourself)
corrected version:
import sys
from random import randint
secret_number = randint(0, 100)
num_guesses = 0
guess = 0
while guess != secret_number:
guess = raw_input("Enter a number: ")
if (int(guess) < secret_number):
print "Your guess is too low. Please try again."
elif (int(guess) > secret_number) :
print "Your guess is too high. Please try again."
else:
print "Thank you, you guessed right"
break
num_guesses = num_guesses + 1
print guess

Categories

Resources