Multiple if conditions, without nesting - python

I have a sample piece of code below that I need some help on. The code sets the 'outcome' variable to False in the beginning and only should become True if all the 'if' conditions are met. Is there a more efficient way of doing this? I am trying to avoid nested 'if' statements.
Thanks!
outcome = False
while True:
if a != b:
print("Error - 01")
break
if a["test_1"] != "test_value":
print("Error - 02")
break
if "test_2" not in a:
print("Error - 03")
break
if a["test_3"] == "is long data string":
print("Error - 04")
break
outcome = True
break

I would write it like this, so the function ends once it encounters an error, and the most likely error should be on top, and if it encounters that error, it will return False and end the function. Else, it will check for all the other errors and then eventually conclude that the outcome is indeed True.
# testOutcome returns a boolean
outcome = testOutcome(a,b)
# Expects a and b
# Breaks out of the function call once error happens
def testOutcome(a,b):
# Most likely error goes here
if a != b:
print("Error - 01")
return False
# Followed by second most likely error
elif a["test_1"] != "test_value":
print("Error - 02")
return False
# Followed by third most likely error
elif "test_2" not in a:
print("Error - 03")
return False
# Least likely Error
elif a["test_3"] == "is long data string":
print("Error - 04")
return False
else:
return True

Or another way :
outcome = True
if a != b:
print("Error - 01")
outcome &= False
if a["test_1"] != "test_value":
print("Error - 02")
outcome &= False
if "test_2" not in a:
print("Error - 03")
outcome &= False
if a["test_3"] == "is long data string":
print("Error - 04")
outcome &= False

Hackiest way of doing this as per user request, not recommended tho,
There are many ways to use structures if you are only looking to understand them.
Functions like zip or list comprehension can be used once you convert to list
Used list to keep positions intact.
a = {'test_1' : "test_value", 'test_4' : "None", 'test_3' : "long data string"}
b = {'test_1' : "test_value", 'test_4' : "None", 'test_3' : "long data string"}
# storing bool values, expecting True
test1 = [a==b,"test_2" in a,a["test_1"] == "test_value", a["test_3"] != "is long data string" ]
# storing error codes for False conditions
result = ["Error - 01", "Error - 02", "Error - 03", "Error - 04"]
if False in test1:
print(result[int(test1.index(False))])
else:
print(True)
Error - 02
[Program finished]

Related

binary search for list in python

My code for binary search function in a list returns true for a value in the list, but returns None (instead of false) for values not in the list.
Can someone please explain me what I'm doing wrong?
The program is:
def searchlist(x,alist):
end=int(len(alist)-1)
mid=int(len(alist)/2)
while len(alist)>2:
if x==alist[mid] or x==alist[0] or x==alist[end] :
return("true")
break
elif x>alist[mid]:
alist=alist[mid:]
mid=int(len(alist)/2)
end=int(len(alist)-1)
elif x<alist[mid]:
alist=alist[:mid]
mid=int(len(alist)/2)
end=int(len(alist)-1)
else:
return("false")
aList=[2,3,5,7,9,12,14,23,34,45,67,89,101]
xnum=int(input("enter a number:"))
searchlist(xnum,aList)
print(searchlist(xnum,aList))
You get None when your function does not return a value. This happens because the while loop terminates without going into the "else" branch.
A better practice would be to return True (not the string, but the Boolean value) when you find the value in the list, and return False after the loop.
Your while loop cannot catch the else statement. you don't need that else. try this :
def searchlist(x,alist):
end=int(len(alist)-1)
mid=int(len(alist)/2)
result = False
while len(alist)>2:
if x==alist[mid] or x==alist[0] or x==alist[end] :
result = True
elif x>alist[mid]:
alist=alist[mid:]
mid=int(len(alist)/2)
end=int(len(alist)-1)
elif x<alist[mid]:
alist=alist[:mid]
mid=int(len(alist)/2)
end=int(len(alist)-1)
return result
aList=[2,3,5,7,5,67,89,101]
xnum=int(input("enter a number:"))
print(searchlist(xnum,aList))

How to exit a while loop when the input or variable in a user-defined function meets the condition in Python [duplicate]

