Thursday, 4 April 2024

Python Conditions

 

Conditions


Python uses boolean logic to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated. For example:


Program:

x = 2

print(x == 2

print(x == 3

print(x < 3)

# Scripts Ends 

Output:

True

False

True


Notice that variable assignment is done using a single equals operator "=", whereas comparison between two variables is done using the double equals operator "==". The "not equals" operator is marked as "!=".

 

1. Boolean operators

The "and", "or"  and "not" boolean operators allow building complex boolean expressions, for example:

Program:

name = "Balaji"

age = 50

if name == "Balaji" and age == 50:

    print("Your name is Blaji, and you are also 50 years old.")


if name == "Cris" or name == "Roky":

    print("Your name is either Cris or Roky.")

print(not(age <= 32))  

print(not(age <= 62))  

# Scripts Ends 

Output:

Your name is Blaji, and you are also 50 years old.

True

False


2. The "in" operator

The "in" operator could be used to check if a specified object exists within an iterable object container, such as a list:

Program:

name = "BalajiTech"

if name in ["Balaji", "BalajiTech"]:

    print("Your name is either BalajiTech or Balaji.")

# Scripts Ends 

Output:

Your name is either BalajiTech or Balaji.


Python uses indentation to define code blocks, instead of brackets. The standard Python indentation is 4 spaces, although tabs and any other space size will work, as long as it is consistent. Notice that code blocks do not need any termination.

Here is an example for using Python's "if" statement using code blocks:


Program:

statement = False

another_statement = True

if statement is True:

    # do something

    pass

elif another_statement is True: # else if

    # do something else

    pass

else:

    # do another thing

    pass

# Scripts Ends 

Output:



A statement is evaulated as true if one of the following is correct: 1. The "True" boolean variable is given, or calculated using an expression, such as an arithmetic comparison. 2. An object which is not considered "empty" is passed.

Here are some examples for objects which are considered as empty: 1. An empty string: "" 2. An empty list: [] 3. The number zero: 0 4. The false boolean variable: False


3. The 'is' and 'not' operator

Unlike the double equals operator "==", the "is" operator does not match the values of the variables, but the instances themselves. Using "not" before a boolean expression inverts it For example:

Program:

x = [1,2,3]

y = [1,2,3]

print(x == y) # Prints out True

print(x is y) # Prints out False


print(not False) # Prints out True

print((not False) == (False)) # Prints out False

# Scripts Ends 

Output:

True

False

True

False


No comments:

Post a Comment

Interactive Report: Introduction to the Internet of Things (IoT) ...

Popular Posts