{"id":115,"date":"2024-01-25T11:15:21","date_gmt":"2024-01-25T11:15:21","guid":{"rendered":"https:\/\/learnpython.elegantwallp.com\/?p=115"},"modified":"2024-01-25T11:15:22","modified_gmt":"2024-01-25T11:15:22","slug":"python-tryexceptelse","status":"publish","type":"post","link":"https:\/\/learnpython.elegantwallp.com\/2024\/01\/25\/python-tryexceptelse\/","title":{"rendered":"Python try\u2026except\u2026else"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you\u2019ll learn how to use the Python&nbsp;<code>try...except...else<\/code>&nbsp;statement.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the Python try\u2026except\u2026else statement<\/h2>\n\n\n\n<p>The\u00a0<code>try<\/code>\u00a0statement has an optional\u00a0<code>else<\/code>\u00a0clause with the following syntax:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>try: <em># code that may cause errors<\/em> except: <em># code that handle exceptions<\/em> else: <em># code that executes when no exception occurs<\/em> <\/code><small>Code language: PHP (php)<\/small><\/code><\/pre>\n\n\n\n<p>The&nbsp;<code>try...except...else<\/code>&nbsp;statement works as follows:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>If an exception occurs in the&nbsp;<code>try<\/code>&nbsp;clause, Python skips the rest of the statements in the&nbsp;<code>try<\/code>&nbsp;clause and the&nbsp;<code>except<\/code>&nbsp;statement execute.<\/li>\n\n\n\n<li>In case no exception occurs in the&nbsp;<code>try<\/code>&nbsp;clause, the&nbsp;<code>else<\/code>&nbsp;clause will execute.<\/li>\n<\/ul>\n\n\n\n<p>When you include the\u00a0<code>finally<\/code>\u00a0clause, the\u00a0<code>else<\/code>\u00a0clause executes after the\u00a0<code>try<\/code>\u00a0clause and before the\u00a0<code>finally<\/code>\u00a0clause.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Python try\u2026except\u2026else statement examples<\/h2>\n\n\n\n<p>Let\u2019s take some examples of using the&nbsp;<code>try...except...else<\/code>&nbsp;statement.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1) Using try\u2026except\u2026else statement for control flow<\/h3>\n\n\n\n<p>The following example illustrates how to use the&nbsp;<code>try...except...else<\/code>&nbsp;clause develop a program that calculates the body mass index (BMI).<\/p>\n\n\n\n<p>First, define a function for calculating the (BMI) based on height and weight:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def calculate_bmi(height, weight): \"\"\" calculate body mass index (BMI) \"\"\" return weight \/ height**2 <\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Second, define another function for evaluating BMI:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def evaluate_bmi(bmi): \"\"\" evaluate the bmi \"\"\" if 18.5 &lt;= bmi &lt;= 24.9: return 'healthy' if bmi >= 25: return 'overweight' return 'underweight' <\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Third, define a new\u00a0<code>main()<\/code>\u00a0function that prompts users for entering height and weight, and prints out the BMI result:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def main(): try: height = float(input('Enter your height (meters):')) weight = float(input('Enter your weight (kilograms):')) except ValueError as error: print('Error! please enter a valid number.') else: bmi = round(calculate_bmi(height, weight), 1) evaluation = evaluate_bmi(bmi) print(f'Your body mass index is {bmi}') print(f'This is considered {evaluation}!') <\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>The&nbsp;<code>main()<\/code>&nbsp;function uses the&nbsp;<code>try...except...else<\/code>&nbsp;statement to control its flow. If you enter height and weight that cannot be converted to numbers, the&nbsp;<code>ValueError<\/code>&nbsp;exception will occur.<\/p>\n\n\n\n<p>If no exception occurs, the&nbsp;<code>else<\/code>&nbsp;clause will execute. It calculates the BMI index and displays the evaluation.<\/p>\n\n\n\n<p>Put it all together.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def calculate_bmi(height, weight): \"\"\" calculate body mass index (BMI) \"\"\" return weight \/ height**2 def evaluate_bmi(bmi): \"\"\" evaluate the bmi \"\"\" if 18.5 &lt;= bmi &lt;= 24.9: return 'healthy' if bmi >= 25: return 'overweight' return 'underweight' def main(): try: height = float(input('Enter your height (meters):')) weight = float(input('Enter your weight (kilograms):')) except ValueError as error: print(error) else: bmi = round(calculate_bmi(height, weight), 1) evaluation = evaluate_bmi(bmi) print(f'Your body mass index is {bmi}') print(f'This is considered {evaluation}!') main()<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">2) Using Python try\u2026except\u2026else and finally example<\/h3>\n\n\n\n<p>The\u00a0<code>else<\/code>\u00a0clause executes right before the\u00a0<code>finally<\/code>\u00a0clause if no exception occurs in the\u00a0<code>try<\/code>\u00a0clause.<\/p>\n\n\n\n<p>The following example shows how to use the\u00a0<code>try...except...else...finally<\/code>\u00a0clause:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>fruits = { 'apple': 10, 'orange': 20, 'banana': 30 } key = None while True: try: key = input('Enter a key to lookup:') fruit = fruits&#91;key.lower()] except KeyError: print(f'Error! {key} does not exist.') except KeyboardInterrupt: break else: print(fruit) finally: print('Press Ctrl-C to exit.')<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>How it works.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, define the&nbsp;<code>fruits<\/code>&nbsp;dictionary that contains three elements.<\/li>\n\n\n\n<li>Second, use a&nbsp;<code>while<\/code>&nbsp;loop to repeatedly get inputs from users. It stops the loop until the users press&nbsp;<code>Ctrl-C<\/code>.<\/li>\n\n\n\n<li>Third, use the&nbsp;<code>try...except...else...finally<\/code>&nbsp;clause inside the&nbsp;<code>while<\/code>&nbsp;loop. We use the user input to find for the element in the dictionary.<\/li>\n<\/ul>\n\n\n\n<p>If the key doesn\u2019t exist, the&nbsp;<code>KeyError<\/code>&nbsp;exception occurs, the except clause will execute.<\/p>\n\n\n\n<p>If users press&nbsp;<code>Ctrl-C<\/code>, the&nbsp;<code>KeyboardInterrupt<\/code>&nbsp;exception occurs that executes the&nbsp;<code>break<\/code>&nbsp;statement to terminate the loop.<\/p>\n\n\n\n<p>If the key is found in the&nbsp;<code>fruits<\/code>&nbsp;dictionary, the program prints out the found element.<\/p>\n\n\n\n<p>The&nbsp;<code>finally<\/code>&nbsp;clause always executes. It shows the reminder to the users that they should press Ctrl-C to exit.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Summary: in this tutorial, you\u2019ll learn how to use the Python&nbsp;try&#8230;except&#8230;else&nbsp;statement. Introduction to the Python try\u2026except\u2026else statement The\u00a0try\u00a0statement has an optional\u00a0else\u00a0clause with the following syntax: The&nbsp;try&#8230;except&#8230;else&nbsp;statement works as follows: When you include the\u00a0finally\u00a0clause, the\u00a0else\u00a0clause executes after the\u00a0try\u00a0clause and before the\u00a0finally\u00a0clause. Python try\u2026except\u2026else statement examples Let\u2019s take some examples of using the&nbsp;try&#8230;except&#8230;else&nbsp;statement. 1) Using try\u2026except\u2026else statement [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[22],"tags":[],"class_list":["post-115","post","type-post","status-publish","format-standard","hentry","category-8-exception-handling"],"_links":{"self":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/115","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/comments?post=115"}],"version-history":[{"count":1,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/115\/revisions"}],"predecessor-version":[{"id":116,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/115\/revisions\/116"}],"wp:attachment":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/media?parent=115"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/categories?post=115"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/tags?post=115"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}