This question already has answers here:
How to break out of while loop in Python?
(5 answers)
Closed 4 years ago.
I'm trying to use a while loop to iterate through a function in Python which requests a user input, i.e. commitchanges to perform one of two actions, and if the input is not valid after a few attempts to close the program.
If the input is equal to 'y' (Yes) then the program should commit the changes made by the SQL update query, i.e. conn.commit()
If the input is equal to 'n' (No) then the program should not commit the changes and rollback, i.e. conn.rollback()
If the input is anything other than 'y' or 'n' then the program should alert the user that that is not a valid input.
Here's my current function:
def action(inputattempts):
commitchanges = input()
if commitchanges.lower() == 'y':
try:
conn.commit()
print ('Table Updated. No. of records updated:', totalupdates)
except cx_Oracle.DatabaseError as error:
print(error)
elif commitchanges.lower() == 'n':
conn.rollback()
print ('Rollback - No updates made to table')
else:
print ('Not a valid selection - Try again')
print (inputattempts)
Where the variable totalupdates is a global variable defined later on in the program which counts the number of records affected by the curs.execute SQL query.
I'm then calling the above function in a while loop as follows:
inputattempts = 0
while (inputattempts < 4):
inputattempts += 1
action(inputattempts)
print ('FAILED')
Essentially, I'd like the user to have a maximum of 4 attempts at entering a valid input, i.e. 'y' or 'n' before the program aborts if the input is not valid after those attempts. However, if 'y' or 'n' is entered the first time the function is called the program should either commit or rollback and exit the loop.
Currently, I'm having to complete 4 iterations of the while loop regardless of my input. Is there a way I can tweak any of that syntax to exit the loop when the above conditions are met?
As suggested by #rdimaio:
Your action function returns True if the flow was valid; False otherwise (i.e. invalid user input).
def action(inputattempts):
commitchanges = input()
if commitchanges.lower() == 'y':
try:
conn.commit()
print ('Table Updated. No. of records updated:', totalupdates)
except cx_Oracle.DatabaseError as error:
print(error)
return True
elif commitchanges.lower() == 'n':
conn.rollback()
print ('Rollback - No updates made to table')
return True
print ('Not a valid selection - Try again')
print (inputattempts)
return False
Then, you check whether the flow was valid in your while and break when condition is met:
input_attempts = 0
while input_attempts < 4:
input_attempts += 1
if action(input_attempts):
break
if input_attempts == 4:
print ('FAILED')
Just get the user input outside of actions() and pass it as a parameter:
while inputattempts < 4:
inputattempts += 1
commit_changes = input()
action(inputattempts, commit_changes)
Then after the call to action() you can condition on what you need and break out if appropriate.
You can return a value from your function and check over it's returned value to break or not.
def action(inputattempts):
correct_input = True
commitchanges = input()
if commitchanges.lower() == 'y':
try:
conn.commit()
print ('Table Updated. No. of records updated:', totalupdates)
except cx_Oracle.DatabaseError as error:
print(error)
elif commitchanges.lower() == 'n':
conn.rollback()
print ('Rollback - No updates made to table')
else:
print ('Not a valid selection - Try again')
print (inputattempts)
correct_input = False
return correct_input
then change your while loop to break the loop when
inputattempts = 0
while (inputattempts < 4):
inputattempts += 1
if action(inputattempts):
break
print ('FAILED')
Have your function return a flag telling whether or not the input was accepted:
def action(inputattempts):
commitchanges = input()
if commitchanges.lower() == 'y':
try:
conn.commit()
print ('Table Updated. No. of records updated:', totalupdates)
return True # <-- New
except cx_Oracle.DatabaseError as error:
print(error)
elif commitchanges.lower() == 'n':
conn.rollback()
print ('Rollback - No updates made to table')
return True # <-- New
else:
print ('Not a valid selection - Try again')
print (inputattempts)
return False # <-- New
Now in your loop, you can do
inputattempts = 0
while (inputattempts < 4):
inputattempts += 1
if action(inputattempts):
break
print ('FAILED')
where the break simply exists the loop. Also, I imagine that the print of 'FAILED' should only occur if the loop is exited after the 4 attempts, not if the break was reached. This can be achieved using else. Finally, your while loop really only counts, and so a for loop is more appropriate. Consider
for inputattempts in range(4):
if action(inputattempts):
break
else:
print ('FAILED')

How to make it run through my whole range?

