I am helping a friend with some code for a school helping bot, but I've run into a problem. On the last line, where it says: if helpselect == ('*****'): , I am trying to add multiple conditions in one line of code so that the specific line of code activates when they type math or math. HELP
import time
print('Hello, my name is CareBot and I am here to help!')
time.sleep(3)
name = input('Please input your name: ')
print('Nice to meet you, %s. I am a bot that can lead you to resources to help out with school subjects!' % name)
time.sleep(2)
print('Now, what subject can I help you with?')
helpselect = input('Please input a subject: ')
if helpselect == ('*****'):
if helpselect in {"math", "english"}:
print("You selected math or english")
Something like that? (You said "when they type math or math", which is redundant.)
If you're just trying to check if the person typed a certain subject then I might create a set of strings. When you check if something is in a set of strings you are checking whether or not the word you typed is one of the words in the set of strings.
setofstrings = ["math", "english", "science"]
if helpselect in setofstrings:
or perhaps you want to do this.
if helpselect == "math" or helpselect == "english":
If you're trying to check if there are any math symbols in a line of code.
What I would do is create a string called mathsymbols.
mathsymbols = "+-*/"
Then check and see if the input contains any math symbols by doing this line of code. This checks if what you typed any individual character in the string mathsymbols.
if helpselect in mathsymbols:
I would want learn sets, strings, the "in" operator, "and", "or", etc.
Related
I am trying to make a calculator and the user must input which operation they want to use, I have only done addition so far but you get the point.
welcome = str(input("Welcome to the calculator, which form of operation do you wish to choose? "))
Addition = "Add", "add", "Addition", "addition", "+"
for x in Addition:
if welcome == Addition:
print("Works")
I run the code and when I input any of the strings in the "Addition" variable, it does not print "Works"?.
I have tried without the for loop and it still does not print "Works"
I am an absolute beginner at python and I just made this stackoverflow account today. I don't know how to write the code in proper code form in this question.
You are probably looking for in we can also use .lower() on the input so we have fewer things to match.
welcome = str(input("Welcome to the calculator, which form of operation do you wish to choose? ")).lower()
addition = ['add','addition','+']
if welcome in addition:
print('worked')
Hi im new with python but in my school i was asked to write a code that ask the user to input a word and a sentence with few feature but it must have a presence check (so the user cant just leave the question blank or the word) but i dont know how to put a presence check, also if the word or sentence is left blank the user should be able to re-enter it again. can anyone help me?
Use a while loop as long as UserSen is empty:
UserSen = input("Please type in a sentence without punctuation: ").lower()
while len(UserSen) == 0:
UserSen = input("Please type in a sentence without punctuation: ").lower()
UserSen = UserSen.split()
I'm new to Python and I have a question.
I am making a simple chatbot and I want it to give answers to questions and things like that.
Here is an example:
def ChatMode():
ChatCommand = raw_input ("- user: ")
if "quit" in ChatCommand :
print "Lucy: See you later."
print ""
UserCommand()
else :
print "Lucy: sorry i don\'t know what you mean."
ChatMode()
For something more advanced I need it to check for 2 strings.
I tried some things like:
def ChatMode() :
ChatCommand = raw_input ("- user: ")
if "quit" + "now" in ChatCommand :
print "Lucy: See you later."
print ""
UserCommand()
else :
print "Lucy: sorry i don\'t know what you mean."
ChatMode()
But that made "quitnow".
I also tried to replace the + with an & but that gave me an error:
TypeError: unsupported operand type(s) for &: 'str' and 'str'
Does anyone have a short code to do this? I don't want 5+ sentences, I want to keep it as short as possible.
Use separate clauses to check if both "quit" and "now" are in the ChatCommand e.g.
if "quit" in ChatCommand and "now" in ChatCommand:
Note that in Python, the logical and operator && is and, and & is the bitwise and.
if "quit" in ChatCommand and "now" in ChatCommand:
Also, as a bit of style, in Python CamelCase is usually reserved for Classes.
Use all():
if all(word in ChatCommand for word in ("quit", "now")):
If you want to avoid matching quit within quite, you can use a regex:
import re
if all(re.search(regex, ChatCommand) for regex in (r"\bquit\b", r"\bnow\b")):
because the \b word boundary anchors only match at the start and end of a word.
I'm trying to create a function to check if the user inputs a number. If the user inputs a number my program should output an error message, if the users enters a string of letters, my program should proceed with program. How can I do this?
I've come up with this so far:
#Checks user input
def CheckInput():
while True:
try:
city=input("Enter name of city: ")
return city
except ValueError:
print ("letters only no numbers")
This function doesn't seem to work. Please help.
You are looking to filter out any responses that include digits in the string. The answers given will do that using a regular expression.
If that's all you want, job done. But you will also accept city names like Ad€×¢® or john#example.com.
Depending on how choosy you want to be, and whether you're just looking to fix this code snippet or to learn the technique that the answers gave you so that you can solve the next problem where you want to reject anything that is not a dollar amount, say),you could try writing a regular expression. This lets you define the characters that you want to match against. You could write a simple one to test if the input string contains a character that is not a letter [^a-zA-Z] (the ^ inside [ ] means any character that is not in the class listed). If that RE matches, you can then reject the string.
Then consider whether the strict rule of "letters only" is good enough? Have you replaced one flawed rule (no digits allowed) with another? What about 'L.A.' as a city name? Or 'Los Angeles'? Maybe you need to allow for spaces and periods. What about hyphens? Try [^a-zA-Z .-] which now includes a space, period and hyphen. The backslash tells the RE engine to treat that hyphen literally unlike the one in "a-z".
Details about writing a regex here:http://docs.python.org/3/howto/regex.html#regex-howto
Details about using the Re module in Python here: http://docs.python.org/3/library/re.html#module-re
import re
def CheckInput():
city = input('Enter name of city: ')
if re.search(r'\d', city):
raise Exception('Invalid input')
You wouldn't be type checking because in Python 3 all text inputs are strings. This checks for a decimal value in the input using regular expressions and raises an exception if one is found.
val = input("Enter name of city:")
try:
int( val )
except ValueError:
return val
else:
print("No numbers please")
Edit: I saw mention that no number should be present in the input at all. This version checks for numbers at any place in the input:
import re
val = input("Enter name of city:")
if re.search( r'\d', val ) is not None:
print("No numbers please")
else:
return val
You can use the type(variable_name) function to retrieve the type.
I have to write a program in python where the user is given a menu with four different "word games". There is a file called dictionary.txt and one of the games requires the user to input a) the number of letters in a word and b) a letter to exclude from the words being searched in the dictionary (dictionary.txt has the whole dictionary). Then the program prints the words that follow the user's requirements. My question is how on earth do I open the file and search for words with a certain length in that file. I only have a basic code which only asks the user for inputs. I'm am very new at this please help :(
this is what I have up to the first option. The others are fine and I know how to break the loop but this specific one is really giving me trouble. I have tried everything and I just keep getting errors. Honestly, I only took this class because someone said it would be fun. It is, but recently I've really been falling behind and I have no idea what to do now. This is an intro level course so please be nice I've never done this before until now :(
print
print "Choose Which Game You Want to Play"
print "a) Find words with only one vowel and excluding a specific letter."
print "b) Find words containing all but one of a set of letters."
print "c) Find words containing a specific character string."
print "d) Find words containing state abbreviations."
print "e) Find US state capitals that start with months."
print "q) Quit."
print
choice = raw_input("Enter a choice: ")
choice = choice.lower()
print choice
while choice != "q":
if choice == "a":
#wordlen = word length user is looking for.s
wordlen = raw_input("Please enter the word length you are looking for: ")
wordlen = int(wordlen)
print wordlen
#letterex = letter user wishes to exclude.
letterex = raw_input("Please enter the letter you'd like to exclude: ")
letterex = letterex.lower()
print letterex
Here's what you'd want to do, algorithmically:
Open up your file
Read it line by line, and on each line (assuming each line has one and only one word), check if that word is a) of appropriate length and b) does not contain the excluded character
What sort of control flow would this suggest you use? Think about it.
I'm not sure if you're confused about how to approach this from a problem-solving standpoint or a Python standpoint, but if you're not sure how to do this specifically in Python, here are some helpful links:
The Input and Output section of the official Python tutorial
The len() function, which can be used to get the length of a string, list, set, etc.
To open the file, use open(). You should also read the Python tutorial sec. 7, file input/output.
Open a file and get each line
Assuming your dictionary.txt has each word on a separate line:
opened_file = open('dictionary.txt')
for line in opened_file:
print(line) # Put your code here to run it for each word in the dictionary
Word length:
You can check the length of a string using its str.len() method. See the Python documentation on string methods.
"Bacon, eggs and spam".len() # returns '20' for 20 characters long
Check if a letter is in a word:
Use str.find(), again from the Python sring methods.
Further comments after seeing your code sample:
If you want to print a multi-line prompt, use the heredoc syntax (triple quotes) instead of repeated print() statements.
What happens if, when asked "how many letters long", your user enters bacon sandwich instead of a number? (Your assignment may not specify that you should gracefully handle incorrect user input, but it never hurts to think about it.)
My question is how on earth do I open the file
Use the with statement
with open('dictionary.txt','r') as f:
for line in f:
print line
and search for words with a certain length in that file.
First, decide what is the length of the word you want to search.
Then, read each line of the file that has the words.
Check each word for its length.
If it matches the length you are looking for, add it to a list.