I'm experimenting with raw_input and it works fine except for my 1st if statement and my else statement. Whenever I run the code and answer the 2nd question with a raw_input listed after 'League' in the 1st if statement, it returns both the 1st if's print and the else's print when it should only print the 1st if. Any idea what's wrong?
name = raw_input('What is your name?\n')
game = raw_input('\nWhat MOBA do you play/have played? \n(The answer ' \
'must be case sensitive i.e. LoL for League and DoTA for y\'know the whole darn thing '\
'is too '\
'darn long to say even though I typed a lot more than the name)\n')
if game in ('League' , 'League of Legends' , 'LoL'):
print '\nYou go girl! '
if game in ('DoTA' , 'DoTA 2' , 'DoTA2'):
print '\nThat\'s cool and all but........ Go play League you dang noob. '
else:
print '\nAre you kidding me? You play %s? I\'m severely disappointed in you %s. You ' \
'should at least be playing ' \
'one of these popular games. \nShame, shame, shame. Go install one. ' % (game, name)
you can always use if for the first conditional, elif for any number of other conditionals (if the input is in the second list in your instance) and else if the input is not in any of those lists, your indentation is also a little messed up,nesting if statements inside each other will only run the nested conditional if the first statement is true, I'd also recommend you use the string.lower() method on your users input so you don't have to instruct the user to type case-sensitive input and use variables to store those lists so you can reuse them elsewhere in your code..something like this:
name = raw_input('What is your name?\n')
game = (raw_input('\nWhat MOBA do you play/have played?')).lower()
awesomeGames=['league' , 'league of legends' , 'lol']
coolGames=['dota' , 'dota 2' , 'dota2']
if game in awesomeGames:
print '\nYou go girl! '
elif game in coolGames:
print '\nThat\'s cool and all but........ Go play League you dang noob. '
else:
print '\nAre you kidding me? You play %s? I\'m severely disappointed in you %s. You ' \
'should at least be playing ' \
'one of these popular games. \nShame, shame, shame. Go install one. ' % (game, name)
The indent level is incorrect.
Spend one more space for the second if statement.
or 1 less space and elif instead of the second if.
Replace the second if condition by elif. elif can be used as many times as you want until the condition matches but its better practice to have the last condition as else (which is like default statement when other conditions have failed)
Related
My problem is, that my program randomly generates a random answer if the userinput contains more than one word, even though i don't want to. I mean i understand why the programm generates a random answer, but how can i overcome this?
Here is my code:
import random
print("Welcome to Chatbot! Have fun.")
print("")
randomanswer = ['Thats not good', 'me too', 'how about you?']
reactionanswer = {'hello': 'hello, whats up?',
'sad': 'speak to me',
'entertainment': 'how can i entertain you?'}
userinput = ''
while True:
userinput = input("Question/Answer: ")
userinput = userinput.lower()
if userinput == 'bye':
print("See you soon!")
break
else:
usersplit = userinput.split()
for i in usersplit:
if i in reactionanswer:
print(reactionanswer[i])
else:
print(random.choice(randomanswer))
Works fine for me, I ran exactly your code and get this:
Question/Answer: hello guy
hello, whats up?
Thats not good
Question/Answer: nothing in the list
me too
me too
me too
Thats not good
work also for several words. it depend on what works meaning - you wrote that for each word that not in your known list it would generate random answer. and for any known word it will answer as you want to. and that exactly what happen - in the first case the first word generated the first known answer and the second generated random answer. clarify what exactly not work as you expect.
The problem is that even though you found your answer the for loop continues to run. Add add "break" statement if the word has been found in answers. Like this:
else:
usersplit = userinput.split()
for i in usersplit:
if i in reactionanswer:
print(reactionanswer[i])
break < --- add this
else:
print(random.choice(randomanswer))
I'm following the "Learn Python The Hard Way" book. In the partial example below the input string is compared against some values.
When I execute the code, if you enter any input that contains the word + any other character, it is still evaluated to True,
e.g. > fleeee, headsss, headhead
def cthulhu_room():
print "Here you see the great evil Cthulhu."
print "He, it, whatever stares at you and you go insane."
print "Do you flee for your life or eat your head?"
choice = raw_input("> ")
if "flee" in choice:
start()
elif "head" in choice:
dead("Well that was tasty!")
else:
cthulhu_room()
How can I modify it so it matches 'head' exactly?
Use == instead of in.
By using in you search if it's inside.
Using == checks for the exact string.
I need to find a way to return a sentence based upon the input of the user i.e key word search.
I have a dictionary created and can return a sentence based on one word but cant figure out if I can return a sentence based on multiple words:
water damage returns a sentence on dropping your phone into water
i have a cracked screen does not return anything. I am aware that the issue is around the .split.strip functions I am using.
My next issue is that I can not seem to create a null entry check, I have tried the usual, while input_1 is None, or =='' yet the strip function removes whitespace so I am guessing there is no null entry to pick up on.
similar_words = {
'water': 'you have let water into your phone',
'wet': 'let your phone dry out then try to restrat the phone',
'crack case': 'you have cracked your screen or case, this will need replacing by a specialist',
'cracked screen': 'you have cracked your screen or case, this will need replacing by a specialist',
'turn on': 'your battery may need replacing',
'crack': 'your phone screen has been cracked, you need to contact the technician centre',
}
def check():
if word.lower() in similar_words:
print(similar_words[word.lower()])
input_1 = input("What seems to be the problem with your phone?: ").strip().split()
for word in input_1:
check()
def close():
print ('Please press enter to close the program')
quit()
close_1 = input('Have we addressed your problem, please answer yes or no?: ')
if close_1=='yes':
close()
else:
print ('Lets us move on then')
If the input is simply "cracked screen" then the call to split() returns a list of two words: ["cracked", "screen"]. The test word.lower() in similar_words effectively compares each word to all of the keys of the dictionary looking for a match.
As you have neither "cracked" nor "screen" as a key in the dictionary, it fails to find a match.
Each of your keys needs to be a single word if you are splitting your input to a list of single words.
But then, if you have "cracked" as a key, an input such as "my case cover is cracked" will be reported as if it was a cracked screen.
You need a much smarter test, and probably need to read up on ngrams. Split the input into unigrams, bigrams, etc, and check each against the list of keys. Then you need to figure out how to deal with inputs like "my screen is cracked".
As for the NULL check, if the input string is empty, strip().split() will return an empty list ([]). Check for len(input_1) == 0.
According to your program I think that you need to display the phone problem's solution only but your program is not displaying it. So I have done some changes in the program and it is displaying it.
similar_words = {
'water': 'you have let water into your phone',
'wet': 'let your phone dry out then try to restart the phone',
'crack case' : 'you have cracked your screen or case, this will need replacing by a specialist',
'cracked screen' : 'you have cracked your screen or case, this will need replacing by a specialist',
'turn on' : 'your battery may need replacing',
'crack' : 'your phone screen has been cracked, you need to contact the technician centre'
}
input_1 = input("What seems to be the problem with your phone?: ").split()
for word in input_1:
if word in similar_words.keys():
print(similar_words[word])
#similar_words[word] gives only the value of the key word
close_1 = input('Have we addressed your problem, please answer yes or no?: ')
if close_1=='yes':
quit()
else:
print ('Lets us move on then')
As a newbie to programming I currently have an exam where I am supposed to submit Python code for a madlibs game. What I am currently missing in my code is the validation of the user input against the word that should appear in the text.
Right now the program is able to take user input and display the full text but I don't know where to put the validation of the user input in my code, especially because I am going through a list of different words. I know that I have to define the variable somewhere to make a check against the user input but I am completely stuck right now.
This is the current working version of my code, i.e. without the attempt of the input validation against the words.
print "Welcome to my first quiz with user input"
print "Lets get cracking straight away"
print
import time
while True:
difficulty_level = raw_input("Which difficulty level would you like? Type EASY, MEDIUM or HARD to continue? ")
if difficulty_level.upper() == "EASY":
time.sleep(1)
print "Here it goes..."
print
time.sleep(1)
print "Here's your text. Should be an easy one. Just fill in the blanks for _Word_ 1-3."
print
print
print "Python is a _Word1_ language that provides constructs intended to enable clear programs on both small and large scale. Python implementation was started in December _Word2_ by Guido von Rossum. The most simple _Word3_ in Python is _Word4_ and normally used at the beginning to tell Python to write 'Hello World' on the screen."
print
# A list of replacement words to be passed in to the play game function.
parts_of_speech1 = ["_Word1_", "_Word2_", "_Word3_", "_Word4_"]
# The following is the text for the easy text..
easy_text = "Python is a _Word1_ language that provides constructs intended to enable clear programs on both small and large scale. Python implementation was started in December _Word2_ by Guido von Rossum. The most simple _Word3_ in Python is _Word4_ and normally used at the beginning to tell Python to write 'Hello World' on the screen."
# Checks if a word in parts_of_speech is a substring of the word passed in.
def word_in_pos_easy(word, parts_of_speech1):
for pos in parts_of_speech1:
if pos in word:
return pos
return None
# Plays a full game of mad_libs. A player is prompted to replace words in the easy text,
# which appear in parts_of_speech with their own words.
def easy_game(easy_text, parts_of_speech1):
replaced = []
easy_text = easy_text.split()
for word in easy_text:
replacement = word_in_pos_easy(word, parts_of_speech1)
if replacement != None:
user_input = raw_input("Type in: " + replacement + " ")
word = word.replace(replacement, user_input)
replaced.append(word)
else:
replaced.append(word)
replaced = " ".join(replaced)
print
time.sleep(1)
print "Ok, lets see your results. Does it make sense?"
print
time.sleep(1)
return replaced
print
time.sleep(1)
print easy_game(easy_text, parts_of_speech1)
# Difficulty Level Medium
if difficulty_level.upper() == "MEDIUM":
time.sleep(1)
print "Good choice. Lets see how much you know about Python"
print
time.sleep(1)
print "Here's your text. It's a tricky one that requires some more knowledge about Python. Just fill in the blanks for _Word_ 1-3."
print
print
print "A string object is _Word1_, i.e. it cannot be modified after it has been created. An important concept in Python and other programming languages is _Word2_. You use them to store a value. To assign a value to a Variable you use the _Word3_ operator. A more versatile data type in Python is _Word4_. They contain items separated by commas and within square brackets. To some extent they are similar to arrays in C."
print
# A list of replacement words to be passed in to the play game function.
parts_of_speech2 = ["_Word1_", "_Word2_", "_Word3_", "_Word4_"]
# The following are some test strings to pass in to the play_game function.
medium_text = "A string object is _Word1_, i.e. it cannot be modified after it has been created. An important concept in Python and other programming languages is _Word2_. You use them to store a value. To assign a value to a Variable you use the _Word3_ operator. A more versatile data type in Python is _Word4_. They contain items separated by commas and within square brackets. To some extent they are similar to arrays in C."
# Checks if a word in parts_of_speech is a substring of the word passed in.
def word_in_pos_medium(word, parts_of_speech2):
for pos in parts_of_speech2:
if pos in word:
return pos
return None
# Plays a full game of mad_libs. A player is prompted to replace words in ml_string,
# which appear in parts_of_speech with their own words.
def medium_game(medium_text, parts_of_speech2):
replaced = []
medium_text = medium_text.split()
for word in medium_text:
replacement = word_in_pos_medium(word, parts_of_speech2)
if replacement != None:
user_input = raw_input("Type in: " + replacement + " ")
word = word.replace(replacement, user_input)
replaced.append(word)
else:
replaced.append(word)
replaced = " ".join(replaced)
print
time.sleep(1)
print "OK, lets see your results. Does it make sense?"
print
time.sleep(1)
return replaced
print
time.sleep(1)
print medium_game(medium_text, parts_of_speech2)
# Difficulty Level Hard
if difficulty_level.upper() == "HARD":
time.sleep(1)
print "Bold move! Here we go. Check out this text. It's a tough one"
print
time.sleep(1)
print "Here's your text. This one requires quite some Python knowledge"
print
print
print "Similar to other programming languages, Python has flow controls. The most known statement is the _Word1_ statement. It can be combined with an else statement and helps to process a logic based on a specific condition. For more repetitive processing one needs to use loops. _Word2_ loops execute a sequence of statements multiple times and abbreviates the code that manages the loop variable._Word3_ loops repeat a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body."
print
# A list of replacement words to be passed in to the play game function.
parts_of_speech3 = ["_Word1_", "_Word2_", "_Word3_", "_Word4_"]
# The following are some test strings to pass in to the play_game function.
hard_text = "Similar to other programming languages, Python has flow controls. The most known statement is the _Word1_ statement. It can be combined with an else statement and helps to process a logic based on a specific condition. For more repetitive processing one needs to use loops. _Word2_ loops execute a sequence of statements multiple times and abbreviates the code that manages the loop variable. _Word3_ loops repeat a statement or group of statements while a given condition is TRUE. It tests the _Word4_ before executing the loop body."
# Checks if a word in parts_of_speech is a substring of the word passed in.
def word_in_pos_hard(word, parts_of_speech3):
for pos in parts_of_speech3:
if pos in word:
return pos
return None
# Plays a full game of mad_libs. A player is prompted to replace words in the hard text,
# which appear in parts_of_speech with their own words.
def hard_game(hard_text, parts_of_speech3):
replaced = []
hard_text = hard_text.split()
for word in hard_text:
replacement = word_in_pos_hard(word, parts_of_speech3)
if replacement != None:
user_input = raw_input("Type in: " + replacement + " ")
word = word.replace(replacement, user_input)
replaced.append(word)
else:
replaced.append(word)
replaced = " ".join(replaced)
print
time.sleep(1)
print "OK, lets see your results. Does it make sense?"
print
time.sleep(1)
return replaced
print
print hard_game(hard_text, parts_of_speech3)
else:
print "Sorry, that was not a correct input. Please enter EASY, MEDIUM or HARD to set the difficulty level."
Here's how I would do it:
from random import shuffle
import sys
from time import sleep
# version compatibility shim
if sys.hexversion <= 0x3000000: # Python 2.x
inp = raw_input
else: # Python 3.x
inp = input
def get_word(prompt):
return inp(prompt).strip().lower()
def shuffled(words):
words_copy = list(words)
shuffle(words_copy)
return words_copy
class MadLib:
BLANK = "___"
DELAY = 1
def __init__(self, intros, prompt, words):
self.intros = intros
self.prompt = prompt
self.words = words
self.num_words = len(words)
assert prompt.count(self.BLANK) == self.num_words, "Number of blanks must match number of words!"
def play(self):
# show introduction
for s in self.intros:
sleep(self.DELAY)
print(s, flush=True)
# display madlib with blanks
sleep(self.DELAY)
print(self.prompt)
# get words from user
print("Words available: " + ", ".join(shuffled(self.words)))
gotten = [
get_word("Word {}: ".format(i))
for i in range(1, self.num_words + 1)
]
# evaluate results
num_right = sum(g == w for g,w in zip(gotten, self.words))
if num_right == self.num_words:
print("You did it!")
return True
else:
print("You got {} out of {} words right.".format(num_right, self.num_words))
return False
madlibs = {
"easy":
MadLib(
[
"Here we go...",
"Here's your text. Should be an easy one.",
"Just fill in the blanks!"
],
(
"Python is a ___ language that provides constructs intended to "
"enable clear programs on both small and large scale. "
"Python implementation was started in December ___ by "
"Guido von Rossum. The most basic ___ in Python is ___, "
"often used by beginners to tell Python to display 'Hello "
"World' on the screen."
),
['programming', '1989', 'command', 'print']
),
"medium":
MadLib(
[
"Good choice. Lets see how much you know about Python",
"Here's your text. It's a tricky one that requires some more knowledge about Python.",
"Just fill in the blanks!"
],
(
"A string object is ___, i.e. it cannot be modified after it "
"has been created. An important concept in Python and other "
"programming languages is the ___, used to store a value. "
"To assign a value to you use the ___ operator. A more "
"versatile data type in Python is ___, containing items "
"separated by commas and within square brackets and to "
"some extent they are similar to arrays in C."
),
['immutable', 'variable', 'equals', 'list']
),
"hard":
MadLib(
[
"Bold move! Here we go. Check out this text. It's a tough one!",
"Here's your text. This one requires quite some Python knowledge.",
"Just fill in the blanks!",
"Here's your text:"
],
(
"Similar to other programming languages, Python has flow "
"control commands. The most common is ___ which lets you branch "
"based on a condition. Looping commands like ___ execute "
"statements a given number of times, or ___ repeats statements "
"so long as a condition is True."
),
['if', 'for', 'while']
)
}
def main():
print(
"Welcome to my first quiz with user input!\n"
"Lets get cracking straight away."
)
while True:
choice = get_word("Which difficulty level would you like? [easy, medium, hard] (or just hit Enter to exit) ")
if not choice:
break
elif choice in madlibs:
madlibs[choice].play()
else:
print("Sorry, that was not a recognized option.")
if __name__=="__main__":
main()
if strengh1 <=0:
death1=True
else:
death1 = False
if strengh2 <=0:
death2=True
else:
death2=False
def output(character):
if death character == False:
print
print('Character', character ,' strengh is now %s' % strengh1)
print('Character ', character ,' skill is now %s' % skill1)
else:
print
print('Character ', character ,' is dead')
output(1)
output(2)
Hi guys I am currently doing a bit of a project. here is part of my very last lines of code. There are two characters and i want to be able to use a function. I am almost fully self taught and i havnt been coding very long at all so there might be basic errors or i might be doing something that just cant work, but how can i change the name of the "death" variable in the function using what is in the function call? So for example output(10 needs to change death to death1? is this possible. Also i need to be able to print this in one solid output as
Character (then the function parameter) is now dead
Your code demonstrates a profound misunderstanding of the way Python names work. Just setting character = 1 and writing death character will not access death1, that simply doesn't make any sense. There is a good primer on how Python deals with names here.
Your specific issue could be solved by passing to output all of the variables it actually needs:
def output(character, strength, skill, death):
if not death:
print
print('Character', character ,' strength is now %s' % strength)
print('Character ', character ,' skill is now %s' % skill)
else:
print
print('Character ', character ,' is dead')
output(1, strength1, skill1, death1)
This is obviously a bit awkward, so the next step would be to encapsulate these parameters as attributes in a Character class; see e.g. the tutorial. Then you can pass a single Character instance to the function.
Very often, the most natural solution is to use a dictionary.
death = dict()
# most probably strength should be a dict too
if strengh1 <=0:
death[1]=True
else:
death[1] = False
# or death[1] = bool(strength1<=0)
if strengh2 <=0:
death[2]=True
else:
death[2]=False
def output(key):
if death[key]== False:
print
print('Character', character ,' strengh is now %s' % strengh1)
print('Character ', character ,' skill is now %s' % skill1)
else:
print
print('Character ', character ,' is dead')
output(1)
output(2)
Depending on what 1 and 2 stand for, you might want to use strings instead -- strength['muscles'], death['poisoning'] perhaps? (Or strength['marketing'] and death['irrelevance'] if this is a startup game.)