Why is my if true/elif/else-code not working? - python

In python, I am trying to make this code accept the user to move forward if he writes "True", and not if he writes "False" for the statement in User_Answer. When I run the code however, I get the "the answer is correct!"-part no matter what I write. The part I am having trouble with starts with "Test_Answer".
Could anyone help me with this?
name_list = ["Dean", "Bill", "John"]
enter_club = ["Enter", "enter"]
print ("THE CLUB - by Mads")
print (" ")
print ("""You approach a secret club called \"The club\". The club members are dangerous.
Make sure you tell the guard one of the members names.""")
print ("")
print ("Good evening. Before you are allowed to enter, we need to check if your name is on our list.")
def enter_the_club():
enter_now = input(" \nPress \"enter\" to enter the club... ")
if (enter_now in enter_club) == True:
print (" ")
print ("But as you enter, you are met with an intelegence test. \n It reads:")
check_name = input("What is your name? ")
def list_check():
if (check_name in name_list) == True:
print("Let me check.. Yes, here you are. Enjoy yourself, %s!" % check_name)
enter_the_club()
elif check_name.isalpha() == False:
print("Haha, nice try %s! Let's hear your real name." % check_name)
list_check()
elif (check_name in name_list) == None:
print ("You will need to give us your name if you want to come in.")
list_check()
else:
print ("I am sorry, but I can not find your name on the list, %s." % check_name)
print ("Are you sure that's your listed name?")
list_check()
list_check()
print ("But as you enter, you are met with an intelegence test.")
print (" ")
print ("It reads:")
Test_Answer = True
def IQtest():
User_Answer = input("Is 18/4 % 3 < 18 True or False? ")
if Test_Answer == User_Answer:
print ("Great, %s, the answer is correct!" % check_name)
else:
print ("You are not allowed to enter before the answer is correct, %s!" % check_name)
IQtest()
IQtest()

True is a boolean constant. What the user enters will be either "True" or "False", both character strings. Also, your elif condition cannot be true. What are you trying to do with three decision branches?
Without changing your code too much ... try this?
Test_Answer = "True"
def IQtest():
User_Answer = input("Is 18/4 % 3 < 18 True or False? ")
if Test_Answer == User_Answer:
print ("Great, %s, the answer is correct!" % check_name)
else:
print ("You are not allowed to enter before the answer is correct, %s!" % check_name)
IQtest()
Note that I've also corrected your "else" syntax.
Also, you have no value for check_name; I assume this is a global variable that you've handled elsewhere.

Related

print something when input isn't something specified

Sorry for the horrible question. Basically, I am making the Yes or No game in Python and I need it to print something e.g. "You Win" if they input something from a library that I have already made with every acceptable word. TY in advance
q1 = input ("Answer: ")
while q1 == "yes" or "Yes" or "no" or "No":
print ("Sorry but you answered \"" + q1 + "\" which means you lose!")
sys.exit ("\nGame Over")
if q1 == ###:
print ("Well done you have earned yourself a point")
score +=1
print ("Your current score is: " + score)
input_word = input('Insert a word: ')
list_of_acceptable_words = ['word1', 'word2']
if input_word in list_of_acceptable_words:
print('You Win')
Where input_word is a string containing the input from the user and list_of_acceptable_words is a list of acceptable words
You can probably start out from this snippet, using the built-in set type:
>>> lib={'Alice','Bob'}
>>> print('Bob' in lib)
True
>>> print('Carol' in lib)
False
Then one can add a bit of code around to match your needs more closely:
>>> guess='Dave'
>>> print(['You lose...', 'You WIN!'][guess in lib])
You lose...
>>> guess='Alice'
>>> print(['You lose...', 'You WIN!'][guess in lib])
You WIN!
Edit: now that you have updated your OP with some snippet, I can write some code more in line with your needs.
accepted=set(line.strip() for line in open('accepted.txt'))
q1 = input("Answer: ")
while q1.lower() in {"yes", "no"}:
print ("Sorry but you answered \"" + q1 + "\" which means you lose!")
sys.exit ("\nGame Over")
if q1 in accepted:
print ("Well done you have earned yourself a point")
score +=1
print ("Your current score is: " + score)
Of course, if you count good answers, you will want to put this into some loop, then the initializition of accepted can stay outside.

NameError: name is not defined but first instance is fine

