Presentation is loading. Please wait.

Presentation is loading. Please wait.

Bools and simple if statements

Similar presentations


Presentation on theme: "Bools and simple if statements"— Presentation transcript:

1 Bools and simple if statements
Decisions in Python Bools and simple if statements

2 Computer logic is Boolean
George Boole, 19th cent. English mathematician, logician Had the idea to do logic with two values True and False Computer logic is based on exactly that Making decisions in a computer is based on two-valued logic, results are either True or False Python has two predefined constants (literals): True and False (note, no quotes) Several operators will give Boolean results

3 Relational Operators Familiar from algebra: >, <, >=, <=, ==, != Relational operators give the “relationship” between two things They can compare many different types, but be careful to compare things of the same type, ints and floats are ok, ints and strings are not They compare the two operands and give True or False as a result Comparing numbers is fairly routine Be careful about comparing floats to floats for exact equality The way floats are stored may cause some numbers that you think should be equal NOT to be equal Precedence of all of these operators is lower than the arithmetic operators and all six of them have the same precedence

4 Where to use them? You can use them to generate Bools and store the results X_larger = x > y # stores True or False in X_larger the_same = x == y # stores True or False in the_same Most often use the results in an if statement

5 if statement syntax statement starts with the word if
immediately followed by some expression which has a Bool value then a colon next will be at least one statement indented more than the if statement, usually several statements

6 if statement semantics
When an if statement is encountered in execution First the expression that gives the Boolean value will be evaluated If the result is True, the statements which are indented after the if will all be executed If the result of the expression is False, the statements which are indented will be skipped In either case execution continues at the next statement after the if statement


Download ppt "Bools and simple if statements"

Similar presentations


Ads by Google