Introduction to Computer Science Programming with Python Conditional


























- Slides: 26
Introduction to Computer Science Programming with Python
Conditional Statements Chapter 3
Conditional Steps
Comparison Operators ▪ Boolean expressions ask a question and produce Yes or No result which we use to control program flow ▪ Boolean expressions using comparison operators evaluate to True/False or Yes/No ▪ Comparison operators look at variables but do not change the variables Python Meaning < Less than <= Less than or equal to == equal to >= Greater than or Equal to > Greater than != Not equal
Comparison Operators
One-way Decisions
Indentation ▪ Python will get confused if you sometimes, use tabs and sometimes, 4 spaces ▪ It will look right to you, but Python will complain ▪ Sometimes, this causes to a statement to be out of block ▪ Tip, be consistent ▪ If you use spaces, keep using spaces without taps ▪ If you use tabs, keep using tabs without spaces ▪ Remember how many tabs you use ▪ Text. Editors will not be able to notify you with that ▪ IDEs such as Py. Charm, will notify you with indentation errors
Warning: Turn off Tabs ▪ Atom automatically uses spaces for files with ”. py” extension (nice!) ▪ Most text editors can turn tabs into spaces, make sure to enable this feature ▪ Note. Padd++: Settings Preferences Language Menu/Tab Settings ▪ Text/Wrangler: Text. Wrangler Preferences Editor Defaults ▪ Python cares a lot about how far a line is indented. If you mix tabs and spaces, you might get indentation errors even if everything looks fine This will save you much unnecessary pain
Code Blocks Increase / maintain after if or for – decrease to indicated and of block
Nested Decision
Two-way Decisions ▪ Sometimes we want to do one thing if a logical expression is true and something else if the expression is false ▪ It is like a fork in the road – we must choose one or the other path but not both
Two-way Decisions with else
More Conditional Statements Chapter 3
Multi-way Conditional Statements Only 1 statement will be executed. Either if, elsif, or else
Multi-way # No else
Multi-way Puzzles
Multi-way Puzzles
Multi-way Puzzles
Error Handling ▪ This is to prevent the system from crashing ▪ If you have a line of code, that might cause compiler errors, we need to prevent this from happening ▪ This is extremely important, Why? Lets see
The try / except Structure ▪ You surround a dangerous section of code with try and except ▪ If the code in the try works, the except is skipped ▪ If the code in the try fails, it jumps to the except ▪ In other programming languages such as Java, it is known as, try and catch. Where catch is referred to catching an exception/error
Hey!, I cannot convert a string to integer! So, I am quitting It stops here
Live Demo – Practical Example