Python if statement to compare to a string not working [duplicate] - python

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed 7 days ago.
I've been trying to make a line management program, but something isn't working properly and only half of it works.
I've tried to move things around and change if statements to else statements. but still only half if it works.
what's meant to happen is, the user type in a word, if that word = Next, it removes the first person in that line. if the user types any other word but Next, it adds it to the end of the list.
Example below:
# This is just a line manager :D
print("")
Line = \["Bob" , "Steve" , "Michael"\]
print(Line)
print("")
#infinit loop
I = 0
while I < 1:
print("Type the name of the person you want to add to the queue, or if you wanna remove the first person in the line, type 'Next'")
print("")
New = str(input())
if New != "Next" or "next":
Line.append(New)
print(Line)
continue
if New =="Next":
Line.remove(Line\[0\])
print(Line)

The error is on this line:
if New != "Next" or "next":
The second half, or "next", checks the truthiness of the string "next", which is true since it's a non-empty string. Also, it should check if the answer is neither, not either or. Instead, do it like this:
if New != "Next" and New != "next":
or even tidier:
if New not in ["Next", "next"]:
But in this case (and any taking user input), use this:
if New.lower() != "next":
which turns the user input to lowercase :)

Related

Typeerror: str() takes at most 3 arguments (8 given) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to create a function that shows a given course code is correct or not.
the course code starts with four letters and three numbers with space in-between them.
def checkCourseCode(input_word):
course_name =str("COMP", "LASC", "ENGN")
course_code =int(1,2,3,4,6)
for CourseCode in input_word (course_name,'',course_code):
if CourseCode == "COMP 123":
print("True")
else:
print("False")
input_word = input("Please select menu choice: ")
checkCourseCode(input_word)
If I take off the remaining 5 values from course_name I am still getting this error.
Please select menu choice: COMP 123
Traceback (most recent call last):
File "e:\CourseCode.py", line 11, in <module>
checkCourseCode(input_word)
File "e:\UCourseCode.py", line 3, in checkCourseCode
course_name =str("COMP", "LASC", "ENGN")
TypeError: decoding str is not supported
In python, lists and tuples do not require types (they are dynamic). str and int are constructors.
course_names = ("COMP", "LASC", "ENGN")
course_codes = ("215", "123", "1705")
You could set course_codes as an int, but for my example I used strings as it'll be less problematic, and also lets you use special characters too.
However lists are not the best way to do this. For example, course COMP may have course code 215 but course LASC may not. To insure this problem doesn't occur, use dictionaries. (Dictionaries don't have to be typed too.)
courses = {
"COMP":("215", "123"),
"LASC":("215", "1712"),
"ENGN":("281", "192")
}
The example above lets you access a key (or a course in our case), and get the value (the class codes for each course). Note that dictionaries are mutable (can be changed) while tuples are not.
Your original function is broken (did you forget a comma in the for loop?). While I see what you were trying to do, it isn't the best way as you have to loop through each item, which makes it go slower. Plus it also has the same issue that I noted with using lists.
This function is much more organized and neat. Let's go through it step by step.
def checkCourseCode(input_word):
input_data = input_word.split(" ")
Here we are using a method of the str object, split, which lets us seperate a string by a character. So if our input was "COMP 123", the split method turns it into ["COMP", "123"].
if len(input_data) != 2:
return False
We only want 2 things, the course name and course code. If the user inputs something extra, it might cause an issue. Here we are making sure that it is exactly 2 items and if not, it is not a valid course.
if input_data[0] in courses:
This line checks if the course name is in our database (courses dict).
if input_data[1] in courses[input_data[0]]:
print("True")
return True
We are doing the same thing we did last time. Only this time we are getting the value from the key (getting the codes from the course) and checking if the code the user inputted is in those codes. If it is true, we print out true and return true. What return True does is it allows us to collect the result of the function. So if we want to use the result of the checkCourseCode function later in the code, we can do that.
else:
print("False")
return False
else:
print("False")
return False
Here we are just saying that if the last one wasn't correct then we will print and return False. We need to do it on both lines as we have 2 if statements.
And finally, we are done! Let's try it.
input_word = input("Please select menu choice: ")
checkCourseCode(input_word)
This should result in:
Please select menu choice: COMP 123
True
Success!
I want the full code now please
courses = {
"COMP":("215", "123"),
"LASC":("215", "1712"),
"ENGN":("281", "192")
}
def checkCourseCode(input_word):
input_data = input_word.split(" ")
if len(input_data) != 2:
return False
if input_data[0] in courses:
if input_data[1] in courses[input_data[0]]:
print("True")
return True
else:
print("False")
return False
else:
print("False")
return False
input_word = input("Please select menu choice: ")
checkCourseCode(input_word)

