CHAPTER 9 - PYTHON IF STATEMENTS



AD

If statements are the backbone of programming. Fortunately they are fairly simple to understand. Watch indentations for If statements. With input statements, remember to declare the variables as int, or float. When using input remember to have cursor in the results window of PyCharm, before entering input.

9.1.0 If statement

A simple if statement:

myinteger1 = 30
myinteger2 = 40
if myinteger2 > myinteger1:
    print('myinteger2 is larger than myinteger1')

# Output
# myinteger2 is larger than myinteger1

9.2.0 An if-else statement

myinteger1 = input("Input myinteger1")
myinteger2 = input("Input myinteger2")
myinteger1 = int(myinteger1)
myinteger2 = int(myinteger2)
if myinteger2 > myinteger1:
   print('myinteger2 is larger than myinteger1')
else:
   print('myinteger1 is larger than myinteger2')

# Output
# Input myinteger1 8
# Input myinteger2 9
# myinteger2 is larger than myinteger1

9.3.0 An if-elif-else statement

An if – elif – else statement. Note that there can be multiple elif.

myinteger1 = input("Input myinteger1")
myinteger2 = input("Input myinteger2")
myinteger1 = int(myinteger1)
myinteger2 = int(myinteger2)
if myinteger2 > myinteger1:
    print('myinteger2 is larger than myinteger1')
elif myinteger1 == myinteger2:
    print('myinteger2 equals myinteger1')
else:
    print('myinteger2 is smaller than myinteger1')

# Output
# Input myinteger1     4
# Input myinteger2     9
# myinteger2 is larger than myinteger1

9.4.0 Conditional Operators

If statements have the following Condition Operators:

Equals    a == b
Not Equals    a != b
Less Than    a < b
Less Than or Equal To    a <= b
Greater Than    a > b
Greater Than or Equal To     a >= b

Note that == is a comparison operator, where = is an assignment operator in Python.

9.5.0 Logical Operators

and    returns true if both statements are true
or    returns true if one of the statements is true
not    reverse results, returns false if the result is true

The following examples use the logical operators.

myint1 = 30
myint2 = 40
print(myint2 > myint1)     # Result is True
print(myint2 > 3 and myint1 > 5)     # Result is True
print(myint2 > 3 and myint1>120)     # Result is False

# Output
# True
# True
# False





Win-Python Navigation

SALARSEN.COM
Table of Contents
Ch1-Install Python
Ch2-Install PyCharm
Ch3-Save Work
Ch4-Add Project
Ch5-Variables
Ch6-Print&Input
Ch7-Lists
Ch8-Loops
Ch9-If&Logical
Ch10-Functions
Ch11-Bubble Sort
Ch12-Plotting
Ch13-Files
Ch14-Print Format
Ch15-Dict&Comp&Zip
Ch16-Arrays
Ch17-Electrical
Ch18-Regression
Ch19-Differential
Ch20-Secant