I am coding an impossible quiz game, and it doest work. I want the program to exit when the var fails is equal to 3.
Instead, when you enter a wrong answer three times, the program loops rather quitting.
print("Welcome to impossible quiz")
print("")
print("You get 3 fails then you're out")
print("")
startcode = int(input("Enter 0 to continue: "))
fails = 0
if startcode != 0:
exit(1)
print("Welcome")
print("")
print("Level one")
L1ans = input("1+1= ")
while L1ans != "window":
print("incorect")
fails = fails + 1
L1ans = input("1+1= ")
if fails = 3:
exit(1)
if fails == 3:
should do the job
Your logic is a bit convoluted, and you have a syntax error. Try this:
fails = 0 # Set your failure flag
correct = False # Set your correct flag
while not correct: # if not correct loop
answer = input("1+1= ") # get the user's answer here
correct = answer == "window" # check for correctness
if not correct: # Handle incorrect case
print("Incorrect.")
fails += 1
if fails > 3: # quit if we've looped too much. > is better than == for this
exit()
print("Correct!")
Note that this is easily encapsulated in a class that can handle any question:
def ask_question(question, answer, fails) {
correct = False # Set your correct flag
while not correct: # if not correct loop
answer = input(question) # get the user's answer here
correct = answer == answer # check for correctness
if not correct: # Handle incorrect case
print("Incorrect.")
fails += 1
if fails > 3: # quit if we've looped too much. > is better than == for this
exit()
print("Correct!")
return fails
}
fails = 0
fails = ask_question("1+1= ", "window", fails)
fails = ask_question("Red and earth is", "Macintosh", fails)
Welcome to Stackoverflow!
I can only see 1 problem with your code, so your were nearly there!
Your if statement needs to have 2 equal symbols.
if fails == 3:
exit(1)
Related
I was doing beginner python projects as I am a beginner still. I came upon this guessing game project and Wanted to do a Yes or No type of question on whether the user wants to take part in guessing or not.
If user enters Yes, they take part, if anything else ("No" or anything the program exits the code)
However I seem to be doing something wrong, when I enter Yes, the program exits the code anyway. What am I doing wrong? Thank you all,
Here is the code. I am only posting a part of it, where I most probably get the error.
import random
guess = 0
name = input("Hello what is your name?: ")
num = random.randint(1 , 50)
response = input("Well hello there " + name + " I have a number between 1-50, Want to play? You have 10 tries")
if response != "Yes" and response != "yes":
exit()
else:
while guess <= 10:
guess += 1
take = int(input("Guess a number!"))
if take == num:
print("You win! You guessed " + str(guess) + " times")
elif take > num:
print("Too high!")
elif take < num:
print("Thats too low!")
elif take >= guess:
print("You lose... The number was "+ num)
if response != "Yes" or "yes":
equates to this:
if response != "Yes" # which resolves to False when response is a 'no'
OR
"yes" # which is a non-empty string, which Python equates to True.
So basically, you code is equivalent to:
if False OR True:
and thus it always runs the exit() function.
In addition to the items noted above, the if statement should be checking both conditions and thus it should be using and instead of using or, as shown below (HT to #tomerikoo):
What you need is TWO separate tests in the if statement:
if response != "Yes" and response != "yes":
If you believe that you might have other versions of yes answers OR if you think that doing a comparison against a general sequence of terms might be easier to understand, you can also do this test instead:
if response in ['Yes', 'yes', 'y', 'Y', 'YES']:
Debugging:
For folks who are new to programming, in Python, it is sometimes fast and easy to use a simple print() function to rapidly evaluate the current state of a variable, to ensure that it really points at the value you believe it does. I added a print statement below with a comment. It would be beneficial to see what value is associated with response. (Caveat: there are professional tools built into Python and into code editors to help with watching variables and debugging, but this is fast and easy).
import random
guess = 0
name = input("Hello what is your name?: ")
num = random.randint(1 , 50)
response = input("Well hello there " + name + " I have a number between 1-50, Want to play? You have 10 tries")
print(response) # checking to see what was actually returned by the
# input() method
if response != "Yes" and response != "yes":
print(response) # check to see what the value of response is at
# the time of the if statement (i.e. confirm that
# it has not changed unexpectedly).
exit()
else:
while guess <= 10:
guess += 1
take = int(input("Guess a number!"))
if take == num:
print("You win! You guessed " + str(guess) + " times")
elif take > num:
print("Too high!")
elif take < num:
print("Thats too low!")
elif take >= guess:
print("You lose... The number was "+ num)
In python "non-empty random str" is True and empty string "" is False for conditional usages. So,
if "yes":
print("foo")
prints 'foo'
if "":
print("foo")
else:
print("bar")
prints 'bar'
In your case you want program to exit if response is not "Yes" or not "yes". You have two conditions evaluated in if statement:
response == "Yes" --> False
"yes" --> True
if 1 or 2 --> True --> so exit.
so it should be like that:
if response not in ["Yes", "yes"]:
exit()
else:
do_something()
I'm trying to build a guessing game in Python. You have a limited number of around 5 guesses/lives and if you run out of them, you will lose the game. (for reference: it uses both random(for random number) and termcolor(for color) modules)
Program:
from termcolor import colored
import random
def lostit():
print(colored("Sorry! You lost!", "red"))
decideto = input("Try again? (yes/no):")
while decideto not in ("yes", "no"):
decideto = input(colored("Invalid response:", "red"))
if decideto is "yes":
guessnum()
elif decideto is "no":
print("Bye, bye.")
def guessnum():
numtoguess = random.randint(1, 10)
print(colored("I've picked a random number from 0 to 9! Guess what it is! You've got 3 hints and 5 guesses!", "green"))
usernum = input(colored("Try to guess it: ", "cyan"))
guesses = 5 # The limit
usertries = 0 # Chances
if guesses >= usertries:
while usernum != numtoguess:
usernum = input(colored("Wrong! Guess again: ", "red"))
usertries += 1 # Tried to make it add until the limit, but doesn't work
elif guesses == usertries:
lostit()
print(colored("Great job! You guessed it!", "green"))
So far, it works when you type in the right number. However, I've experienced problems with the lives/guesses part. I've tried to set a limit to how many tries the player has, however the program seems to ignore this, meaning the player basically has infinite lives. How do I solve this?
print(colored("Sorry! You lost!", "red"))
decideto = input("Try again? (yes/no):")
should likely be indented.
This is also strange. You don't have a variable called lostit, but you have a loop with that variable:
while lostit not in ("yes", "no"):
The logic on your code is simply wrong. See this loop:
while usernum != numtoguess:
usernum = input(colored("Wrong! Guess again: ", "red"))
usertries += 1 # Tried to make it add until the limit, but doesn't work
You are looping while the guess isn't equal to number you selected.
I would reorg. Main function defines the number to guess, how many guesses they get, it loops while two things are true (guess isn't equal to number and guess count is less than total number of guesses). Also note the scope of variables.
from termcolor import colored
import random
def guessnum():
numtoguess = random.randint(1, 10)
print(colored("I've picked a random number from 0 to 9! Guess what it is! You've got 3 hints and 5 guesses!", "green"))
usernum = input(colored("Try to guess it: ", "cyan"))
guesses = 5 # The limit
usertries = 1 # Chances, but they already used a guess
while (usernum != numtoguess) and (guesses >= usertries):
again = input("Try again? (yes/no):")
while again not in ("yes", "no"):
again = input(colored("Invalid response choose yes/no:", "red"))
if decideto is "yes":
usernum = input(colored("Wrong! Guess again: ", "red"))
usertries += 1
elif decideto is "no":
print("Bye, bye.")
return
if usernum == numtoguess:
print(colored("Great job! You guessed it!", "green"))
if guesses >= usertries:
print(colored("Sorry! You lost!", "red"))
Take a look at this section:
if guesses >= usertries:
while usernum != numtoguess:
usernum = input(colored("Wrong! Guess again: ", "red"))
usertries += 1 # Tried to make it add until the limit, but doesn't work
elif guesses == usertries:
lostit()
First of all, your if and elif are not mutually exclusive: let's say guesses is equal to usertries. It will enter to first if (since you use >=) and not the second elif (because it entered the first one). In other words, Elif code is not reachable.
Seoncd, your while loop is inside the if. It keeps running until you guess the right number, and only then compare your guess with "lives". You should substitute the statements to check the lives inside the loop:
while guesses >= usertries:
usernum = input(colored("Wrong! Guess again: ", "red"))
if usernum != numtoguess:
usertries += 1
# User is wrong. We add one to our counter
else
# user is right. Do something to break the loop
# When we reach here, we ended loop: means user lost
lostit()
The logic is: as long as user has guesses, ask him for another number. compare the number: if he is right, do something. else, keep loop.
I am making a little text based game where you have to guess the number that is between certain criteria which can either be preset by the user or by a random number generator but the problem is when I try to randomly generate the two parameters for the game I get an error 'ValueError: int() base must be >= 2 and <= 36, or 0'
I dont actually know what I should try as I have never encountered this problem before.
import random
Guess = 0
Run = ("Yes")
while Run == ("Yes"):
Number_1 = random.randint(1, 30)
Number_2 = random.randint(int(Number_1, 999999999999))
Answer = random.randint(int(Number_1), int(Number_2))
while int(Guess) != int(Answer):
Guess = (input("\nWhat is your guess? > "))
if int(Guess) < int(Answer):
print("The answer is Greater then that.")
if int(Guess) > int(Answer):
print("The answer is less then that.")
print("Congrates on guessing correctly!!")
Again = (input("\nDo you want to play again? ('y' or 'n') > "))
if Again == ("y"):
Run = ("Yes")
if Again == ("n"):
Run = ("No")
I expect it to generate 2 numbers a lowest possible number and a highest possible and then have the user try to guess that number but it cant seem to properly generate the number.
You've misplaced a closing paren in the statement Number_2 = random.randint(int(Number_1, 999999999999)), so instead of asking for a random int between Number_1 and 999999999999, you're telling the system to parse Number_1 as expressed in base-999999999999.
Im trying to get the print statement to run without it having to run each time the "bones" iteration runs. it should be after the two guesses have been made.
[ ]Complete Foot Bones Quiz
foot_bones = ["calcaneus", "talus", "cuboid", "navicular", "lateral cuneiform",
"intermediate cuneiform", "medial cuneiform"]
def foot_bones_quiz(guess, answer):
total_bones = 0
for bones in answer:
total_bones += bones.count(bones)
if guess.lower() == bones.lower():
return True
else:
pass
return False
**print("Total number of identified bones: ", total_bones)**
guess = 0
while guess < 2:
guess = guess + 1
user_guess = input("Enter a bone: ")
print("Is ", user_guess.lower(), " a foot bone?", foot_bones_quiz(user_guess, foot_bones))
print("Bye, Thanks for your answers.")
foot_bones = ["calcaneus", "talus", "cuboid", "navicular", "lateral cuneiform",
"intermediate cuneiform", "medial cuneiform"]
# Declare total as global variable rather than in the loop, as we are calling this loop twice, and this will not store the count from previous loop iteration
total_bones = 0
def foot_bones_quiz(guess, answer):
global total_bones
for bones in answer:
# First bones is a string, so bones.count(bones) is just giving 1 all the time, so you have to increase the count, only when a bone is actually identified
if guess.lower() == bones.lower():
total_bones += bones.count(bones)
return True
else:
pass
return False
guess = 0
while guess < 2:
guess = guess + 1
user_guess = input("Enter a bone: ")
print("Is ", user_guess.lower(), " a foot bone?", foot_bones_quiz(user_guess, foot_bones))
print("Bye, Thanks for your answers.")
# Now we actually print, how many guesses were correct out of the 2 made
print("Total number of identified bones: ", total_bones)
Tested it on Ubuntu, python 3.6, attaching the screen shots as well.
I am writing a simple Python (shell) program that asks for input. What I am looking for is a certain length (len) of a string. If the string is NOT that minimum, I want to throw an exception and take the user back to the input prompt to try again (for only a given amount of tries, say 3).
my code is basically so far
x=input("some input prompt: ")
if len(x) < 5:
print("error message")
count=count+1 #increase counter
etc...
-- This is where I am stuck, I want the error to be thrown and then go back to my input... kind of new to Python, so help is greatly appreciated. This is going to be part of a script on a Linux box.
Loops work well for this.
You also probably want to use raw_input instead of input. The input function parses and runs the input as python. I'm guessing you are asking users for a password of sorts and not a python command to run.
Also in python there is no i++, use i += 1 for example.
With a while loop:
count = 0
while count < number_of_tries:
x=raw_input("some input prompt: ") # note raw_input
if len(x) < 5:
print("error message")
count += 1 #increase counter ### Note the different incrementor
elif len(x) >= 5:
break
if count >= number_of_tries:
# improper login
else:
# proper login
or with a for loop:
for count in range(number_of_tries):
x=raw_input("some input prompt: ") # note raw_input
if len(x) < 5:
print("error message") # Notice the for loop will
elif len(x) >= 5: # increment your count variable *for* you ;)
break
if count >= number_of_tries-1: # Note the -1, for loops create
# improper login # a number range out of range(n)from 0,n-1
else:
# proper login
You want a while loop instead of your if, so you can keep asking for another input as many times as is appropriate:
x = input("some input prompt: ")
count = 1
while len(x) < 5 and count < 3:
print("error message")
x = input("prompt again: ")
count += 1 # increase counter
# check if we have an invalid value even after asking repeatedly
if len(x) < 5:
print("Final error message")
raise RunTimeError() # or raise ValueError(), or return a sentinel value
# do other stuff with x