Okay so me and my friend are programming a small basic torture game and when I try to run my part of the code, some of the if/elif it will not run as if they were False when they seem True
lives = 5
lives_1 = 13
random_number = random.randint(0,100)
random_number_1 = random.randit(0,1000)
while lives > 0:
print random_number # delete in final product
print "'You have %d chances to save your partner'" % (lives)
guess_0 = int(raw_input("Guess a number from 1 to 100 "))
print "You have guessed %d" % (guess_0)
proceed_2 = raw_input("Press 'Enter' to proceed")
if guess_0 != random_number: # This works
print "It is incorrect, your partner loses a finger"
lives -= 1
continue
elif guess_0 == random_number: # This works
print "It is correct you and your partner get to walk free"
print "GAME OVER"
break
elif guess > random_number: # Doesn't work
print "'LOWER!'"
elif guess < random_number: # Doesn't work
print "'HIGHER!'"
else:
print "GAME OVER"
while lives_1 > 0:
print random_number_1 # delete in final product
print "'You ha-- %d ch---e-'" % (lives_1)
guess_1 = raw_input("What should you do? ")
proceed_1 = raw_input("Press Enter to proceed")
print "You decided to shout {}".format(guess_1)
if guess_1 == random_number_1:
print "The cult has decided to let you go" # doesn't work
break
elif guess_1 != random_number_1: # Works but also works when false
lives_1 -= 1
if lives_1 < 5:
print "Tears begin to blind you as you're nearing death"
continue
elif guess_1 < random_number_1: # doesn't work
print "You squeel in agony as one of your nails were ripped off"
print "'Higher'"
elif guess_1 > random_number_1: #doesn't work
print "You squeel in agony as one of your nails were ripped off"
print "'LOWER...'"
else:
print "GAME OVER"
I want it to print out larger or larger than 3 but as you can see it won't. I have the same problem with the other one.
For the second while function, when I enter a number lower or larger than random_number(_1) it won't print out larger or lower and if I enter the value for random_number(_1) it won't run. I can't see anything wrong please help
The problem here ist that your condition
guess > random_number
is an else if of
guess_0 != random_number
and
guess_0 == random_number
meaning it will only get evaluated if NONE of the former two have evaluated to True. As you can see this cannot be the case. You can instead write it like this:
if guess_0 == random_number:
print "It is correct you and your partner get to walk free"
print "GAME OVER"
break
if guess_0 != random_number:
print "It is incorrect, your partner loses a finger"
lives -= 1
if guess > random_number:
print "'LOWER!'"
elif guess < random_number:
print "'HIGHER!'"
In your second while loop you should edit the line
guess_1=raw_input(....)
to
guess_1=int(raw_input(....))
Perhaps you could try simplifying your conditionals to this?
if guess_0 == random_number:
print "It is correct you and your partner get to walk free"
print "GAME OVER"
break
else:
print "It is incorrect, your partner loses a finger"
lives -= 1
if guess_0 > random_number:
print "'LOWER!'"
else:
print "'HIGHER!'"
This principle should also apply to your second loop that you had asked about.
You may avoid to use the while loop until you are obliged, it may be better with a for loop.
In case of a bug appear on exit loop condition, while loop could end with infinite loop, which may result to a computer freeze or heavy ressource load ...
Related
def random():
x_val = randint(1,100)
limit = []
limit2 = len(limit)
while True:
try:
roll = int(raw_input("Please pick a number: "))
except ValueError:
print "Please input numbers only"
continue
if limit2 <= 5:
if roll > 100 or roll < 1:
print "Exceed Limited Guess"
continue
elif roll < x_val:
limit.append(1)
sleep(1)
print "Your guess is lower!"
continue
elif roll > x_val:
limit.append(1)
sleep(1)
print "Your guess is higher!"
continue
elif roll == x_val:
print limit2
return "You guessed correct! You win!"
break
else:
print "Incorrect Input"
continue
elif limit2 > 5:
return "You guessed over 5 times. You lose, sucker..."
break
elif limit2 == 4:
print "Last guess!"
continue
print "Welcome to my world! You will have to pick a correct number from 1 to 100!
If you can do it within 5 times you win! Otherwise you suck!"
while True:
try:
start = raw_input("Start Rolling? Yes or No: ").lower()
except ValueError:
print "Answer Yes or no"
continue
if start == "y" or start == "yes" or start == "ye":
user2 = random()
print user2
elif start == "n" or start == "no" or start == "noo":
print "Ready when you are"
continue
else:
print "Answer Yes or No"
continue
Hi, I am working on a guessing game from 1-100 that I built from ground up by myself and doing research, my original code is not even close to this.
Now, I am stuck on the last part I cannot use the list to limit the input in while loop. I want to stop the game after 5 guesses. However every time it always keep going and once it win it printed out "0" for limit2 variable.
Thank you
The main problem with your code is that you never update the "counter" of the attempted tries made by the user. You initialize it at the beginning (through limit2 = len(limit)), but you never update that value, therefore causing an endless loop.
You simply need to perform the check on len(limit) instead of on limit2.
Working solution can be found below. I took the liberty of commenting limit2 (as it is not needed anymore), improving the indentation, adding two imports, replacing sleep with time.sleep, and fixing the number of checks to perform (if you are aiming at 5 maximum tries, len(limit) needs to be less than 5).
from random import randint
import time
def random():
x_val = randint(1,100)
limit = []
# limit2 = len(limit)
while True:
try:
roll = int(raw_input("Please pick a number: "))
except ValueError:
print "Please input numbers only"
continue
if len(limit) < 5:
if roll > 100 or roll < 1:
print "Exceed Limited Guess"
continue
elif roll < x_val:
limit.append(1)
time.sleep(1)
print "Your guess is lower!"
continue
elif roll > x_val:
limit.append(1)
time.sleep(1)
print "Your guess is higher!"
continue
elif roll == x_val:
print len(limit)
return "You guessed correct! You win!"
break
else:
print "Incorrect Input"
continue
elif len(limit) >= 5:
return "You guessed over 5 times. You lose, sucker..."
break
print "Welcome to my world! You will have to pick a correct number from 1 to 100! If you can do it within 5 times you win! Otherwise you suck!"
while True:
try:
start = raw_input("Start Rolling? Yes or No: ").lower()
except ValueError:
print "Answer Yes or no"
continue
if start == "y" or start == "yes" or start == "ye":
user2 = random()
print user2
elif start == "n" or start == "no" or start == "noo":
print "Ready when you are"
continue
else:
print "Answer Yes or No"
continue
Worthy of note is that -- among several other things that should be fixed in your code -- you should avoid calling a function random, since it is already a name used by a very common module.
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
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)
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!"
I am trying to make a simple guessing game, but the program exits when the user answers, 'yes', that they know how to play. I don't understand why the 'break' makes the program exit rather than continue to the rest of the code. Extreme newbie, in case you can't tell :P
Thanks for all the help!
import random
import time
def calculat(times):
p = "."
for nums in range(times):
print p
time.sleep(.2)
print p * 2
time.sleep(.2)
print p * 3
time.sleep(.2)
print p * 2
time.sleep(.2)
print p
time.sleep(.6)
print "Welcome to Guess!"
print "Press [Enter] to continue!"
raw_input()
while True:
know = raw_input("Do you know how to play? Enter [yes] or [no]\n")
know = know.upper()
if know == "YES":
break
elif know == "NO":
print " "
print "-INSTRUCTIONS-"
print "Here's how the game works. A number 1 to 100"
print "is generated randomly. Your goal is to guess"
print "as many numbers as possible before you run"
print "out of guesses. You have 10 guesses.Good luck!"
print "Have fun!"
else:
print "Please enter [yes] or [no]!"
while True:
score = 0
number = randint(1,100)
newnum = 1
for tries in range(0,9):
if newnum == 1:
print "Okay, I have a number 1 to 100! What is it?"
else:
print "Guess again! What's the number?"
while True:
try:
guess = input()
if guess <= 100 and guess >= 1:
break
else:
print "You must guess an integer, 1 - 100!"
except:
print "You must guess an integer, 1 - 100!"
if guess == number:
print "Heyo! That's correct!"
score = score + 1
number = randint (1,100)
newnum = 1
if tries != 9:
print "Press [Enter]! Guess another number!"
raw_input()
elif guess < number:
if tries != 9:
print "Darn, that guess was less than the number! Try again!"
print "Press [Enter] to continue!"
raw_input()
elif guess > number:
if tries != 9:
print "Whoa, that guess is too big! Try again!"
print "Press [Enter] to continue!"
raw_input()
print "That's it! Let me calculate your final score! [Press Enter]"
raw_input()
calculate(4)
print "Final Score: " + score
print "Good job!"
raw_input()
print "Would you like to play again? [yes] or [no]?"
play = raw_input()
play = play.upper()
if play == "NO":
print "Okay then, press enter to exit!"
raw_input()
break
elif play == "YES":
print "Yey! Let me think of a new number!"
calculate(2)
else:
print "You couldn't even say yes or no. Get out."
raw_input()
break
Oh yeah, the rest of the code could be broken, too. I haven't gotten past the instructions part.
It ends the program because it immediately encounters an error after the instructions are finished. You've imported random but then tried to use randint, unqualified. You've got to qualify it as random.randint or use from random import randint.
I assume you mean the break statement to escape from the first infinite loop. When I run your code, that break statement works just fine and control proceeds to the second infinite while loop.
However, your program then crashes on the first call to randint() because you aren't importing it correctly. Since the randint() function is from outside of your program (it's in the random module), you need to qualify the calls to randint() as random.randint() - so for the first call, you could use number = random.randint(1, 100). Alternatively, you could import randint using from random import randint, rather than import randint. That way, you would be able to call randint() directly.