Script ignores conditions (if, elif, & else) [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)
Closed 2 years ago.
I got to write a script which replaces certain things in a .txt file with a specific variables from input() and then it should create a new .txt with exact same content except the things replaced.
I have a few conditions:
Which compares line content from original .txt with a specific strings and if it's equal, it then replaces the string with replaced one and writes this new string to a new .txt file.
Basically, I must copy\paste original file with a few touches. But when it comes to the test stage, the whole config would be rewritten with only first condition stated in the build_config() function. And If you run my script, you would see that the LACP condition is not working at all, it writes the content in whichever way, when it should only write it if the LACP variable equals to "y".
What's going on? Here is my code:
def build_config():
base_config = open("MES2428B.txt", 'r')
for line in base_config:
complete_config = open(location + ".txt", 'a')
complete_config.write(line)
line.replace("location", "location"+location)
complete_config.close()
base_config.close()
if lacp == "y" or "Y" or "Н" or "н" :
base_config = open("MES2428B_lacp.txt", 'r')
for line in base_config:
complete_config = open(location + ".txt", 'a')
complete_config.write(line)
base_config.close()
complete_config.close()
print("LOCATION:")
location = input()
print("VLAN:")
vlan = input()
print("Adress:")
ip = input()
print("LACP NEEDED? y/n")
lacp = input()
print("COM SPEED:")
COMspeed = input()
print("LOCATION: " + location + "\nVLAN: " + vlan + "\nIP: " + ip)
print("IS EVERYTHING RIGHT? y/n")
while True:
check = input()
if check == "y" or "Y" or "Н" or "н":
build_config()
print("Done, check it!")
input()
break
elif check == "n" or "N" or "т" or "Т":
print("What would you like to change? /n 1 - Локация /n 2 - VLAN /n 3 - IP /n 4 - COM Скорость /n 5 - nothing")
check = input()
if check == 1:
location = input()
elif check == 2:
vlan = input()
elif check == 3:
ip = input()
elif check == 4:
COMspeed = input()
elif check == 5:
print('Then why you press it!?')
build_config()
print("Done! Check it!")
input()
break
elif True:
print("Your input is garbage, try again")
'''

Welcome to SO.
Where you have if check == "y" or "Y" or "Н" or "н":, you want if check.lower() in ('y', 'h'):

The or operator takes two boolean values and returns a boolean value.
This expression:
lacp == 'y' or 'Y'
would be evaluated as follows:
Evaluate lacp == 'y'.
If it is true, the whole expression returns true.
Otherwise, evaluate 'Y' as a boolean value and return that. Any non-zero, non-empty value is coerced to true. So your expression returns true.
The proper general way to incorporate multiple comparisons would be:
(lacp == 'y') or (lacp == 'Y')
The parentheses should not be necessary here, but I think it is a good habit to use them to make the order of evaluation clear.
For specific cases such as yours, there might be other reasonable ways to do your test, as shown in another answer.

Related

How come my if else statement isn't executing properly

a = input("enter your first name ")
for i in range(len(a)):
for space in range(len(a)-i):
print(end=' '*len(a))
for j in range(2*i+1):
print(a,end = '')
print()
print()
if a == 'Allahyar' or 'allahyar':
print(a+ ' is a boomer')
elif a != 'Allahyar' or 'allahyar':
print(a+' has been sent to the pyramid realm')
in this code the if statement executes no matter what and it completely ignores the elif statement. any idea why?
Correct syntax to combine two conditions using logical or operator.
if var == "str1" or var == "str2":
You can also do it like this
if var in ["str1","str2"]:
I'll expand on my comment. The reason you're getting the if condition always triggering is because you think that what you coded should equate to: "variable a is equal to either 'Allahyar' or 'allahyar'" but in reality it will get evaluated as two separate statements like so (brackets added for clarity):
(a == 'Allahyar') or (bool('allahyar'))
A non-empty string 'allahyar' will always evaluate to True so it's impossible for this combined expression to be False.
as #pavel stated the correct code is 𝐚 == '𝐀𝐥𝐥𝐚𝐡𝐲𝐚𝐫' 𝐨𝐫 𝐚 == '𝐚𝐥𝐥𝐚𝐡𝐲𝐚𝐫' I just got confused so I made an elif statement but the actual code was this a = input("enter your first name ")
for i in range(len(a)):
for space in range(len(a)-i):
print(end=' '*len(a))
for j in range(2*i+1):
print(a,end = '')
print()
print()
if a == 'Allahyar' or a == 'allahyar':
print(a+ ' is a boomer')
else:
print(a+' has been sent to the pyramid realm')
there is no reason for the elif statement its just extra code to write for no reason.

Why won't the while loop continue and stop after a user question? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
questionnumber=0
color=("Red")
userask=input("What color of the rainbow am I thinking of? ")
color = userask
if color == "Red":
print("CORRECT")
else:
print("INCORRECT")
questionnumber = questionnumber+1
#print(questionnumber)
while color != "Red":
userask=input("What color of the rainbow am I thinking of? ")
color = userask
if color == "Red":
print("CORRECT")
else:
print("INCORRECT")
questionnumber = questionnumber+1
#print (questionnumber)
if questionnumber>3:
quitter=input("Do you want to quit? ")
if quitter == "yes"or"Yes":
break
else:
continue
So the idea is you have to guess the correct color which in this case is red. But after three attempts, the program asks the user if they want to quit; if yes, the while loop stops, and if no, the while loop continues for another three attempts. I can't seem to figure out why the loop ends regardless of the user's answer.
Your problem is that:
if quitter == "yes"or"Yes"
is based on a misunderstanding of Python logic statements.
It is not interpreted as if quitter == ("yes"or"Yes") as you intended, but it is actually interpreted as:
if (quitter == "yes") or ("Yes")
Any non-blank string evaluates to True, so the break is always executed.
A better way of writing this would be:
if quitter.lower() == "yes":
This converts the contents of quitter to lower case and checks that, so you don't need to check upper and lower case, and other variants like "YES".
Please change this statement to as below :
if ((quitter == "yes") or (quitter == "Yes")):
After prompting the user if they want to quit, change the if statement to
if quitter == "yes" or quitter == "Yes":
break
else:
continue
The reason the program exits is because it's evaluating the string 'Yes' on it's own as True which means the or statement evaluates as True and thus break is ran. You have to specify quitter both before and after the or statement.
truth_val = bool('Yes')
print(truth_val)
>>>True

Python: while (True != True) loop

I started learning to code this week so I'm playing around with small programs that I'm creating to try to get a better understanding of how it work.
One of the programs I made is a Pig Latin translator that loops until the user exits. The program works but the logic isn't making any sense to me.
pyg = "ay" #Pig Latin words end with ay.
def translate(): #Creating a function.
original = input("Enter a word: ").lower() #Ask for input then convert to lower.
if len(original) > 0 and original.isalpha() : #isalpha() verifies only abc's and more than one letter.
first = original[0] #Assigns the first letter of the string to first.
latin = original[1:] + first + pyg #Adds original starting at 2nd letter with first and pyg.
print(latin)
else:
print("You did not enter a valid word, please try again.")
translate() #If you did not enter valid word, then call function again until you do.
translate() #Don't forget to actually call the function after you define it.
#Set run to False.
#Can be set to True if while (run != True) is set to while (run == True).
run = False
#Defining cont(). Ask for imput and error handling.
def cont():
loop = input("Would you like to convert another word? (y/n): ").lower()
if loop == "y" :
run = True
elif loop == "n" :
run = False
print("Thank you for using this program, have a nice day!")
exit()
else :
print("You did not enter a valid response, please try again.")
cont()
cont()
#Infinite loop as long as run is not equal to True.
while (run != True) :
translate()
cont()
My question is, why does this program work? I set run to False and I set the loop to run as long as run != True. No problem there, however when I defined cont(), I set run to take on the value True if the user inputs "y". True != True should be False (if I understand correctly) and the loop should end, but instead it is working as I wanted it to.
Is this a coding mistake that I've made or am I just thinking about this the wrong way? Thank you in advance.
Edit: Thank you very much to everyone that answered. I hadn't learned about local and global variables yet.
To expand on what others have already stated, run on these lines
if loop == "y" :
run = True
elif loop == "n" :
run = False
are not referring to the same run defined by
#Can be set to True if while (run != True) is set to while (run == True).
run = False
run in the cont function is a local variable to your function, not the globaly defined run.
There are a couple (at least) ways to fix this. The preferred (imo) way to do it is have cont return a new value to be assigned to run. That would look like
#Defining cont(). Ask for imput and error handling.
def cont(_run):
loop = input("Would you like to convert another word? (y/n): ").lower()
if loop == "y" :
return _run
elif loop == "n" :
return not _run
else :
print("You did not enter a valid response, please try again.")
return cont(_run)
...
#Infinite loop as long as run is not equal to True.
while (run != True) :
translate()
run = cont(run)
The other (less preferred) way would be to use the global run variable inside of your cont function. This is achieved using the global keyword.
That would look like this:
#Defining cont(). Ask for imput and error handling.
def cont():
global run
loop = input("Would you like to convert another word? (y/n): ").lower()
if loop == "y" :
run = True
elif loop == "n" :
run = False
print("Thank you for using this program, have a nice day!")
exit()
else :
print("You did not enter a valid response, please try again.")
cont()
** Couple side notes
In my first example I return _run when the value is y and not _run when the value is n. This allows you to change you initial run value to be True, and change the while condition without having to change the cont function itself.
You don't need to actually change the run value at all if you use the global and the user enters n since you exit before the function returns.
You might be better off changing your if conditional checks to
if loop in ("yes", "y"):
if loop in ("no", "n"):
since lots of people don't read full instructions :)
The run inside the cont function is a local variable. Changing its value has no effect on the global variable that the while loop refers to.
I think this is probably because of the scope of your run variable; because you're not returning run from your cont function. I believe what your != True check sees is always going to be False outside of that function, though obviously you can successfully end the program within the function.
The problem is that the run variable defined in cont() is not the same as the run variable defined in the global scope. (If you aren't sure what I mean by that you might want to look at https://docs.python.org/3.4/tutorial/classes.html#python-scopes-and-namespaces. Perhaps a better approach for your code would be to have cont() return True or False. It is also more intuitive and readable to use True for when you want to continue. Here's how I would rewrite it.
pyg = "ay" #Pig Latin words end with ay.
def translate(): #Creating a function.
original = input("Enter a word: ").lower() #Ask for input then convert to lower.
if len(original) > 0 and original.isalpha() : #isalpha() verifies only abc's and more than one letter.
first = original[0] #Assigns the first letter of the string to first.
latin = original[1:] + first + pyg #Adds original starting at 2nd letter with first and pyg.
print(latin)
else:
print("You did not enter a valid word, please try again.")
translate() #If you did not enter valid word, then call function again until you do.
#Defining cont(). Ask for imput and error handling.
def cont():
while True:
loop = input("Would you like to convert another word? (y/n): ").lower()
if loop == "y":
return True
elif loop == "n":
print("Thank you for using this program, have a nice day!")
return False
else :
print("You did not enter a valid response, please try again.")
translate()
while cont():
translate()

Python, While Loop Not Functioning Properly

The while loop correctly stops when "no" is entered first for the "would you like to continue" question. When "no" is entered after "yes" or after several "yes" entries, then the user must answer "no" for however many "yes" entries came before it: e.g. "yes", "yes", "no" will produce two "would you like to continue" questions after the first "no" answer.
I am just beginning to learn Python, so any suggestions would be helpful.
Thank you.
def testing3():
def Grade(score):
if score >= 90:
letter = "A"
elif score >= 80:
letter = "B"
elif score >= 70:
letter = "C"
elif score >= 60:
letter = "D"
else:
letter = "F"
print(letter)
def main():
x = input("Enter Numerical Grade: ")
numGrade = int(x)
Grade(numGrade)
main()
def main2():
while True:
test = input("Would you like to continue?: ")
if test == 'Yes':
testing3()
else:
print("Done")
break
main2()
testing3()
Your testing3 call invokes the inner main2 def, but main2 invokes the testing3 def so you are ping-ponging between the two.
To get a sense of this you should look at your stack-frames and you should see a frame for testing3 followed by testing2 followed by testing3 etc for how ever many times you have entered yes.
Whether or not you meant to (I don't think you did) you created a recursive function. So the reason you are having to enter no multiple times is as you unwind up (popping frames off the stack)
The proper use of the while loop should something like:
finish = False
while not finish:
# do your stuff here
finish = evaluateLoopFinish()
Here, finish is a signal flag which you must evaluate at the end of each turn. The first time is set at False, so not False == True, hence enters the loop.
Another tip: use only one main like this
def main(args):
# do your stuff here
if __name__=="__main__":
main()
Every Python script has a name special variable which holds the name of the module except for the script which was given to Python to be executed which receives the special value main.

How come my program does not quit? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 9 years ago.
Alright, so I've tried this for a while now and I can't seem to find a way to close the program once it is running.
What I want it to do is to end the program if the user chooses 'no':
elif y == 'n' or 'no':
sys.exit(0)
However whatever I choose returns the program to the partOne function. I've tried different things to try and solve this, such as moving
partOne()
from the end of the program to in between the two functions but that does not work because then the PartTwo function has yet to be defined.
Thanks for your response.
import hashlib
import sys
def partOne():
x = input("\nEnter something to hash: ")
hash_object = hashlib.sha256(x.encode())
hex_dig = hash_object.hexdigest()
print("\nPlain text: ")
print(x)
print("\nHashed text: ")
print(hex_dig)
print("\nYour password: ")
print(hex_dig[::9])
partTwo()
def partTwo():
y = input("\nDo you want to make another password? (y/n): ")
if y == 'y' or 'yes':
partOne()
elif y == 'n' or 'no':
sys.exit(0)
else:
print("\nYou need to type either 'y' or 'n'.")
partOne()
partOne()
Try y == 'n' or y =='no'
instead of y == 'n' or 'no'
>>> y = 'anything'
>>>
>>> bool(y == 'n' or 'no')
True
your statement always returns True. Instead of checking y == 'no' it just checks 'no', anything converted to bool in python is True if its not None, False, or 0.
In case of strings and other iterables it returns True if its not empty, e.g. '', [], {}, () will always return False.
Or as Foo Bar User says, if y.lower() in ('n', 'no') will also do. lower() will make sure that the matching is case insensitive.

Categories

Resources