Python if statement to compare to a string not working
Question:
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)
Answers:
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. Instead, do it like this:
if New != "Next" or 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 🙂
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. Instead, do it like this:
if New != "Next" or 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 🙂