I'm currently going through Learn Python The Hard Way Exercises and wanted to try writing my own code to let a user choose different paths. When I run the code below, I don't get a name error for "first_decision". However, I keep getting a name error saying it's not defined for the variable "second_decision". I am running Python 2.7.10. Does anyone know why this is?
Error Here:
NameError: name 'second_decision' is not defined
Code Here:
print "This is the root level where we now create 3 branches of decisions. 1, 2, or anything else"
first_decision = raw_input("> ")
print "You chose %r" % first_decision
if first_decision == "1":
print "This is the context after player makes the first choice"
print "Once here, we can let the player make another decision. 1, 2, or 3"
second_decison = raw_input("> ")
print "You chose %r" % second_decision
if second_decision == "1":
print "This is two levels deep"
elif second_decision == "2":
print "This is two levels deep"
else:
print "Everything else for the second level"
elif first_decision == "2":
print "This is the second context after player makes the first choice"
print "Once here, we can let the player make another decision. 1, 2, or 3"
second_decison = raw_input("> ")
print "You chose %r" % second_decision
if second_decision == "1":
print "This is two levels deep"
elif second_decision == "2":
print "This is two levels deep"
else:
print "Everything else for the second level"
else:
print "This is for everything else"
You have wrong name, you assing to "second_decison" and then use "second_decision"
you missed i.
You made a typo in the line
second_decison = raw_input("> ")
This should be
second_decision = raw_input("> ")

Python Hangman game and replacing multiple occurrences of letters

This is my first year programming with Python.
I am trying to create a hangman game.
So my questions: how do I check for
If the person is guessing a letter that has already been guessed and where to include it.
Check they are inputting a valid letter not multiple letters or a number.
What happens if it's a word such as 'Good' and they guess an 'o' at the moment my code breaks if this is the case. Also where on Earth would this be included in the code?
Here is my code
import random
import math
import time
import sys
def hangman():
if guess == 5:
print " ----------|\n /\n|\n|\n|\n|\n|\n|\n______________"
print
print "Strike one, the tigers are getting lonely!"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 4:
print " ----------|\n / O\n|\n|\n|\n|\n|\n|\n______________"
print
print "Strike two, pressure getting to you?"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 3:
print " ----------|\n / O\n| \_|_/ \n|\n|\n|\n|\n|\n______________"
print
print "Strike three, are you even trying?"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 2:
print " ----------|\n / O\n| \_|_/ \n| |\n|\n|\n|\n|\n______________"
print
print "Strike four, might aswell giveup, your already half way to your doom. Oh wait, you can't give up."
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 1:
print " ----------|\n / O\n| \_|_/ \n| |\n| / \\ \n|\n|\n|\n______________"
print
print "One more shot and your done for, though I knew this would happen from the start"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 0:
print " ----------|\n / O\n| \_|_/ \n| |\n| / \\ \n| GAME OVER!\n|\n|\n______________"
print "haha, its funny cause you lost."
print "p.s the word was", choice
print
words = ["BAD","RUGBY","JUXTAPOSED","TOUGH","HYDROPNEUMATICS"]
choice = random.choice(words)
lenWord = len(choice)
guess = 6
guessedLetters = []
blanks = []
loading = ".........."
print "Loading",
for char in loading:
time.sleep(.5)
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.5)
print "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
print "Great I'm glad to see you have finally woken."
time.sleep(1)
raw_input("Did you have a nice journey? ")
time.sleep(2)
print """
Oh wait, I don't care.
I have brought you to this island simply for my amusment. I also get paid to do this.
"""
time.sleep(2)
print"""
Don't worry this isn't all for nothing.
I'm sure the tigers will enjoy your company.
"""
time.sleep(2)
print"""
Hold on, let us make things interesting.
"""
time.sleep(2)
print "I will let you live if you complete an impossible game!"
time.sleep(2)
print "A game know as hangman!"
time.sleep(2)
print "HAHAHAHAHAH, I am so evil, you will never escape!"
time.sleep(2)
print "Enjoy your stay :)"
time.sleep(1)
print
print "Alright lets begin! If you wish to guess the word type an '!' and you will be prompted"
time.sleep(.5)
print
for s in choice:
missing = choice.replace(choice, "_")
blanks.append("_")
print missing,
print
time.sleep(.5)
while guess > 0:
letterGuess = raw_input("Please enter a letter: ")
letterGuess = letterGuess.upper()
if letterGuess == "!":
print "If you guess the FULL word correcly then you win, if incorrect you die. Simple."
fullWordGuess = raw_input("What is the FULL Word? ")
fullWordGuess = fullWordGuess.upper()
if fullWordGuess == choice:
print "You must have hacked this game"
time.sleep(.5)
print "Looks like you beat an impossible game! \nGood Job \nI'll show myself out."
break
else:
print "You lost, I won, you're dead :) Have a nice day!"
print "P.S The word was ", choice
break
else:
print
if letterGuess in choice:
location = choice.find(letterGuess)
blanks.insert(location, letterGuess)
del blanks[location+1]
print " ".join(blanks)
guessedLetters.append(letterGuess)
print
print "You have guessed the letters- ", guessedLetters
if "_" not in blanks:
print "Looks like you beat an impossible game! \nGood Job \nI'll show myself out."
break
else:
continue
else:
guessedLetters.append(letterGuess)
guess -= 1
hangman()
I did not really follow your code since there seems to be something wrong with your indentation, and the many print's confused me a little, but here is how I would suggest soving your Questions:
1.1. Create a list of guessed characters:
guessed_chars = []
if(guess in guessed_chars):
guessed_chars.append(guess)
#do whatever you want to do with the guess.
else:
print("You already guessed that.")
#do what ever you want to do if you already guessed that.
1.2 Lets say the word the player has to ges is word = "snake". To get the indices (since a string is just a list of charcters in python, only that it is immutable) where the guessed letter is in the word you could then use something like:
reveal = "_"*len(word)
temp = ""
for i, j in enumerate(word):
if j == guess:
temp += guess
else:
temp += reveal[i]
reveal = temp
print(reveal)
Maybe not fancy but it should work:
if (guess not in [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z]):
with my suggestion for 1.2 you would just have to check if(word==reveal): no problem with duplicate charcters.
Since I am just a hobbyist there would probably be a more professional way though.
Next time maybe splitting up your question and first looking them up individually would be better, since I am pretty sure that at least parts of your questions have been asked before.

