python if statement always returns false

  • Last Update :
  • Techknowledgy :

PS: the variables i, v and c should have better names.

line = 'if __name__=="__main__": print("Hello!")'
v = line[3: ] # Remove "if "
from the line, so you only have the question and the consequence
i = v.split(': ') # Make a list with the first item being the question and the second item being the consequence.

c = i[1]
question = i[0]
consequences = c.split(' | ')

_consequences = ''
for x in consequences:
   _consequences += f '\n{x}'
Answer = eval(f "{question}") # Check
if the question is true or false

if Answer == True:
   exec(_consequences)
print("True!")
else:
   print("False!") # Finally check
if the question is true or not and
if it is, print "True!"
and
if it 's not, print "False!"

Suggestion : 2

Hi! I'm trying to use OR in my IF statement to try to make it more user friendly. For some reason it always comes back true, no matter what I write. What I mean is that my IF statement always runs no matter what I write with this code. Whats the problem?,Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today. ,Python will let you get away with using strings and numbers with logical operators e.g. and, or, not -- these are syntactically correct and there are some programming tricks you can do with these, though I don't necessarily recommend. I will demonstrate below.,Maybe try making sure your indentations are correctly aligned. That is to say 4 spaces every time indentation is required. Python can be strict about it and can cause disruption to program flow.

>>> proceed = 'Yes' >>>
   proceed.lower() == "y"
or "yes"
'yes' >>>
proceed = 'No' >>>
   proceed.lower() == "y"
or "yes"
'yes'
>>> proceed = 'Yes' >>>
   proceed.lower() == 'y'
or proceed.lower() == 'yes' >>>
   True >>>
   proceed = 'No' >>>
   proceed.lower() == 'y'
or proceed.lower() == 'yes' >>>
   False
>>> proceed = 'Yes' >>>
   proceed.lower() in ['y', 'yes']
True
   >>>
   proceed = 'NO' >>>
   proceed.lower() in ['y', 'yes']
False
proceed = input("{}, would you like to proceed in this purchase?\nY/N ".format(user_name))

if proceed.lower() in ["y", "yes"]:
   print("Thank you for your purchase {}".format(user_name))
tickets_remaining -= how_many_tickets

else:
   print("Thanks {}, have a nice day!".format(user_name))
>>> # the "or"
operator short - circuits since LEFT side is truthy >>>
   # since "yes"
is truthy,
return the LEFT string!
   >>>
   "yes"
or "no"
'yes' >>>
# note that this works with 'no'
too. >>>
   "no"
or "yes"
'no' >>>
True or "I am Truthy too, but short-circuit gives LEFT expression"
True
   >>>
   # since there is not a short - circuit,
   return RIGHT truthy expression >>>
      False or "I can say I am False, but I am truthy"
'I can say I am False, but I am truthy' >>>
# the "and"
operator doesn 't short circuit because >>>
   # the LEFT side is truthy, so it evaluates the RIGHT >>>
   # and this is also truthy, so returns the truthy string. >>>
   "yes"
and "no"
'no' >>>
# this also returns the RIGHT truthy expression
   >>>
   "no"
and "yes"
'yes' >>>
# the "not"
operator short - circuits since "yes"
is truthy
   >>>
   # and returns False >>>
   not "yes"
False
   >>>
   # "no"
is truthy so will also
return False >>>
   not "no"
False
   >>>
   # note the "falsey"
empty string and None
   >>>
   # will
return True >>>
   not ""
True
   >>>
   not None
True
   >>>
   not 0
True

Suggestion : 3

This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.,A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and goes back to testing the expression.,The while statement is used for repeated execution as long as an expression is true:,If the same value occurs multiple times in the same match statement, the interpreter may cache the first value found and reuse it rather than repeat the same lookup. This cache is strictly tied to a given execution of a given match statement.

if test1: if test2: print(x)
if x < y < z: print(x);
print(y);
print(z)

The if statement is used for conditional execution:

if_stmt:: = "if"
assignment_expression ":"
suite
   ("elif"
      assignment_expression ":"
      suite) * ["else"
      ":"
      suite
   ]

The while statement is used for repeated execution as long as an expression is true:

while_stmt:: = "while"
assignment_expression ":"
suite
   ["else"
      ":"
      suite]

The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object:

for_stmt:: = "for"
target_list "in"
expression_list ":"
suite
   ["else"
      ":"
      suite]
2._
for i in range(10):
   print(i)