Delete values from a list whenever the user inputs a specific thing

So let's say I have a list (it's an example, but the concept is the same):
List = ["I", "hate", "don't", "love", "you."]
How can I/Is there a way to delete multiple items from the list? I basically want the program to:
Take input from the user.
How? Whenever the user types delete x y
x and y represent the number given to the item in the list
Delete the specified items from the list whenever the person types "delete" (take it as a command. Also, it's that same delete from point #1)
Example:
#The list
List = ["I", "hate", "don't", "love", "you."]
#what the person types in the console as input
delete 2 3
Once the person inputs that and presses enter, the program will delete the 2nd and 3rd values from the list (in this case, from our human perspective, the words "hate" and "don't", since they take the second and third place respectively) And then it will print the list.
The problem is that I have no idea how to do this. Can anyone help me? I hope I was clear enough. If not, I can try to explain it in a different way.
You can try the following:
List = ["I", "hate", "don't", "love", "you."]
command, *vals = input("Enter command: ").split()
if command=='delete':
print([elem for i, elem in enumerate(List, start=1) if i not in list(map(int, vals))])
Output:
Enter command: delete 2 3
['I', 'love', 'you.']
NOTE: If one enters number greater than the length of list, it does nothing.
I hope this helps. My first time answering a question on here so let me know if this was ok and if you need any more help.
lst = ["I", "hate", "don't", "love", "you."]
Take input from the user. This will be saved in the form of a string.
We'll take your example of the user typing in delete 2 3
command = input("Enter a command")
This variable will be used to save the command, as per your step no.2
saved_command = None
The first if block executes if the first word of their command is 'delete'
and if saved_command is still None
if command.startswith("delete") and not saved_command:
# This makes the saved_command a list. It splits the
# command string where there are spaces so it becomes
# ["delete", "2", "3"]. Then, we remove 'delete' so
# it is just the numbers
saved_command = command.split().remove("delete")
This second if block executes if the command given by the user starts with
delete and saved_command is not None. This will always execute if the first
if block executes since saved_command is set in that if block
if command.startswith("delete") and saved_command:
# Loops through the numbers given. Note that with this, if the user
# passes in something which is not a number, the program will crash
for number in saved_command:
# Removes each item from the original list.
# Note that normally, items are indexed from 0 onwards
# so to have it be in the way you wanted, i.e. 1 is the first
# item, I've subtracted 1 from the number.
# int() is used because the numbers were given as user input so
# they would still be strings
try:
lst.pop(int(number) - 1)
except KeyError:
pass
Note that for the saved_command value to continue to be saved, the program would have to be run inside a loop though you probably knew that.

Best alternative to using if statement?

I am trying to break out of a bad habit of using if/else too frequently. I am new to how functions work and the proper way to call them but I am constantly researching the correct way to implement them with my code. The code that I am making is suppose to check for 3 different words and if the word is not in the input then the user will receive a statement that says "rejected" if the word is correct it will say "accepted". The issue that I am facing is getting my program to work correctly. So far I have set up my program to check each index of the word and if it matches the full word it will be marked as accepted. I am trying to figure out the correct way to add a rejected flag and to avoid the error that I recieve after running this program.
def checker():
q0 = input("enter word:")
if (q0[0]) +(q0[1]) == "if":
print ("accepted")
if (q0[0]) + (q0[1]) + (q0[2]) + q0[3] == "else":
print("accepted")
if(q0[0]) + (q0[1]) == "do":
print("accepted")
else:
print("rejected")
checker()
For this program, I am not going to use a dictionary so I can correctly challenge myself and implement this in an automata fashion. How can I implement this code without getting the string index out of range error. I tried to put break after my print statement but it doesn't work.
Thanks in advance to everyone. This is my first post so if I have made any mistakes in my post please let me know!
Here's an extensible one-liner for you:
def check():
q = input().strip()
acceptable = {'if', 'else', 'do'}
print('accepted' if q in acceptable else 'rejected')
The variable acceptable is set; a data structure which is very quick to check if something is inside of it. You can modify this set (or pass it to check as an argument!) to change the range of acceptable words without changing the control flow of the program (as you would in your original if/else implementation that you're laudably trying to move away from).
EDIT: I guess it's not strictly a 'one-liner'...
First, why do you access each character of the input string, then concatenate them again, then compare to a target string("if", "else", "do")?
Second, why do you use if statements repeatedly if matching either one of them will lead to the same result (print("accepted")?
Try this:
def checker():
q0 = input("enter word:")
if q0 in ["if", "else", "do"]:
print("accepted")
else:
print("rejected")
checker()
Now, you just compare a string q0 to another (each element of the list ["if", "else", "do"]). Also, the first hit in the list will make stop comparing anymore and will continue on to print "accepted".
++ Just to let you know why are you seeing "index out of range error", you are accessing each character of q0 without knowing how many there are. So if the user inputs a string like a, there's no q0[1] or q0[2], but you're asking your program to access it. Thus index out of range error.
You can do this with a for loop and one if statement if that is better for you. Simply put all the accepted values into a list and check if each word is in q0.
def checker():
q0 = input('enter word:')
for i in ['if', 'else', 'do']:
result = ('accepted' if i in q0 else 'rejected')
if result == 'accepted':
break
print(result)
you can do it as one liner with lambda function.
checker = lambda q: print("accepted" if q in ["elif", "if", "else"] else "rejected")
checker()
here is a sample
>>> checker = lambda q: print("accepted" if q in ["elif", "if", "else"] else
"rejected")
>>> checker("if")
accepted
>>> checker("fool")
rejected

Trying to see if values in a list exist in a mongoDB collection for a particular field

I have a list of dictionaries called listCityStateZip. One of the keys in listCityStateZip is called cityStateZip. I want to see which of the cityStateZip values exist in a MongoDB collection called zipcodes (field: citystatezip). If no match is found, then I want to flag that record in my list as "N". If a match is found, I want to flag that record in my list as "Y". I thought the code below would address my issues, but for some reason only the very first record in listCityStateZip (the list) ends up getting a flag. Code shown below. Two questions: 1) is there an easier way to write this code using python and 2) if not, why do I get a flag only in the very first record in my list?
for a in listCityStateZip:
for b in db.zipcodes.find({'citystatezip': a['cityStateZip']},{'_id':1}):
c.append(b)
if len(c) == 0:
a['flag'] = 'N'
else:
a['flag'] = 'Y'
c=[]
You can try this, much easier way
for a in listCityStateZip:
if db.zipcodes.find({'citystatezip': a['cityStateZip']}).count() > 0:
a['flag'] = 'Y'
else:
a['flag'] = 'N'

Why is my program only appending every other input into my list?

I am attempting to create a python program that takes multiple lines from the user and adds them to a list. Inputting a blank line ends the program and returns the list. However only every other line is being added to the list. If anyone could help that would be great.
def read_lines():
lines = []
contin = True
while contin:
if len(input()) == 0:
contin = False
else:
lines.append(input())
return(lines)
There is my code here is what is happening:
>>> read_lines()
abc
def
ghi
jkl
['def', 'jkl']
Because you call it twice for each iteration. You call it once for the len check, and once for the append. Each time, it extracts a new string from the command line. Consider calling it once and storing the result in a variable, at the top of your loop. Then do your len and append operations on that stored result.
The first time you call input with the if statement, it will get the input from the user. Suppose you enter a valid string, then the length will not be zero and the if block will not be executed. So, you go to else block where you again get a new input from the user; This discards the previous input that you got since you did not store it in any variable. Thus, for each valid input you give only the alternate elements are appended to the list.
Your code will append all the input you enter into the list when you alternately press enter key and a valid input in the same order.
I have added the correct code here:
def read_lines():
lines = []
contin = True
while contin:
string = input()
if len(string) == 0:
contin = False
else:
lines.append(string)
return(lines)

Categories

Resources