def isprimelike(n):
for a in range(2,n-1):
if pow(a,n,n) == a%n:
return True
else:
return False
When I check n for a given value it just check 2, then decides if it is true or false and doesn't check the rest of the range. Not sure how to make it check the rest of the range.
That's because you're using a return inside the if-else block. You might want to change the return statement by a print one indicating if it is a prime number or not.
If you want it to return True if all are prime-like or False if at least one is not, then do the following:
def isprimelike(n):
for a in range(2,n-1):
if pow(a,n,n) != a%n:
print('One element is false')
return False
return True
The print statement is just to show something, but it's not relevant.
I would try making a list and allow your for loop to append the results of the range into the list then return the list as a whole so you can have access to all the results.
edit: Complely missed the point of your question. Here's the edit.
import sys
def isprimelike(n):
resultlist = []
for a in range(2,int(n)-1):
if pow(a,int(n),int(n)) == a%int(n):
result.append(True)
else:
result.append(False)
return resultlist
n = sys.argv[1]
resultlist = isprimelike(n)
if True in resultlist:
if False in resultlist:
print('List contains both True and False')
sys.exit(1)
else:
print('List is all True')
sys.exit(1)
if False in resultlist:
if True in resultlist:
print('List contains both True and False')
else:
print('List is all False')

handling if statement in python

following is the example of the code:
if test = "true":
print "hello"
elif test = "false":
pass
else:
print "Error"
In above code if test = "false" ,it will print "Error", but i want code to print nothing if test = "false" and exit
I tried with "continue" instead of "pass" , still the same. Can any one help me.
Thanks in Advance.
You are not comparing values but assigning them in your code.
Use '==' to compare values. Using single "=" will return in assigning a value, and it will be a syntax error when using with if
Assuming that test is a string.
So instead of :
if test = "true":
print "hello"
elif test = "false":
pass
else:
print "Error"
Do this:
if test == "true":
print "hello"
elif test == "false":
pass
else:
print "Error"
If test is a boolean, use:-
if test == True:
Or better simply:
if test:

use statement True and False in Python 2.7

i wish to use a statement "True" and "False" for my Python (2.7) command prompt
segmentation_accuracy(reference=REFERENCE, segmented=SEGMENTED, output=OUTPUT, method=METHOD, threshold=THRESHOLD, sep=SEP, header=HEADER)
if header is True print a text file with an header, if header is False print a text file without an header.
in Command Prompt:
REFERENCE = raw_input("Reference (*.shp):")
SEGMENTED = raw_input("Segmented (*.shp):")
METHOD = raw_input("Method (ke, pu, clinton):")
if METHOD != "ke" and METHOD != "pu" and METHOD != "clinton":
raise ValueError("%s is not a valid method" % METHOD)
if METHOD == "ke" or METHOD == "clinton":
THRESHOLD = input("Threshold (0.0 - 1.0):")
if not check_threshold(THRESHOLD):
raise AccuracyException("Threshold of %s is not valid" % THRESHOLD)
else:
THRESHOLD = None
SEP = raw_input("Sep:")
HEADER = raw_input("Header (True/False):")
if HEADER is not True or HEADER is not False:
raise ValueError("%s is not valid" % HEADER)
# output
OUTPUT = raw_input("Output (*.txt):")
when i run the command prompt in windows if i set raw_input("Header (True/False):") True or False, I always get the ValueError
i also used the combination
if HEADER != True or HEADER != False:
raise ValueError("%s is not valid" % HEADER)
with the same problem
The return value from raw_input is a string and not a boolean. Hence your is not True and is not False tests, although they have well-defined meaning, that meaning is not the meaning that you intend. You need to compare HEADER against string values.
So you would need, for example, code like this:
if HEADER.lower() == 'true':
I used tolower() to effect case-insensitive comparison. You may also want to strip off white space:
if HEADER.strip().lower() == 'true':
I'm sure you can fill in the test against false yourself.
Even if you did have a boolean, you should not use code like is not True or is False. You should test for truth with:
if somebool:
or
if not somebool:
because it is much more readable.
HEADER is a string, not a boolean. This will cause the is check to fail. Your comparison runs like this:
>>> "True" is not True
True
>>> "True" is not False
True
Note that a comparison with == will also fail:
>>> "True" == True
False
>>> "True" == False
False
Try comparing the value as a string:
if HEADER.tolower() == 'true':
#do something
elif HEADER.tolower() == 'false:
#do something else

Categories