I am messing around with this basic Magic 8 Ball program and im trying to make it only allow yes or no questions I am thinking that it will only except questions that have the first word "will" or "do" how can I make a that only allows those to words?
Here is the Script:
import random
import time
print "Welcome to Magic Eight Ball !"
while True:
def Magic8(a):
foo = ['Yes', 'No', 'Maybe', 'Doubtful', 'Try Again']
from random import choice
print choice(foo)
a = raw_input("Question: ")
if a == "exit":
exit()
#If Stament here
print "Determining Your Future..."
time.sleep(2)
Magic8(a)
if a.split(None, 1)[0].lower() in {'will', 'do'}:
print "Determining Your Future..."
time.sleep(2)
magic8(a) # function names are usually not capitalized
str.split() splits the sentence on whitespace, str.lower should handle the uppercase.
You can use str.startswith and pass a tuple of accepted words.
if a.lower().startswith(("will ", "do ")):
# Do your magic.
maybe if you have little words you can use elif or or
if a=="exit":
exit()
elif a=="optionOne":
doSomething
else:
print "word not alowed"
Or you can do like this
if a=="exit" or a=="notAllowedWord":
exit()
Related
I have been on and off programming but recently I have been more active and done some basic projects. However I have been stuck on this particular problem for the past 3 weeks and still cannot seems to solve it. Looked through some codes and tried and only could improve some parts. The bottom is my full code.
The problems that I faced is the one that I have stated in my title, I need to display the mystery word as dashes and when I guess the unknown word, it was suppose to appear as the only word. One issue is when I guess the word correctly, it only display the single alphabet and reset immediately.
import random
word_list =[
"SAXOPHONE",
"THEREMIN",
"XYLOPHONE",
"TROMBONE",
"RECORDER",
"OCARINA",
"HANG",
"GUITAR",
"PIANO",
"DIDGERIDOO",
"CELLO",
"CLARINET",
"BONGO",
"DRUM",
"FLUTE",
"ERHU",
"DIZI",
"HARMONICA",
"GONG",
"GUZHENG"
]
pick_word = random.choice(word_list)
pick_letter = list(pick_word)
print(pick_letter)
print("Welcome to Hangman Instrumental")
turns = 10
while turns > 0:
# input of players(input to accept both lower and upper case)
player_in = input(str("\nEnter a Character: ")).upper()
# check if input is the same as the pick letter
if player_in in pick_letter:
if player_in in pick_letter:
print(player_in)
elif len(player_in) != 1:
print("Invalid input please try again")
else:
turns -= 1
print("You have ",turns, " turns left")
if turns == 0:
print("You Lose !")
Keep a list of all the player's guesses. When you start a new game, set all_guesses to [] and then, reading the letter from the console set:
all_guesses.append(player_in)
Now you can display just letters from that list in the secret word with:
display_word = ''
for c in pick_word:
if c in all_guesses:
display_word += c
else:
display_word += '-'
Then print out display_word however you like. You can combine all of that into a single Python expression:
display_word = ''.join(c if c in all_guesses else '-' for c in pick_word)
That uses three ideas that you may not have seen yet (if-else expressions, generator expressions and the .join() string member function) so if it looks like Martian to you, that's okay. Think of it as a peek ahead into cool things you'll learn later.
I made a really simple program that requests an input and puts a comma or question mark at the end. If the sentence starts with why, how, etc, the program adds an question mark.
But how can I make the last comma a period, so that I can make a proper sentence?
The code:
def sentence_maker(phrase):
x = ("Why", "What", "Who", "How")
sentence = phrase.capitalize()
if sentence.startswith(x):
return "{}?\n".format(sentence)
else:
return "{},".format(sentence)
results = []
while True:
y = input("Say something: ")
if y=="end":
break
else:
results.append(sentence_maker(y))
print(" " .join(results))
The idea is to make something that work like this:
input:
say something: hello
say something: how are you
say something: i'am good
say something: thank you
output:
Hello, How are you?
I'am good, Thank you.
One way to fix this could be to edit the last element after registering that the input is "end".
while True:
y = input("Say something: ")
if y=="end":
results[-1] = results[-1][:-1] + "."
break
else:
results.append(sentence_maker(y))
Test Output:
Say something: Why
Say something: the
Say something: quick
Say something: brown
Say something: fox
Say something: jumps
Say something: end
Why?
The, Quick, Brown, Fox, Jumps.
I am trying to check whether any value in a list exist in a sentence as below:
rich = ["Businessman","Robber","Politician"]
poor = ["Programmer","Engineer","Doctor"]
whoAmI = "I am an Engineer"
if rich.*MISSING_HERE* in whoAmI:
print "You are RICH"
else :
print "You are POOR"
If you look at the line with the if statement, I am checking whether any element fron rich is available in whoAmI. How do I check this?
Use any() method -
if any(r in whoAmI for r in rich):
print "You are RICH"
else :
print "You are POOR"
Try for else loop
rich = ["Businessman","Robber","Politician"]
poor = ["Programmer","Engineer","Doctor"]
whoAmI = "I am an Engineer"
for r in rich:
if r in whoAmI:
print "You are RICH"
break
else:
print "You are POOR"
We can use the re or regex module of Python Library to search for the word in the string. We will be using simple for loop ( Note: Time complexity : O(n))
import re
rich = ["Businessman","Robber","Politician"]
poor = ["Programmer","Engineer","Doctor"]
whoAmI = "I am an Businessman"
for word in rich:
if re.search(i, whoAmI):
print("Rich")
quit()
print("Poor")
We are using Python inbuilt function quit() so as to prevent same outputs from displaying multiple times.
You can use this simplified answer
[any( j in rich for j in whoAmI.split())]
If it satisfies the condition, it will answer True(i.e., 'rich') else it will notify false.
With a list of comprehension:
if len([x for x in rich if x in whoAmI]):
print ("You are RICH")
else :
print ("You are POOR")
You are POOR
So I want to make a bot that tells jokes but I am having trouble checking if any part of an input is part of a seperate list. So for instance (side note: this is all in a while loop):
punWords = [pun, Puns]
userInput = input('What kind of jokes do you want to hear?')
elif userInput in punWords:
print(random.choice(punJokes))
print(random.choice(jokeResponses))
print(' ')
jokeFunc2()
else:
print('Sorry I dont know any of these jokes')
The problem im having is that if the user inputs something like "I want to hear a pun" Then it goes through and compares every word to punWords and if it doesn't match then it prints the "Sorry I don't know any of these jokes" message so that the output ends up looking something like this:
'Sorry I dont know any of these jokes'
'Sorry I dont know any of these jokes'
'Sorry I dont know any of these jokes'
'Sorry I dont know any of these jokes'
'Sorry I dont know any of these jokes'
'Insert pun joke'
What I want to happen is that it only prints the error message if the input doesnt match any of the other words. Thanks a lot for any help and sorry if the post isnt done right (this is my first time posting on any kind of forum).
One way you could do it is to count the number of matches. Then if there are zero matches, print the error message. Something like:
if userInput in punWords:
matchedWords += 1
then after the while loop
if matchedWords:
# do your thing
else:
print ("Sorry I don't know any of these jokes")
You are basically looking for the intersection between two lists (the list of pun words and the list of words entered), which can be performed using a Python set:
words = userInput.split()
if (set(words) & set(punWords)):
print(random.choice(punJokes))
or more simply demonstrated:
a = [1,2,3]
b = [3,4,5]
print(list(set(a) & set(b))) #result: [3]
For example
userDay = input("How was you day? ")
The user input "My day was good"
and then the program recognizes that the user said "good", and then chooses the correct response for "good".
Sorry if you don't understand, its hard to explain.
Easy and quick way would be split the response into words using response.split() and then check each word if it equal to good
This way you can avoid searching for ‘ good’ or ‘ good ‘ or ’good ‘ (good word can be starting word, ending word or somewhere in the line)
I'd suggest using python's built-in lexical analysis tool, shlex. It is very useful as it contains functionality that makes it easy to write a (simple) lexical analyzer.
So in your case you can do something like this:
import shlex
user_input = 'My day was good'
li = shlex.split(user_input)
print 'Your day was good' if 'good' in li else 'Your day was bad'
The prints here are for demonstrating purposes only. You have to substitute them with your code that will choose the correct response for "good".
Just check if a substring is in a string:
userDay = input("How was you day? ")
if 'good' in userDay:
print('good')
or you can use:
if userDay.find('good') == 1:
print('good')
Something like this:
response = input("How was you day? ")
if response == 'good':
# do something
Or if you're just looking for 'good' in the response somewhere:
response = input("How was you day? ")
if 'good' in response.lower():
# do something