handling if statement in python - 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:

Related

How to continue the program even after evaluating the condition to true in if else loop in python?

I am implementing the scenario in which i have multiple if,elif,else loops.My problem is when the condition met ,its coming out of the program and exits the program .
Expected Behavior - After successful completion it should not exit but rather again show me the options to select .Only after pressing something like cntrl+c it should exit out the program.
class Manager:
def __init__(self):
self.not_useful_tests = []
self.sdsf
def sdsf(self):
try:
input = raw_input()
if input == 'x':
self.not_useful_tests.append(0)
else:
if input == 1:
verify = self.ABC()
return verify
if input == 2:
verify = self.xyz()
return verify
if input == 3:
verify = self.hyg()
return verify
if input == 4:
verify = self.fgh()
return verify
if input == 5:
verify = self.qwe()
return verify
except KeyboardInterrupt as e:
print "Exception caught : " + str(e)
return None
How to achieve this beahvior ? What to add in the code so as to achieve the task ?
To repeat something while some condition is true, use a while loop:
while True:
input = raw_input()
if input == 1:
return 'some value'
if input == 2:
return 'some other value'
If you don't want to return a function result, but rather want to continue execution outside of the loop, i.e. 'break out of the loop' use break:
while True:
input = raw_input()
if input == 1
print('doing something')
break
if input == 2
print('doing something else')
break
print('Continuing here')
And if that's what you want, you can also set a condition to end the loop like this:
result = None
while result is None:
input = raw_input()
if input == 1:
result = 'x'
if input == 2:
result = 'y'
print('will continue here if result has a value')

python if evaluating True for False value

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!"

How to return a boolean value and print a message in python

for example, I want to return a Boolean value False and print a message ("It did not pass the test") at same time in python, how to do that?
Are you looking for this?
def this_returns_false(<arguments>):
"""
Do stuff here
"""
return False
if not this_returns_false(<args>): # not accesses the function for False statement now
print "It did not pass the test"
a possible shorthand:
print "It did not pass the test" if not this_returns_false else ""
OP's code:
def password_check(password):
upper_letter = str.upper(lower_letter)
if ((count_digit(password) == 0) or (count_Lletter(password) == 0) or (count_Uletter(password) == 0)):
return False and print("it did not pass the test")
Edit after OP's code:
def password_check(password):
upper_letter = str.upper(lower_letter)
if (not count_digit(password)) or (not count_Lletter(password)) or (not count_Uletter(password)):
# not is the same as !
print("it did not pass the test")
return False
The print statement is executed before the return statement here btw.

Python if( ): vs if:

On Code Academy there is this course where in the example they show
def speak(message):
return message
if happy():
speak("I'm happy!")
elif sad():
speak("I'm sad.")
else:
speak("I don't know what I'm feeling.")
The above example will NOT be related to the rest of the code I show. That was just an example for the if statement. Now I was under the impression that when ever writing an if statement it had to end in an ():like the above example.
However when doing the assignments this does not work:
def shut_down(s):
if s == "yes"():
return "Shutting down"
elif s == "no"():
return "Shutdown aborted"
else:
return "Sorry"
However this works:
def shut_down(s):
if s == "yes":
return "Shutting down"
elif s == "no":
return "Shutdown aborted"
else:
return "Sorry"
My question is how come the () is not needed next to the "yes" and "no" but :is still needed. I thought whenever writing an if statement it will automatically have to end with ():. In that very first example, that's how it is shown. Do you understand my confusion.
In the example given, happy() and sad() are functions, and as such require parentheses. The if itself does not need parentheses at the end (and it shouldn't have them)
No, if has nothing to do with ()
happy is a function. happy() is a call to that function. So, if happy(): tests if the happy function returns true when called.
In other words, if happy(): speak("I'm happy!") is equivalent to
result_of_happy = happy()
if result_of_happy:
speak("I'm happy!")
As has been mentioned happy() / sad() are functions so they require (). In example two of your question you are comparing your value to the string "yes" because it is a string it does not require ().
Within an if statement you can use parentheses to make the code more readable and ensure certain operations are evaluated before others.
if (1+1)*2 == 4:
print 'here'
else:
print 'there'
Differs from:
if 1+1*2 == 4:
print 'here'
else:
print 'there'
Because string objects are not callable so what are you expecting then:
Then use lambda not that efficient tho:
def shut_down(s):
if (lambda: s == "yes")():
return "Shutting down"
elif (lambda: s == "no")():
return "Shutdown aborted"
else:
return "Sorry"

Unable to execute the else part of an if statment when conditon does not match in python

When the Condition matches, It is printing the proper output as expected. But when the condition does not match the "if not found" part is not working.
here If condition checks the username and password both. If it satisfies, It executes the code below it, But when It does not match, It displays blank , I mean there is no Invalid Login printed , though It should get printed
passwd = {}
actual_user = {}
found = False
for row in prsnobj.result:
actual_user[row[0]] = row[1]
for i in range(1, 100):
passwd[row[0]] = row[2]
for i in range(1, 100):
if login == actual_user[i] and password == passwd[i]:
found = True
print "WELCOME !!"
if not found:
print "<h4>Invalid Login</h4>"
You can write this without a flag, using for/else:
for u, p in zip(actual_user.values(), passwd.values()):
if login == u and password == p:
print "WELCOME !!"
break
else:
print "<h4>Invalid Login</h4>"
But it may be better to use a dictionary:
logindb = {row[1]:row[2] for row in prsnobj.result}
if login in logindb and logindb[login] == password:
print "WELCOME !!"
else:
print "<h4>Invalid Login</h4>"
The relevant part of your code could be more simple expressed as this:
if a == 1:
found = True
if not found:
print "not found"
The problem with this is that you never set found to false. Even if a is not equal to 1, found is still true from the last time you found something.
So the solution is something like this:
found = False
if a == 1:
found = True
if not found:
print "not found"
for row in prsnobj.result:
logindb = {row[1]:row[2]}
#print logindb
if login in logindb and logindb[login] == password:
print "Welcome"
break
else:
print "Invalid"
break

Categories