Inputting scoring (python 2.7.5)

I'm having trouble inputting scoring in my python quiz code. Here is the script:
#This is the Test script for )TUKT(, Developed by BOT.
print ""
print "Welcome to the Ultimate Kirby Test."
print ""
begin = (raw_input("Would you like to begin?:"))
if begin == "yes":
print ""
print "Alright then! Let's start, shall we?"
print "Q1. What color is Kirby?"
print "1) Black."
print "2) Blue."
print "3) Pink."
print "4) Technically, his color changes based on the opponent he swallows."
choice = input("Answer=")
if choice ==1:
print "Incorrect."
print ""
elif choice ==2:
print "Incorrect."
print ""
elif choice ==3:
print "Tee hee.... I fooled you!"
print ""
elif choice ==4:
score = score+1
print "Well done! You saw through my trick!"
print ""
elif choice > 3 or choice < 1:
print "That is not a valid answer."
print ""
print "Well done! You have finished my test quiz."
print("Score:")
print ""
#End of Script
The error always says
score = score+1 is not defined.
I did not get anywhere researching.
Thanks! Help is very much appreciated!
You forgot to define a variable called score. You can't reference a value that doesn't exist!
Just declare it at the start:
score = 0
In the line score = score + 1, Python goes: 'so I need to create a variable called score. It contains the value of score, plus 1.' But score doesn't exist yet, so an error is thrown.
The varibale score has never been defined. Insert score = 0 as first line of your scirpt.

How to go back to first if statement if no choices are valid

How can I have Python move to the top of an if statement if no condition is satisfied correctly.
I have a basic if/else statement like this:
print "pick a number, 1 or 2"
a = int(raw_input("> ")
if a == 1:
print "this"
if a == 2:
print "that"
else:
print "you have made an invalid choice, try again."
What I want is to prompt the user to make another choice for this if statement without them having to restart the entire program, but am very new to Python and am having trouble finding the answer online anywhere.
A fairly common way to do this is to use a while True loop that will run indefinitely, with break statements to exit the loop when the input is valid:
print "pick a number, 1 or 2"
while True:
a = int(raw_input("> ")
if a == 1:
print "this"
break
if a == 2:
print "that"
break
print "you have made an invalid choice, try again."
There is also a nice way here to restrict the number of retries, for example:
print "pick a number, 1 or 2"
for retry in range(5):
a = int(raw_input("> ")
if a == 1:
print "this"
break
if a == 2:
print "that"
break
print "you have made an invalid choice, try again."
else:
print "you keep making invalid choices, exiting."
sys.exit(1)
You can use a recursive function
def chk_number(retry)
if retry==1
print "you have made an invalid choice, try again."
a=int(raw_input("> "))
if a == 1:
return "this"
if a == 2:
return "that"
else:
return chk_number(1)
print "Pick a number, 1 or 2"
print chk_number(0)
Use a while loop.
print "pick a number, 1 or 2"
a = None
while a not in (1, 2):
a = int(raw_input("> "))
if a == 1:
print "this"
if a == 2:
print "that"
else:
print "you have made an invalid choice, try again."

Categories