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
Related
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]
I have the following object field:
is_vendor = models.BooleanField(default=False)
I have the following if statement:
print(customer.is_vendor) //This prints False
if customer.is_vendor:
print('im a vendor') //This prints even the value above is false
else:
print('im not a vendor')
Why is this occurring?
You have a string in the field -- "False" as opposed to False. Which is cool for Django but not python. Try customer.is_vendor.to_python() instead. That will wrangle it into a boolean for you.
if "False": print 'True!' # is True
if False: print 'True!' # Nope.
if customer.is_vendor.to_python():
print "Is a vendor!"
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')
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:
I am supposed to write a script with the following criteria:
Write a function called validatePassword that takes a password string as a parameter and returns true or false. The function should only return true if:
The password is at least 8 characters
The password contains at least one number
The password contains at least one upper case letter. Hint: use the isupper() string function.
The password contains a symbol one of the symbols !##$%^&*()+=
I have this so far:
def validatePassword(pswd):
if len(pswd)> 8:
return True
else:
return False
for char in pswd:
if char in '01234567890':
return True
else:
return False
for char in pswd:
if char in '!##$%^&*()_+=':
return True
else:
return False
for char in pswd:
if char.isupper and char .islower:
return True
else:
return False
return True
while False:
print("There was an error with your password")
print (validatePassword(Herseuclds))
I know that print (validatePassword(Herseuclds)) has a syntax error because I am missing the variable but I just don't get how to do this.
def validatePassword(pswd):
if len(pswd) < 8:
return False
number_in_password = False
for char in pswd:
if char in '012356789':
number_in_password = True
if not number_in_password:
return False
symbol_in_password = False
for char in pswd:
if char in '!##$%^&*()_+=':
symbol_in_password = True
if not symbol_in_password:
return False
uppercase_in_password = False
for char in pswd:
if char.isupper():
uppercase_in_password = True
if not uppercase_in_password:
return False
#this only happens if nothing above has disqualified the password
return True
print (validatePassword("herseuc"))
print (validatePassword("herseuclds"))
print (validatePassword("herseuclds!"))
print (validatePassword("herseuclds!123"))
print (validatePassword("herseuclds!123A"))
The main issue with your code is in the last line.
print (validatePassword(Herseuclds))
Right now, the interpreter thinks Herseuclds is a variable, and not a string. If Herseuclds is the password, and not a variable describing the password, then you need quotes around it to make it a string literal.
print (validatePassword("Herseuclds"))
You obviously haven't defined a variable called Herseuclds anywhere in your program, but the program thinks Herseuclds is a variable and not a string, so it throws the error.
Best of luck, and happy coding!
First issue is that you are passing an undeclared variable to your function. See silentphoenix's answer for details.
Secondly, your program only check to see if AT LEAST ONE condition is met, not all.
If a password is 8 characters long, it will return true even if the password doesn't satisfy the other requirements.
I am not going to write your code for you, but I can pseudocode the issue:
def validatePassword(pswd):
if len(pswd) < 8:
return False
# if there isn't a number:
return False
# if there isn't a symbol:
return False
# if there isn't an upper and lowercase:
return False
return True
while True:
print("There was an error with your password")
print (validatePassword("Herseuclds"))
sidenote: watch your indentation :)
Since you can use is.upper() you can also utilize is.digit() to check for numbers instead of having to write down actual digits.
Another thing to speed it up, since they all have to be done at the same time, you can check if the password validates those requirements in one line with any()
def validatePassword(pswd):
l = []
if len(pswd)> 8:
for char in pswd:
l.append(char)
if any(l for x in l if x.isdigit()) and any(l for x in l if x.isupper()) and any(l for x in l if x in '!##$%^&*()_+='):
print('Success')
else:
print('Try again')
while True:
a = input('What is your password?')
validatePassword(a)
At the beginning there's an minimum check to see if the lengeth is greater than 8. If it is, the word gets broken up into a list. This allows any() to be used and checked against the remainding requirements.
def valid_password(password):
return (
# The password is at least 8 characters
len(password) >= 8 and
# The password contains at least one number
any(c in "0123456789" for c in password) and
# The password contains at least one upper case letter
any(c.isupper() for c in password) and
# The password contains a symbol one of the symbols !##$%^&*()+=
any(c in "!##$%^&*()+=" for c in password))
Example:
from getpass import getpass
while not valid_password(getpass('Enter password: ')):
print('invalid password. Try again')