While Loop Syntax while expression statements Example count
- Slides: 8
While Loop • Syntax: while expression: statement(s) Example: count = 0 while (count < 9): print 'The count is: ', count = count + 1 print "Good bye!"
While Loop: • "break" and "continue" statements break is used to exit a for loop or a while loop. continue is used to skip the current block, and return to the "for" or "while" statement.
Use else in Loop • When the loop condition of "for" or "while" statement fails then code part in "else" is executed. • If break statement is executed inside for loop then the "else" part is skipped. • Note that "else" part is executed even if there is a continue statement.
Nested While Loop while expression: statement(s)
Error and Exception • Error: Syntax error, also known as Parsing error. Example: while True print 'Hello world‘ • Exception: Error detected during execution Example: x=10/ • Syntax: try: pass except Exception: pass
Handling Exception while True: try: x = int(raw_input("Please enter a number: ")) break except Value. Error: print "Oops! That was no valid number. Try again. . . "
Try • The try clause(the statements between the try and except keywords) is executed. • If no exception occurs, the except clause is skipped and execution of the try clause is finished. • If an exception occurs during execution of the try clause, the rest of the clause is skipped. If the type of the exception matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try clause. • If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statement. if no handler is found, it is an unhandled exception and execution stops with a message as shown above.
Example of Exception • Arithmetic. Error • Zero. Division. Error • Value. Error