i = 5 # this will not affect the
for -loop
# because i will be overwritten with the next
# index in the range
for i in range(10):
   print(i)
i = 5 # this will not affect the
for -loop
# because i will be overwritten with the next
# index in the range

Suggestion : 4

So I'm writing a program (A sort of "custom anycodings_python if statement") that checks if your input is anycodings_python true or false. This is the script I have anycodings_python right now:,I'm expecting this to work, but then when i anycodings_python input something that's true, for example: anycodings_python __name__=="__main__", so my input looks like anycodings_python this:,I have replaced your exec with eval to anycodings_if-statement get rid of your global variable (still anycodings_if-statement not good coding practise, but if this is anycodings_if-statement what you need...). Also, the for is not anycodings_if-statement needed.,How do I fix this so it prints it anycodings_python accurately?

So I'm writing a program (A sort of "custom anycodings_python if statement") that checks if your input is anycodings_python true or false. This is the script I have anycodings_python right now:

v = line[3: ] # Remove "if "
from the line, so you only have the question and the consequence
i = v.split(': ') # Make a list with the first item being the question and the second item being the consequence.
for r in i:
   if r == i[1]: # Check which item in the list is the question and which is the consequence
c = r
question = i[0]
consequences = c.split(' | ')
for x in consequences:
   self.consequences += f '\n{x}'
# Create a variable with all of the consequences, each in one line
Answer = False # reate the Answer variable with the
default value False
def checkVal(question):
   global Answer
if question:
   b = open('if.BaRT', 'w+')
b.write(self.consequences)
b.close()
self.run('if.BaRT')
os.remove('if.BaRT')
else:
   pass # Check
if the question is true or false
if Answer == True:
   print("True!")
else:
   print("False!") # Finally check
if the question is true or not and
if it is, print "True!"
and
if it 's not, print "False!"

I'm expecting this to work, but then when i anycodings_python input something that's true, for example: anycodings_python __name__=="__main__", so my input looks like anycodings_python this:

if __name__ == "__main__": print("Hello!")

this is the output:

False!

PS: the variables i, v and c should have anycodings_if-statement better names.

line = 'if __name__=="__main__": print("Hello!")'
v = line[3: ] # Remove "if "
from the line, so you only have the question and the consequence
i = v.split(': ') # Make a list with the first item being the question and the second item being the consequence.

c = i[1]
question = i[0]
consequences = c.split(' | ')

_consequences = ''
for x in consequences:
   _consequences += f '\n{x}'
Answer = eval(f "{question}") # Check
if the question is true or false

if Answer == True:
   exec(_consequences)
print("True!")
else:
   print("False!") # Finally check
if the question is true or not and
if it is, print "True!"
and
if it 's not, print "False!"

Suggestion : 5

August 17, 2021August 17, 2021

Using the if statement you can find the function returned true or not in Python. This step is needed some time in order to proceed to the next step of a separate function.

if function_Name(argu):
   # do_something

Simple example code.

def validate_age(age):
   if age > 20:
   return True
else:
   return False

# Print value
print(validate_age(23))

# Check true
if validate_age(23):
   print("validate_age function returns True")
else:
   print("validate_age function returns False")

Suggestion : 6

The Boolean values True and False have no quotes around them! Just as '123' is a string and 123 without the quotes is not, 'True' is a string, not of type bool.,There are also Boolean operators that are applied to types others than numbers. A useful Boolean operator is in, checking membership in a sequence:,In general you should not need an if-else statement to choose between true and false values! Operate directly on the boolean expression.,You see that conditions are either True or False. These are the only possible Boolean values (named after 19th century mathematician George Boole). In Python the name Boolean is shortened to the type bool. It is the type of the results of true-false conditions or tests.

2 < 5
3 > 7
x = 11
x > 10
2 * x < x
type(True)
    weight = float(input("How many pounds does your suitcase weigh? "))
    if weight > 50:
       print("There is a $25 charge for luggage that heavy.")
    print("Thank you for your business.")
if balance < 0:
   transfer = -balance
# transfer enough from the backup account:
   backupAccount = backupAccount - transfer
balance = balance + transfer
    temperature = float(input('What is the temperature? '))
    if temperature > 70:
       print('Wear shorts.')
    else:
       print('Wear long pants.')
    print('Get some exercise outside.')
x = 5
x
x == 5
x == 6
x
x != 6
x = 6
6 == x
6 != x 'hi' == 'h' + 'i'
'HI' != 'hi' [1, 2] != [2, 1]
'a' > 5