Codecademy Loops 8/19 - python

I haven't programmed in a while so I thought I'd continue with my codecademy tutorial to get back into shape. I'm really confused right now because I'm getting all these syntax errors where I'm pretty sure I shouldn't.
Here's my code:
from random import randint
# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)
guesses_left = 3
# Start your game!
while guesses_left > 0:
guess = int(raw_input("Your guess: ")
if guess == random_number:
print "You win!"
break
guesses_left = guesses_left - 1
else:
print "You lose."
I'm getting a syntax error because of the colon on line 10.
I don't get why, its an if statement, and after an if statement you always have a colon don't you?
I've been getting a bunch of syntax errors today for simple stuff like this and I don't understand why.

Is this a straight copy/paste of your code? Your int() is unclosed
guess = int(raw_input("Your guess: ") <--- missing parenthesis
Also, the decrement of guesses_left is in the wrong place. It should probably be placed after the else block, since it should be decremented every loop, regardless of the result of the if/else
Further, the indentation on your else block doesn't line up with your if. Indentation in python is key.

Slight changes to your code:
from random import randint
# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)
guesses_left = 3
# Start your game!
while guesses_left > 0:
guesses_left = guesses_left - 1
guess = int(raw_input("Your guess: "))
if guess == random_number:
print "You win!"
break
else:
print "You lose."

This code works and gets you through. The main error I got was that it works but still said there was an error after the game was over. This was due to my else: print 'You lose.' being part of the while operation. Instead have the else: function on the same indentation as the while: , and this is what they wanted to see
from random import randint
# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)
guesses_left = 3
while guesses_left > 0:
guess = int(raw_input("Your guess: "))
guesses_left -= 1
if guess == random_number:
print "You win!"
break
else:
print "You lose."

Here is how i did it, I've added some extra features just for fun c:
from random import randint
# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)
print random_number # For debugging
guesses_left = 3 # Amount of guesses left
print "Guess my number! You've got 3 tries left!"
tries = [] # Array for user input
while guesses_left > 0:
guess = int(raw_input("Your guess: ")) # Asks user to enter a number
if guess in tries: # Checks if user entered the same number before
print "You've already guessed this number: ", guess
print "You've got " , int(guesses_left) , " guess(es) left!"
elif guess > 10 or guess < 1: # Checks if user input is between 1 and 10
print "Wrong input! Guess a number between 1 and 10!"
print "You've got " , int(guesses_left) , " guess(es) left!"
elif guess == random_number: # If user input is the same as the random number you win!
print "You win!"
break
else:
guesses_left -= 1 # Decreases the amount of guesses left
print "You've got " , int(guesses_left) , " guess(es) left!"
tries.append(guess) # Saves user input to "tries"
else:
print "You lose!"

Related

creating a python number guessing game

SUPER new to programming so bear with me, please. I am taking my first ever programming class and for a project, I was given a list of requirements I need to fulfill, creating a simple number guessing game has been the only thing I've not had a lot of trouble with so I decided to give it a go.
(i need 1 class, function, dictionary or list, for loop, and while loop) What I, well at least have tried to make is a guessing game that gives a limit of 2 guesss for a # between 0 and 10, any help would be greatly appreciated. :)
import random
class Player:
player = ""
playerscore = 0
def gamestart(self):
self.number = random.randint(0,7)
self.guesss = 0
self.list = []
self.limit = 3
print()
print("Guess what number I'm thinking off")
print()
print("Might even give you a hit if you do well enough")
print()
while self.limit > 0:
self.player_guess = int(input("Well? What are you waiting for? Start guessing:"))
print()
if self.player_guess > 7 or self.player_guess < 0:
print("Wow that was a terrible guess, think harder or we might be here all week long")
print("also,", self.player_guess , "is not in the range...")
print("Becareful though, you only have", self.limit, "guesss left")
elif self.player_guess > self.number:
self.guesss += 1
self.limit-= 1
print("WRONG")
print(self.player, "You only have", self.limit, "guesss left")
self.list.append(self.player_guess)
elif self.player_guess < self.number:
self.guesss += 1
self.limit -= 1
print("oh oh... wrong again!")
print()
print(self.player, "You only have", self.limit, "guesss left.")
self.list.append(self.player_guess)
else:
self.limit -= 1
self.playerscore += 1
self.list.append(self.player_guess)
print()
print("wow, you actually got it right")
print()
print(self.player_guess, "IS THE CORRECT ANSWER!")
print()
print("you only had",self.limit,"left too...")
print("Lets see all the numbers you guessed")
print()
for i in self.list:
print(i)
self.list.clear()
I found the question confusing, however the following code should work as a number guessing game, hope I answered your question.
import random
game = "true"
guesses = 2
while game == "true":
comp_number = int(random.uniform(1,8))
print("I have randomly selected a number between 1 and 7 (inclusive), you have 2 attempts to guess the number.")
while guesses > 0:
if guesses == 2:
turn = "first"
else:
turn = "final"
guess = int(input("Please submit your "+turn+" guess:"))
while guess < 1 or guess > 7:
print("Invalid guess, remember my number is between 1 and 7 (inclusive)")
guess = int(input("Resubmit a valid guess:"))
if guess == comp_number:
print("Congratulations you guessed my number, you win!")
if str(input("Would you like to play again? Please enter Y or N.")) == "Y":
guesses = 2
game = "true"
else:
game = "false"
break
else:
print("Incorrect number, try again.")
guesses -= 1
print("You where unable to guess my number, I win!")
if str(input("Would you like to play again? Please enter Y or N.")) == "Y":
guesses = 2
game = "true"
else:
game = "false"
break

I am trying to do the basic number guessing game on python

I am having trouble writing the code of the basic number guessing game in Python. The objective of the game is to correctly guess a number from 1 to 10 picked at random by the program. I also put some help text that tells the users if they guessed too high or too low. I keep getting a syntax error. This is the code i wrote so far:
print "Welcome to the number guessing game"
print "I have my number..."
import random
while True:
random.randint(1, 10)
number = raw_input("What is your guess[1-10]: ")
if number > random.radint(1, 10):
print "sorry you guessed to high"
elif number < random.radint(1, 10):
print "You guessed to low"
elif number == random.radint(1, 10):
print "You guessed right thanks for playing"
break
else: raw_input("What is your guess[1-10]: ")
It is randint not radint. You are creating a new random number for every test; you should assign a variable to a random number outside of the while loop.
r = random.randint(1, 10)
You must indent if: else: blocks - Python is layout sensitive, e.g.
if number > r:
print "sorry you guessed to high"
You are comparing against a str, need to convert the input to an int().
number = int(raw_input("What is your guess[1-10]: "))
You have an unnecessary else: condition at the end.
So putting it all together:
import random
print "Welcome to the number guessing game"
print "I have my number..."
r = random.randint(1, 10)
while True:
number = int(raw_input("What is your guess[1-10]: "))
if number > r:
print "sorry you guessed to high"
elif number < r:
print "You guessed to low"
else:
print "You guessed right thanks for playing"
break
You could change the while loop to cover the condition:
import random
print "Welcome to the number guessing game"
print "I have my number..."
number = 0
r = random.randint(1, 10)
while number != r:
number = int(raw_input("What is your guess[1-10]: "))
if number > r:
print "sorry you guessed to high"
elif number < r:
print "You guessed to low"
print "You guessed right thanks for playing"

Avoid Nesting If Statements? (Python 2.7)

I got the idea for this guessing game from a book, Invent With Python. I didn't like that the original script didn't cover the possibilities of re-guessing a number or incorrectly using a number not in 1 - 20, so I modified it. The program works great, however, I'm just wrapping my head around if/elif/else code blocks.
I'd like to rewrite the script without having to nest and if inside of an if. I can't even begin to wrap my head around how to do that. Can anyone please help me--just one example of how this program could work without nesting would be great!
Here's the little script in its entirety:
from random import randint
from sys import exit
name = raw_input("Hello! What's your name? ")
print "Well %s, I'm thinking of a number between 1 and 20." % name
print "Since I'm a benevolent computer program, I'll give you 6 guesses."
secret_number = randint(1, 20)
guesses_left = 6
already_guessed = []
while guesses_left > 0:
try:
guess = int(raw_input("Take a guess: "))
if guess >= 1 and guess <= 20 and guess not in already_guessed:
already_guessed.append(guess)
guesses_left -= 1
if guess == secret_number:
print "You win! %d was my secret number!" % secret_number
exit(0)
elif guess < secret_number:
print "Your guess is too low!"
elif guess > secret_number:
print "Your guess is too high!"
elif guess in already_guessed:
print "You already guessed that!"
else:
print "Not a number between 1 - 20!"
print "Please try again!"
print "You have %d guesses left!" % guesses_left
except ValueError:
print "Invalid input! Please try again!"
Try it like this, using continue to exit the current iteration of the loop and start again at the top of the loop.
You also had a logic bug here:
if guess <= 1 and guess >= 20 and guess not in already_guessed:
A number cannot possibly be both less than or equal to 1, and greater than or equal to 20. Your and should have been an or like this:
if (guess <= 1 or guess >= 20) and guess not in already_guessed:
Or simpler:
if 1 <= guess <= 20 and guess not in already_guessed:
Also, keep your try/except only around the things that can actually raise an exception (or shouldn't happen if an exception occurs:
from random import randint
import sys
name = raw_input("Hello! What's your name? ")
print "Well {}, I'm thinking of a number between 1 and 20.".format(name)
print "Since I'm a benevolent computer program, I'll give you 6 guesses."
secret_number = randint(1, 20)
guesses_left = 6
already_guessed = []
while guesses_left > 0:
print "You have {} guesses left!".format(guesses_left)
try:
guess = int(raw_input("Take a guess: "))
except ValueError:
print "Invalid input! Please try again!\n"
continue
# If the number is not between 1 and 20...
if not (1 <= guess <= 20):
print "Not a number between 1 - 20!"
print "Please try again!\n"
continue
if guess in already_guessed:
print "You already guessed that!\n"
continue
guesses_left -= 1
already_guessed.append(guess)
if guess == secret_number:
print "You win! {} was my secret number!".format(secret_number)
sys.exit(0)
elif guess < secret_number:
print "Your guess is too low!\n"
elif guess > secret_number:
print "Your guess is too high!\n"
Here's an example run:
Hello! What's your name? :)
Well :), I'm thinking of a number between 1 and 20.
Since I'm a benevolent computer program, I'll give you 6 guesses.
You have 6 guesses left!
Take a guess: 2
Your guess is too low!
You have 5 guesses left!
Take a guess: 2
You already guessed that!
You have 5 guesses left!
Take a guess: 3
Your guess is too low!
You have 4 guesses left!
Take a guess: 7
Your guess is too high!
You have 3 guesses left!
Take a guess: 5
Your guess is too high!
You have 2 guesses left!
Take a guess: 4
You win! 4 was my secret number!
Just change the nested if statements to elif like so:
from random import randint
from sys import exit
name = raw_input("Hello! What's your name? ")
print "Well %s, I'm thinking of a number between 1 and 20." % name
print "Since I'm a benevolent computer program, I'll give you 6 guesses."
secret_number = randint(1, 20)
guesses_left = 6
already_guessed = []
while guesses_left > 0:
try:
guess = int(raw_input("Take a guess: "))
if guess <= 1 and guess >= 20 and guess not in already_guessed:
already_guessed.append(guess)
guesses_left -= 1
elif guess == secret_number:
print "You win! %d was my secret number!" % secret_number
exit(0)
elif guess < secret_number:
print "Your guess is too low!"
elif guess > secret_number:
print "Your guess is too high!"
elif guess in already_guessed:
print "You already guessed that!"
else:
print "Not a number between 1 - 20!"
print "Please try again!"
print "You have %d guesses left!" % guesses_left
except ValueError:
print "Invalid input! Please try again!"
This would be simplest way i see to solve your dilema

Python guessing game not working

I am making a python code that picks a random number and compares it to a guess made by the user.
import random
attempts=0
secret=random.randint(1,49)
print "welcome to my guessing game"
repeat
def repeat():
guess=raw_input("I have thought of a number between 1 and 50. you have to try and guess it")
if secret==guess:
print "Well Done! you guessed it in "+attempts+" attempts"
elif secret < guess:
print "too high"
guess=raw_input("have another go")
elif secret > guess:
print "too low"
guess=raw_input("have another go")
attempts += 1
while guess != secret and attempts>6:
repeat()
but it is saying that repeat is not defined.
This will allow the user to guess 7 times, then prints game over:
this is for Python 2. for Python 3. use int(input(""))
import random
secret = random.randint(1,49)
attempts = 0
for attempts in range(7):
guess=input("I have thought of a number between 1 and 50. you have to try and guess it: ")
if secret==guess:
print "Well Done! you guessed it "
elif secret < guess:
print "too high"
guess=input(" Enter to have another go")
elif secret > guess:
print "too low"
guess=input("Enter to have another go")
if attempts == 6:
print "Game Over"
The Program is not working because you can not run or call a function before it is created. Also you should call repeat by doing this "repeat()"
I've adapted your code to the following which should work. You might want to read up on Local and Global Variables as that's what was causing your main issue in your code.
import random
def repeat(secret, attempts):
guess=raw_input("I have thought of a number between 1 and 50. you have to try and guess it")
if secret==guess:
print "Well Done! you guessed it in "+attempts+" attempts"
elif secret < guess:
print "too high"
guess=raw_input("have another go")
elif secret > guess:
print "too low"
guess=raw_input("have another go")
attempts += 1
while guess != secret and attempts < 6:
repeat(secret, attempts)
attempts = 0
secret = random.randint(1,49)
print "welcome to my guessing game"
repeat(secret, attempts)

error with elif statement

This is an example in the Python book I'm reading. When I try to run the program there's an error, and when I check the code for the error elif is highlighted in red. I'm programming in Python 2.5.
import random
secret = random.randint(1, 99)
guess = 0
tries = 0
print "It is a number between 1 and 99. I'll give you six tries. "
while guess != secret and tries < 6:
guess = input("What's your guess? ")
if guess < secret:
print "Too low!"
elif guess > secret:
print "Too high"
tries = tries + 1
if guess == secret:
print "Correct! You found my secret!"
else:
print "No more guesses! Better luck next time!"
print "The secret number was", secret
Python is indentation sensitive.
import random
secret = random.randint(1, 99)
guess = 0
tries = 0
print "It is a number between 1 and 99. I'll give you six tries. "
while guess != secret and tries < 6:
guess = input("What's your guess? ")
if guess < secret:
print "Too low!"
elif guess > secret:
print "Too high"
tries = tries + 1
elif guess == secret:
print "Correct! You found my secret!"
else:
print "No more guesses! Better luck next time!"
print "The secret number was", secret
Edit: I know there are still bugs in this, such as tries = tries + 1 which should be somewhere else in the code. But this version at least does not give syntax errors.
The problem lies in your indentation.
Instead of:
if foo:
foobar()
elif bar:
barbaz()
It should be:
if foo:
foobar()
elif bar:
barbaz()
Fixed, your code would then look like this (note, I've also fixed your else at the end to work correctly):
import random
secret = random.randint(1, 99)
guess = 0
tries = 0
print "It is a number between 1 and 99. I'll give you six tries. "
while guess != secret:
if tries < 6:
guess = input("What's your guess? ")
if guess < secret:
print "Too low!"
elif guess > secret:
print "Too high"
tries = tries + 1
elif guess == secret:
print "Correct! You found my secret!"
else:
print "No more guesses! Better luck next time!"
print "The secret number was", secret
break
There are several problems with this code.
The elif and if should have the same indentation level.
You only increment tries in the too-high case.
input() returns a string; you should convert it to an integer.
After testing < and >, the == is redundant.
Since <, > and == cover every case, you'll never reach the else:
Here's a reworking of the logic:
while guess != secret and tries < 6:
guess = int(input("What's your guess? "))
if guess < secret:
print "Too low!"
elif guess > secret:
print "Too high"
tries = tries + 1
if guess == secret:
print "Correct! You found my secret!"
else:
print "No more guesses! Better luck next time!"
print "The secret number was", secret

Categories

Resources