DEV Community

DEV Community

Emil Ossola

Posted on May 31, 2023

Mastering Python's If-Else Shorthand

Python's if-else statements are an essential tool for writing conditional statements in your code. It allows you to execute a block of code based on the result of a condition.

However, Python also offers a shorthand syntax for if-else statements, which can make your code more concise and easier to read. This shorthand syntax is also known as the ternary operator or conditional expression.

In this article, we will explore how to use the shorthand syntax for if-else statements and how it can help you write more efficient and readable code.

Image description

Basic syntax of if-else shorthand

Python's if-else shorthand is a concise way of writing conditional statements. The syntax of if-else shorthand is as follows:

Image description

The condition is evaluated first, and if it is True, the expression value_if_true is returned. If the condition is False, the expression value_if_false is returned. This shorthand can be used as a replacement for the longer if-else statements. The basic syntax can be enhanced with nested if-else statements and also with the and and or operators to make more complex conditional statements.

Example code snippet for Python If Else Shorthand

Here's an example code snippet that demonstrates the basic syntax of Python's If-Else shorthand:

In the first block of code, we have a traditional if-else statement that assigns the value "Positive" to the variable result if x is greater than 0, and "Non-Positive" otherwise.

In the second block of code, we have the same functionality achieved with the If-Else shorthand. This code is more concise and easier to read. We assign the value "Positive" to result if x is greater than 0, and "Non-Positive" otherwise, all in a single line of code.

Multiple conditions in if-else shorthand

Python's if-else shorthand allows developers to write a more concise and readable code when dealing with conditional statements. In cases where multiple conditions need to be checked, you can use logical operators such as and and or to combine them. For example:

Here, we used the and operator to check if x is between 5 and 15, and the or operator to check if y is not between 10 and 30. By using these operators, we can combine multiple conditions into a single line of code and make it more readable.

Example code snippet of multiple conditions in if-else shorthand

Here is an example code snippet to demonstrate multiple conditions in if-else shorthand:

In the above example, we have used the if-else shorthand with multiple conditions to check which variable is greater. If a is greater than b, then the first condition is true and the result will be "a is greater than b". If a is equal to b, then the second condition is true and the result will be "a is equal to b". If neither of these conditions is true, then the third condition is true and the result will be "b is greater than a".

Nested if-else shorthand

In Python, we can use nested if-else shorthand to simplify our code and make it more readable. This involves nesting an if-else statement inside another if or else statement. The syntax for nested if-else shorthand is as follows:

Image description

In this example, we are checking if the value is greater than 10. If it is, then the result variable will be assigned the string "Greater than 10". If it's not, then it will be assigned the string "Less than or equal to 10". We can also nest another if-else statement inside either the if or else branch to further simplify our code.

Example code snippet of nested if-else shorthand

Here's an example code snippet that demonstrates Python's nested if-else shorthand:

This code snippet uses nested if-else shorthand to check the values of x, y, and z and assign the appropriate message to the result variable based on the values. The first expression uses the ternary conditional operator shorthand to check whether x is greater than y. The second expression uses nested if-else shorthand to check whether x is greater than both y and z. This shorthand makes the code concise and easy to read.

Ternary operator in Python

In Python, the ternary operator is a shorthand method of writing an if-else statement. It is often used to assign the result of an expression to a variable based on a condition.

The ternary operator takes the form of a single line of code that includes the condition, a question mark (?), and two expressions separated by a colon (:). If the condition is true, the expression before the colon is executed; if the condition is false, the expression after the colon is executed. This operator is often used to simplify code and make it more readable.

Example code snippet of ternary operator in Python

The ternary operator in Python is a shorthand way of writing an if-else statement in a single line. It takes the form of value_if_true if condition else value_if_false. Here's an example code snippet that demonstrates how to use the ternary operator in Python:

In this example, we're using the ternary operator to check whether the value of num is even or odd. If num is even, the value of even_or_odd will be "even". Otherwise, it will be "odd". The output of this code snippet will be:

Recap of If-Else Statement in PythonProgramming

If-else statements are fundamental to programming since they enable a program to execute different instructions based on a particular condition. They allow us to control the flow of our program and make it more dynamic.

In Python programming, if-else statements are commonly used for decision making, looping, and error handling. Without if-else statements, it would be impossible to write programs that can respond to different situations and conditions.

In Python, using the if-else shorthand is a great way to write more readable and concise code. As we have seen, there are different ways to implement this shorthand technique, depending on the specific use case. It's important to remember that, while this technique can be very useful, it can also make your code harder to understand if you overuse it.

Learning Python with an online Python compiler

Learning a new programming language might be intimidating if you're just starting out. Lightly IDE, however, makes learning Python simple and convenient for everybody. Lightly IDE was made so that even complete novices may get started writing code.

Image description

Lightly IDE's intuitive design is one of its many strong points. If you've never written any code before, don't worry; the interface is straightforward. You may quickly get started with Python programming with our online Python compiler only a few clicks.

The best part of Lightly IDE is that it is cloud-based, so your code and projects are always accessible from any device with an internet connection. You can keep studying and coding regardless of where you are at any given moment.

Lightly IDE is a great place to start if you're interested in learning Python. Learn and collaborate with other learners and developers on your projects and receive comments on your code now.

Extended Readings on Python

  • Step-by-Step Guide to Writing List of Files in Directory with Python
  • How to Convert a List to a Tuple in Python
  • How to Import Class from Another File in Python

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

jzfrank profile image

HFDP(12) - Compound Pattern

jzfrank - May 29

dharamgfx profile image

🤷‍♀️Mastering JavaScript Console Methods: Boost Your Debugging Skills!🚀

Dharmendra Kumar - May 29

techiesdiary profile image

ChatGPT - Prompts for Code Refactoring

Sandeep Kumar - May 29

rsicarelli profile image

KMP-102 - XCFramework para Devs KMP

Rodrigo Sicarelli - May 29

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Python If Else shorthand with examples

Python If Else shorthand with examples

Table of Contents

Have you ever wondered if you can write if else statements in the same line like a ternary operator: x=a>10?"greater":"not greater" in Python?

In this article, we will see how to write Shorthands for if else statements in Python.

Simple if condition

We can write a simple if condition in Python as shown below:

There are no shorthands for simple if statements.

If else statements

Consider the following if else statement:

We can shorten it as shown below:

The syntax here is

action_if_true if condition else action_if_false

You can assign the result to a variable as well:

Else if ladder

In Python you can write an else-if ladder as shown below:

The shorthand for the else-if ladder would be:

Using tuples as a ternary operator

Python has the following syntax to assign the boolean value of the result. However, this is a confusing syntax and is not used widely.

If you have liked article, do follow me on twitter to get more real time updates!

Related Articles

  • Cannot import name 'force_text' from django.utils.encoding

Leave a Comment

  • Python if-else Shorthand
  • Python How-To's

Use the Ternary Operator as if-else Shorthand in Python

Python if-else Shorthand

Shorthand notations are often used in programming to make our work easier. Shorthand notations are the methods by which a work can be done more concisely and in less time and energy.

This article will discuss the shorthand notation used in Python as a shortcut for the if-else statements.

As discussed earlier, a shorthand notation is a way in which a program can be written concisely. There have been many shorthand notations that we have been using so far in Python.

Let us take the example of the assignment operators. The expression a=a+b becomes a+=b ; similarly, a=a/b becomes a/=b , and many more.

Similar to such shorthand notations in Python, we have one more notation known as a ternary operator for the if-else statement in Python. It was introduced in Python version 2.5 and is continued to exist because of its usefulness.

Since the if-else statements are used as decision-making statements in any programming language, so are ternary operators. These ternary operators decide whether to execute the first set of statements or the second based on the condition’s truth or falsity.

This ternary operator is used in almost all programming languages, such as Java, C++, etc., in place of the if-else statement making it easier to use the if statement. However, Python does not follow the same syntax as the other languages, but the purpose remains the same in all of them.

There are three components in the ternary operator: the condition, the positive value, and the negative value. The condition is the same thing checked in an if statement; it will decide whether to execute the statements inside if or else .

The positive value refers to the statements inside the if statement, whereas the negative value represents the statements inside the else statement in Python.

In other languages, the ternary operator is used with the colon and the question mark symbol. However, the if and the else keywords are used in Python but with different syntax.

The syntax for the ternary operator is as follows:

However, the syntax seems a little confusing, but the processing is as simple as the if/else statements. Let us understand the ternary operator with the help of the code examples.

Therefore, as you can observe in the above code example, the expression 3>4 is checked for validity since it is false. Thus, the statement print(15) after else has been executed.

On the other hand, since the expression/condition 5>4 is true. Therefore, the positive statement print(10) has been executed.

Let us take another example to grasp the ternary operator in Python better.

As you can observe in the above code example, in the first statement, the positive value to be evaluated, 2+a , has been printed since the condition a==4 was true. Had it not been true, the value of b would have been printed.

Similarly, for the second assignment statement, the condition is evaluated that turns out to be false. Therefore, the value b will be printed with an addition of 1, and the answer turns out to be 3.

In this article, we’ve learned about the shorthand notation for the if-else statement in Python, the ternary operator.

The ternary operator comes with a condition/expression, a positive, and a negative value. The condition/expression is checked, and if found true, the positive value is executed; otherwise, the negative statement is executed.

Related Article - Python Condition

  • How to Use the if not Condition in Python

Shorthand syntax for if/else in Python (conditional expression)

In Python, the shorthand syntax for an if/else statement is called a conditional expression or a ternary operator. It allows you to write a concise one-liner to evaluate a condition and choose one of two values based on the result of that condition.

What is the Point?

The syntax of the conditional expression is as follows:

Explanation of the syntax:

  • condition : The expression that is evaluated to determine which value to choose.
  • value_if_true : The value returned if the condition is true.
  • value_if_false : The value returned if the condition is false.

For example, you can write:

Instead of:

Nested shorthand if/else/elif

The shorthand syntax can also be nested to create a shorthand elif statement, but this is not recommended as it reduces readability and may cause errors. The syntax for a nested shorthand if/else/elif in Python is:

Where condition_1 and condition_2 are any expressions that evaluate to boolean values, value_if_true_1 is the value to return if condition_1 is true, value_if_true_2 is the value to return if condition_1 is false and condition_2 is true, and value_if_false is the value to return if both conditions are false (again, you should refrain from using this syntax as it is very error-prone and difficult to debug).

The code snippet above is equivalent to this:

More examples

Some more practical examples that demonstrate the beauty and conciseness of conditional expression in Python.

Checking if a string is empty or not

Converting a boolean value to its string representation, assigning a default value if a variable is none.

This tutorial ends here. Happy coding & have a nice day!

Next Article: Making use of the "with" statement in Python (4 examples)

Previous Article: Python Function: Keyword & Positional Arguments

Series: Control Flow & Functions in Python

Related Articles

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries

Search tutorials, examples, and resources

  • PHP programming
  • Symfony & Doctrine
  • Laravel & Eloquent
  • Tailwind CSS
  • Sequelize.js
  • Mongoose.js

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python shorthandf if else, if ... else in one line.

If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:

One line if else statement:

You can also have multiple else statements on the same line:

One line if else statement, with 3 conditions:

Related Pages

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Currently Reading :

Currently reading:

Types Of Control Flow In Python

Python if-else statements.

Author image

Harsh Pandey

Software Developer

Published on  Thu Mar 14 2024

Python's if-else statements are conditional constructs used for decision-making. They execute a code block if a specified condition is true and another block if it's false. Syntax includes if followed by the condition, then else. It's fundamental in controlling program flow, allowing for responsive and dynamic code execution.

Control flow in Python is primarily managed through if-else statements, allowing the program to execute certain code blocks conditionally. These statements evaluate a condition, executing a block of code if the condition is true, and optionally, another block if the condition is false. Python supports various forms of these conditional structures, each serving different purposes.

The simplest form is the if statement. It executes the specified block only when the condition is true. For instance.

Output: x is greater than 3

For situations requiring two conditions, if-else is used. It provides an alternative path of execution when the if condition fails.

Output: x is not greater than 3

When multiple conditions need to be checked, elif (else if) statements come into play. They allow for sequential checking of conditions.

Output: x is greater than 3 but not greater than 5

These conditional statements are fundamental in Python, enabling the script to react differently based on varying inputs or situations, thus making the code dynamic and responsive.

Python if else Statement In A List Comprehension

Python if-else statements can be efficiently integrated into list comprehensions, providing a concise way to create lists by iterating over an iterable and conditionally including elements. This approach combines the power of if-else statements with the brevity and readability of list comprehensions.

In Python, list comprehensions offer a clear and expressive way to construct lists. Utilizing if-else statements within them enables conditional logic to be applied to each element of the iterated sequence. This results in dynamic list creation based on specific conditions.

For example, consider a scenario where you want to create a list of strings based on the values in a numerical list: for numbers greater than 5, the string 'High' is appended to the new list, and for numbers less or equal to 5, the string 'Low' is appended. This can be achieved with a single line of code using a list comprehension with an if-else statement.

Output: ['Low', 'High', 'Low', 'High', 'Low']

Nested-If Statement In Python

Nested-if statements in Python are constructs where an if or elif statement is present inside another if or elif clause. This structure is commonly used when multiple conditions need to be checked in sequence. Each nested if statement allows for further conditional branching, providing more granularity in decision-making processes.

In Python, indentation is crucial for defining the scope of each nested conditional block. The inner if statements are only evaluated if the outer if condition is true. If the outer condition is false, the inner nested conditions are not checked.

For example, consider a scenario where we want to check if a number is positive and even. First, we check if the number is positive, and if it is, we then check if it's even.

# Output: Number is positive and even.

Python if-elif-else Ladder

Python if-elif-else ladder is a way of handling multiple conditions in a program. This structure allows the program to evaluate each condition in sequence and execute a block of code corresponding to the first true condition. The if-elif-else ladder starts with an 'if' statement, which is the initial condition to check. If this condition is false, the program moves to the next condition, indicated by an 'elif' (short for else if) statement. You can have as many 'elif' statements as necessary. Finally, if none of the 'if' or 'elif' conditions are true, the code in the 'else' block executes.

The if-elif-else ladder is crucial for decision-making processes in Python, allowing for clear and efficient control flow based on various conditions.

Here's a simple coding example to demonstrate how the if-elif-else ladder works.

In this example, the program checks the value of age. The output of the code will be "Adult" since age is 20, which falls under the second condition (elif age < 60). If age were less than 18, it would print "Minor", and if age were 60 or above, it would print "Senior Citizen".

Short Hand if Statement

The shorthand if statement in Python allows a more concise way to execute an expression based on a condition. This form is typically used when you have a single statement to execute in the case of a true condition. It's handy for simple conditions and actions written in a single line.

The shorthand if statement in Python follows the structure: action if condition else other_action. This format allows you to act if a condition is true and another action if the condition is false, all in one line.

For example, consider assigning a value to a variable based on a condition. You can do this in a single line using a shorthand if statement.

In this code, max_value will be assigned the value of x if x is greater than y, otherwise y is assigned to it. The output of this code will be 20, as y is greater than x. This approach simplifies the code and improves readability for straightforward conditional assignments.

Short Hand if-else Statement

The short-hand if-else statement in Python, also known as the ternary operator, allows for concise decision-making in a single line. This operator evaluates a condition and returns one of two values based on whether the condition is true or false. It follows the syntax: value_if_true if condition else value_if_false.

This compact form is particularly useful for simple conditional assignments. For instance, instead of using a multi-line if-else block to assign a value to a variable, you can do it in a single line.

In this code, max_value is assigned the value of a if a is greater than b, otherwise, it gets the value of b. The output of this program would be 20, as b is greater than a. This demonstrates a straightforward and efficient way of implementing a condition-based assignment.

Harsh Pandey

About the author

Software Developer adept in crafting efficient code and solving complex problems. Passionate about technology and continuous learning.

Related Blogs

Exploratory Data Analysis on Iris Dataset in Python

Harsh Pandey

Accessing Key Value In A Dictionary

How to prepend elements to a list in Python?

Get current year in Python

How To Create A Dictionary In Python

How to Calculate z-score in Python

Browse Flexiple's talent pool

Explore our network of top tech talent. Find the perfect match for your dream team.

  • Programmers
  • React Native
  • Ruby on Rails

TutorialsTonight Logo

Python Conditional Assignment

When you want to assign a value to a variable based on some condition, like if the condition is true then assign a value to the variable, else assign some other value to the variable, then you can use the conditional assignment operator.

In this tutorial, we will look at different ways to assign values to a variable based on some condition.

1. Using Ternary Operator

The ternary operator is very special operator in Python, it is used to assign a value to a variable based on some condition.

It goes like this:

Here, the value of variable will be value_if_true if the condition is true, else it will be value_if_false .

Let's see a code snippet to understand it better.

You can see we have conditionally assigned a value to variable c based on the condition a > b .

2. Using if-else statement

if-else statements are the core part of any programming language, they are used to execute a block of code based on some condition.

Using an if-else statement, we can assign a value to a variable based on the condition we provide.

Here is an example of replacing the above code snippet with the if-else statement.

3. Using Logical Short Circuit Evaluation

Logical short circuit evaluation is another way using which you can assign a value to a variable conditionally.

The format of logical short circuit evaluation is:

It looks similar to ternary operator, but it is not. Here the condition and value_if_true performs logical AND operation, if both are true then the value of variable will be value_if_true , or else it will be value_if_false .

Let's see an example:

But if we make condition True but value_if_true False (or 0 or None), then the value of variable will be value_if_false .

So, you can see that the value of c is 20 even though the condition a < b is True .

So, you should be careful while using logical short circuit evaluation.

While working with lists , we often need to check if a list is empty or not, and if it is empty then we need to assign some default value to it.

Let's see how we can do it using conditional assignment.

Here, we have assigned a default value to my_list if it is empty.

Assign a value to a variable conditionally based on the presence of an element in a list.

Now you know 3 different ways to assign a value to a variable conditionally. Any of these methods can be used to assign a value when there is a condition.

The cleanest and fastest way to conditional value assignment is the ternary operator .

if-else statement is recommended to use when you have to execute a block of code based on some condition.

Happy coding! 😊

  • Module 2: The Essentials of Python »
  • Conditional Statements
  • View page source

Conditional Statements 

There are reading-comprehension exercises included throughout the text. These are meant to help you put your reading to practice. Solutions for the exercises are included at the bottom of this page.

In this section, we will be introduced to the if , else , and elif statements. These allow you to specify that blocks of code are to be executed only if specified conditions are found to be true, or perhaps alternative code if the condition is found to be false. For example, the following code will square x if it is a negative number, and will cube x if it is a positive number:

Please refer to the “Basic Python Object Types” subsection to recall the basics of the “boolean” type, which represents True and False values. We will extend that discussion by introducing comparison operations and membership-checking, and then expanding on the utility of the built-in bool type.

Comparison Operations 

Comparison statements will evaluate explicitly to either of the boolean-objects: True or False . There are eight comparison operations in Python:

The first six of these operators are familiar from mathematics:

Note that = and == have very different meanings. The former is the assignment operator, and the latter is the equality operator:

Python allows you to chain comparison operators to create “compound” comparisons:

Whereas == checks to see if two objects have the same value, the is operator checks to see if two objects are actually the same object. For example, creating two lists with the same contents produces two distinct lists, that have the same “value”:

Thus the is operator is most commonly used to check if a variable references the None object, or either of the boolean objects:

Use is not to check if two objects are distinct:

bool and Truth Values of Non-Boolean Objects 

Recall that the two boolean objects True and False formally belong to the int type in addition to bool , and are associated with the values 1 and 0 , respectively:

Likewise Python ascribes boolean values to non-boolean objects. For example,the number 0 is associated with False and non-zero numbers are associated with True . The boolean values of built-in objects can be evaluated with the built-in Python command bool :

and non-zero Python integers are associated with True :

The following built-in Python objects evaluate to False via bool :

Zero of any numeric type: 0 , 0.0 , 0j

Any empty sequence, such as an empty string or list: '' , tuple() , [] , numpy.array([])

Empty dictionaries and sets

Thus non-zero numbers and non-empty sequences/collections evaluate to True via bool .

The bool function allows you to evaluate the boolean values ascribed to various non-boolean objects. For instance, bool([]) returns False wherease bool([1, 2]) returns True .

if , else , and elif 

We now introduce the simple, but powerful if , else , and elif conditional statements. This will allow us to create simple branches in our code. For instance, suppose you are writing code for a video game, and you want to update a character’s status based on her/his number of health-points (an integer). The following code is representative of this:

Each if , elif , and else statement must end in a colon character, and the body of each of these statements is delimited by whitespace .

The following pseudo-code demonstrates the general template for conditional statements:

In practice this can look like:

In its simplest form, a conditional statement requires only an if clause. else and elif clauses can only follow an if clause.

Similarly, conditional statements can have an if and an else without an elif :

Conditional statements can also have an if and an elif without an else :

Note that only one code block within a single if-elif-else statement can be executed: either the “if-block” is executed, or an “elif-block” is executed, or the “else-block” is executed. Consecutive if-statements, however, are completely independent of one another, and thus their code blocks can be executed in sequence, if their respective conditional statements resolve to True .

Reading Comprehension: Conditional statements

Assume my_list is a list. Given the following code:

What will happen if my_list is [] ? Will IndexError be raised? What will first_item be?

Assume variable my_file is a string storing a filename, where a period denotes the end of the filename and the beginning of the file-type. Write code that extracts only the filename.

my_file will have at most one period in it. Accommodate cases where my_file does not include a file-type.

"code.py" \(\rightarrow\) "code"

"doc2.pdf" \(\rightarrow\) "doc2"

"hello_world" \(\rightarrow\) "hello_world"

Inline if-else statements 

Python supports a syntax for writing a restricted version of if-else statements in a single line. The following code:

can be written in a single line as:

This is suggestive of the general underlying syntax for inline if-else statements:

The inline if-else statement :

The expression A if <condition> else B returns A if bool(<condition>) evaluates to True , otherwise this expression will return B .

This syntax is highly restricted compared to the full “if-elif-else” expressions - no “elif” statement is permitted by this inline syntax, nor are multi-line code blocks within the if/else clauses.

Inline if-else statements can be used anywhere, not just on the right side of an assignment statement, and can be quite convenient:

We will see this syntax shine when we learn about comprehension statements. That being said, this syntax should be used judiciously. For example, inline if-else statements ought not be used in arithmetic expressions, for therein lies madness:

Short-Circuiting Logical Expressions 

Armed with our newfound understanding of conditional statements, we briefly return to our discussion of Python’s logic expressions to discuss “short-circuiting”. In Python, a logical expression is evaluated from left to right and will return its boolean value as soon as it is unambiguously determined, leaving any remaining portions of the expression unevaluated . That is, the expression may be short-circuited .

For example, consider the fact that an and operation will only return True if both of its arguments evaluate to True . Thus the expression False and <anything> is guaranteed to return False ; furthermore, when executed, this expression will return False without having evaluated bool(<anything>) .

To demonstrate this behavior, consider the following example:

According to our discussion, the pattern False and short-circuits this expression without it ever evaluating bool(1/0) . Reversing the ordering of the arguments makes this clear.

In practice, short-circuiting can be leveraged in order to condense one’s code. Suppose a section of our code is processing a variable x , which may be either a number or a string . Suppose further that we want to process x in a special way if it is an all-uppercased string. The code

is problematic because isupper can only be called once we are sure that x is a string; this code will raise an error if x is a number. We could instead write

but the more elegant and concise way of handling the nestled checking is to leverage our ability to short-circuit logic expressions.

See, that if x is not a string, that isinstance(x, str) will return False ; thus isinstance(x, str) and x.isupper() will short-circuit and return False without ever evaluating bool(x.isupper()) . This is the preferable way to handle this sort of checking. This code is more concise and readable than the equivalent nested if-statements.

Reading Comprehension: short-circuited expressions

Consider the preceding example of short-circuiting, where we want to catch the case where x is an uppercased string. What is the “bug” in the following code? Why does this fail to utilize short-circuiting correctly?

Links to Official Documentation 

Truth testing

Boolean operations

Comparisons

‘if’ statements

Reading Comprehension Exercise Solutions: 

Conditional statements

If my_list is [] , then bool(my_list) will return False , and the code block will be skipped. Thus first_item will be None .

First, check to see if . is even contained in my_file . If it is, find its index-position, and slice the string up to that index. Otherwise, my_file is already the file name.

Short-circuited expressions

fails to account for the fact that expressions are always evaluated from left to right. That is, bool(x.isupper()) will always be evaluated first in this instance and will raise an error if x is not a string. Thus the following isinstance(x, str) statement is useless.

12 Python if else Exercises for Beginners

python-if-else-exercises-for-practice-program-with-solution-pdf

One of the basic concepts of Python is the if else statement , which allows you to execute different blocks of code depending on some conditions. In this article, we will learn how to use the if-else statement in Python and practice some exercises for beginners.

Course for You: Learn Python in 100 days of coding

What is the if-else statement in Python?

The if-else statement in Python is a way of making decisions based on some conditions. The general syntax of the if-else statement is:

The condition can be any expression that evaluates to either True or False . For example, you can use comparison operators ( == , != , < , > , <= , >= ) or logical operators ( and , or , not ) to create conditions. The code inside the if block will be executed only if the condition is True , otherwise the code inside the else block will be executed.

You can also use the elif keyword to add more conditions after the first if statement. The syntax of the elif statement is:

You can have as many elif statements as you want, but you can only have one else statement at the end. The conditions are checked from top to bottom, and only the first one that is True will be executed.

Now that you have learned how to use the if-else statement in Python, you can try some exercises to test your skills. Here are some problems that you can solve using the if-else statement:

Exercise 1: Checking Even or Odd

Let’s start with a simple exercise. Write a Python program that takes an integer as input and prints whether it is even or odd using if else statement.

Exercise 2: Grade Calculator

Create a Python program that calculates and displays the grade of a student based on their score. The grading criteria are as follows:

  • Score >= 90: A
  • 80 <= Score < 90: B
  • 70 <= Score < 80: C
  • 60 <= Score < 70: D
  • Score < 60: F

Exercise 3: Leap Year Checker

Write a Python program that checks if a given year is a leap year or not. A leap year is divisible by 4, except for years divisible by 100 but not divisible by 400.

Exercise 4: Age Classifier

Create a Python program that categorizes a person’s age into different groups: child, teenager, adult, or senior.

Exercise 5: Temperature Converter

Write a Python program that converts temperatures between Celsius and Fahrenheit. The user should input the temperature and its unit (C or F), and the program should convert it to the other unit.

Exercise 6: Simple Calculator for Addition

Create a simple calculator program that performs addition, subtraction, multiplication, or division based on user input.

Exercise 7: Number Comparison

Write a program that compares two numbers and determines whether they are equal, greater than, or less than each other.

Exercise 8: Simple ATM Machine

Create a basic ATM machine program that allows users to check their account balance and withdraw funds. You can set an initial account balance and then deduct the withdrawn amount.

Exercise 9: BMI Calculator

Create a Python program that calculates and categorizes a person’s Body Mass Index (BMI) based on their height and weight.

Exercise 10: Ticket Pricing

Create a Python program for a movie theater that calculates ticket prices based on age and time of day. Tickets for children (age < 12) are $5, adults (age >= 12) are $10, and seniors (age >= 60) are $7. For evening shows (after 5 PM), there’s an additional $2 surcharge.

Exercise 11: Voting Eligibility Checker

Create a Python program that determines whether a person is eligible to vote based on their age.

Exercise 12: Check for Vowel or Consonant

Write a Python program that checks whether a given letter is a vowel or a consonant.

In this article, I have listed 12 normal and nasted ‘if else’ practice program exercises in Python, you can use it as pdf and read it whenever you want. These ‘if-else’ exercises cover various scenarios and will help you gain confidence in using conditional statements in Python more often to prepare for the interview.

This is it for this article. If you want to learn Python quickly then this Udemy course is for you: Learn Python in 100 days of coding . If you are a person who loves learning from books then this article is for you: 5 Best Book for Learning Python . See you in the comment section below.

Similar Read:

  • 15 Simple Python Programs for Practice with Solutions
  • 14 Python Exercises for Intermediate with Solutions
  • 12 Python Object Oriented Programming (OOP) Exercises
  • 19 Python Programming Lists Practice Exercises
  • 11 Basic lambda Function Practice Exercises in Python
  • 15 Python while Loop Exercises with Solutions for Beginners
  • 14 Simple for Loop Exercises for Beginners in Python
  • 12 Python Dictionary Practice Exercises for Beginners

Anindya Naskar

Hi there, I’m Anindya Naskar, Data Science Engineer. I created this website to show you what I believe is the best possible way to get your start in the field of Data Science.

Related Posts

  • Learn Dash with Python in 5 minutes
  • Color detection using OpenCV and Python
  • Flask vs Django: Which One is Easier for Machine Learning?
  • Add HTML and CSS in Flask Web Application
  • Install TensorFlow GPU with Jupiter notebook for Windows
  • Learn CNN from scratch with Python and Numpy
  • How to Make Money With Python: 12 Proven Ways

Leave a comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Get Started With Python
  • Your First Python Program
  • Python Comments

Python Fundamentals

  • Python Variables and Literals
  • Python Type Conversion
  • Python Basic Input and Output
  • Python Operators

Python Flow Control

  • Python if...else Statement
  • Python for Loop

Python while Loop

Python break and continue

Python pass Statement

Python Data types

  • Python Numbers and Mathematics
  • Python List
  • Python Tuple
  • Python String
  • Python Sets
  • Python Dictionary
  • Python Functions
  • Python Function Arguments
  • Python Variable Scope
  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

  • Python Directory and Files Management
  • Python CSV: Read and Write CSV files
  • Reading CSV files in Python
  • Writing CSV files in Python
  • Python Exception Handling
  • Python Exceptions
  • Python Custom Exceptions

Python Object & Class

  • Python Objects and Classes
  • Python Inheritance
  • Python Multiple Inheritance
  • Polymorphism in Python
  • Python Operator Overloading

Python Advanced Topics

  • List comprehension
  • Python Lambda/Anonymous Function
  • Python Iterators
  • Python Generators
  • Python Namespace and Scope
  • Python Closures
  • Python Decorators
  • Python @property decorator
  • Python RegEx

Python Date and Time

  • Python datetime
  • Python strftime()
  • Python strptime()
  • How to get current date and time in Python?
  • Python Get Current Time
  • Python timestamp to datetime and vice-versa
  • Python time Module
  • Python sleep()

Additional Topic

  • Precedence and Associativity of Operators in Python
  • Python Keywords and Identifiers
  • Python Asserts
  • Python Json
  • Python *args and **kwargs

Python Tutorials

Python Assert Statement

  • List of Keywords in Python

In computer programming, the if statement is a conditional statement. It is used to execute a block of code only when a specific condition is met. For example,

Suppose we need to assign different grades to students based on their scores.

  • If a student scores above 90 , assign grade A
  • If a student scores above 75 , assign grade B
  • If a student scores above 65 , assign grade C

These conditional tasks can be achieved using the if statement.

  • Python if Statement

An if statement executes a block of code only if the specified condition is met.

Here, if the condition of the if statement is:

  • True - the body of the if statement executes.
  • False - the body of the if statement is skipped from execution.

Let's look at an example.

Working of if Statement

Note: Be mindful of the indentation while writing the if statements. Indentation is the whitespace at the beginning of the code.

Here, the spaces before the print() statement denote that it's the body of the if statement.

  • Example: Python if Statement

Sample Output 1

In the above example, we have created a variable named number . Notice the test condition ,

As the number is greater than 0 , the condition evaluates True . Hence, the body of the if statement executes.

Sample Output 2

Now, let's change the value of the number to a negative integer, say -5 .

Now, when we run the program, the output will be:

This is because the value of the number is less than 0 . Hence, the condition evaluates to False . And, the body of the if statement is skipped.

An if statement can have an optional else clause. The else statement executes if the condition in the if statement evaluates to False .

Here, if the condition inside the if statement evaluates to

  • True - the body of if executes, and the body of else is skipped.
  • False - the body of else executes, and the body of if is skipped

Working of if…else Statement

  • Example: Python if…else Statement

In the above example, we have created a variable named number .

Since the value of the number is 10 , the condition evaluates to True . Hence, code inside the body of if is executed.

If we change the value of the variable to a negative integer, let's say -5 , our output will be:

Here, the test condition evaluates to False . Hence code inside the body of else is executed.

  • Python if…elif…else Statement

The if...else statement is used to execute a block of code among two alternatives.

However, if we need to make a choice between more than two alternatives, we use the if...elif...else statement.

  • if condition1 - This checks if condition1 is True . If it is, the program executes code block 1 .
  • elif condition2 - If condition1 is not True , the program checks condition2 . If condition2 is True , it executes code block 2 .
  • else - If neither condition1 nor condition2 is True , the program defaults to executing code block 3 .

Working of if…elif…else Statement

  • Example: Python if…elif…else Statement

Since the value of the number is 0 , both the test conditions evaluate to False .

Hence, the statement inside the body of else is executed.

  • Python Nested if Statements

It is possible to include an if statement inside another if statement. For example,

Here's how this program works.

Working of Nested if Statement

More on Python if…else Statement

In certain situations, the if statement can be simplified into a single line. For example,

This code can be compactly written as

This one-liner approach retains the same functionality but in a more concise format.

Python doesn't have a ternary operator. However, we can use if...else to work like a ternary operator in other languages. For example,

can be written as

We can use logical operators such as and and or within an if statement.

Here, we used the logical operator and to add two conditions in the if statement.

We also used >= (comparison operator) to compare two values.

Logical and comparison operators are often used with if...else statements. Visit Python Operators to learn more.

Table of Contents

  • Introduction

Write a function to check whether a student passed or failed his/her examination.

  • Assume the pass marks to be 50 .
  • Return Passed if the student scored more than 50. Otherwise, return Failed .

Video: Python if...else Statement

Sorry about that.

Related Tutorials

Python Tutorial

Python - if, elif, else Conditions

By default, statements in the script are executed sequentially from the first to the last. If the processing logic requires so, the sequential flow can be altered in two ways:

Python uses the if keyword to implement decision control. Python's syntax for executing a block conditionally is as below:

Any Boolean expression evaluating to True or False appears after the if keyword. Use the : symbol and press Enter after the expression to start a block with an increased indent. One or more statements written with the same level of indent will be executed if the Boolean expression evaluates to True .

To end the block, decrease the indentation. Subsequent statements after the block will be executed out of the if condition. The following example demonstrates the if condition.

In the above example, the expression price < 100 evaluates to True , so it will execute the block. The if block starts from the new line after : and all the statements under the if condition starts with an increased indentation, either space or tab. Above, the if block contains only one statement. The following example has multiple statements in the if condition.

Above, the if condition contains multiple statements with the same indentation. If all the statements are not in the same indentation, either space or a tab then it will raise an IdentationError .

The statements with the same indentation level as if condition will not consider in the if block. They will consider out of the if condition.

The following example demonstrates multiple if conditions.

Notice that each if block contains a statement in a different indentation, and that's valid because they are different from each other.

else Condition

Along with the if statement, the else condition can be optionally used to define an alternate block of statements to be executed if the boolean expression in the if condition evaluates to False .

As mentioned before, the indented block starts after the : symbol, after the boolean expression. It will get executed when the condition is True . We have another block that should be executed when the if condition is False . First, complete the if block by a backspace and write else , put add the : symbol in front of the new block to begin it, and add the required statements in the block.

In the above example, the if condition price >= 100 is False , so the else block will be executed. The else block can also contain multiple statements with the same indentation; otherwise, it will raise the IndentationError .

Note that you cannot have multiple else blocks, and it must be the last block.

elif Condition

Use the elif condition is used to include multiple conditional expressions after the if condition or between the if and else conditions.

The elif block is executed if the specified condition evaluates to True .

In the above example, the elif conditions are applied after the if condition. Python will evalute the if condition and if it evaluates to False then it will evalute the elif blocks and execute the elif block whose expression evaluates to True . If multiple elif conditions become True , then the first elif block will be executed.

The following example demonstrates if, elif, and else conditions.

All the if, elif, and else conditions must start from the same indentation level, otherwise it will raise the IndentationError .

Nested if, elif, else Conditions

Python supports nested if, elif, and else condition. The inner condition must be with increased indentation than the outer condition, and all the statements under the one block should be with the same indentation.

  • Compare strings in Python
  • Convert file data to list
  • Convert User Input to a Number
  • Convert String to Datetime in Python
  • How to call external commands in Python?
  • How to count the occurrences of a list item?
  • How to flatten list in Python?
  • How to merge dictionaries in Python?
  • How to pass value by reference in Python?
  • Remove duplicate items from list in Python
  • More Python articles

python short if else assignment

We are a team of passionate developers, educators, and technology enthusiasts who, with their combined expertise and experience, create in -depth, comprehensive, and easy to understand tutorials.We focus on a blend of theoretical explanations and practical examples to encourages hands - on learning. Visit About Us page for more information.

  • Python Questions & Answers
  • Python Skill Test
  • Python Latest Articles
  • Learn Python
  • Python Lists
  • Python Dictionaries
  • Python Strings
  • Python Functions
  • Learn Pandas & NumPy
  • Pandas Tutorials
  • Numpy Tutorials
  • Learn Data Visualization
  • Python Seaborn
  • Python Matplotlib

Python If-Else Statements with Multiple Conditions

  • November 11, 2022 November 11, 2022

Conditional statements, or if-else statements, allow you to control the flow of your code. Understanding the power of if-else statements allows you to become a stronger Python programmer. This is because they allow you to execute only certain parts of your code if a condition or multiple conditions are met. In this tutorial, you’ll learn how to use Python if-else statements with multiple conditions .

By the end of this tutorial, you’ll have learned:

  • How to use Python if-else statements with multiple conditions
  • How to check if all conditions are met in Python if-else statements
  • How to check if only some conditions are met in Python if-else statemens
  • How to write complex if-else statements with multiple conditions in Python

Table of Contents

Understanding Python if-else Statements

One of the benefits of Python is how clear the syntax is. This is also true for if-else statements, which follow simple English syntax in order to control flow of your program . Python if-else statements, allow you to run code if a condition is met. They follow the syntax shown below:

To better understand how Python handles multiple conditions, it’s important to understand how logical operators work. Let’s take a look at this next.

Understanding Logical Operators in Python

While Python provides many more comparison operators , in this tutorial we’ll focus on two: and and or . These comparison operators allow us to chain multiple conditions using logical statements. To break this down:

  • and ensures that both conditions are met, otherwise returning False
  • or ensures that at least one condition must be true, otherwise returning False

Now that we’ve covered some of the basics, let’s dive into how to use multiple conditions in Python if-else statements.

Using Multiple Conditions in Python if-else Statements

In Python if-else statements, we can use multiple conditions which can be used with logical and and or operators. Let’s take a look at how we can write multiple conditions into a Python if-else statement:

We can see that the first condition uses the logical and operator to check if both conditions are true. If this isn’t met, the else block is executed. Let’s dive into how these operators work in action.

Checking For Multiple Conditions to be True in Python if-else Statements

We can use Python if-else statements to check that all conditions are true by using one or more and statements. This allows us to check that every condition is true. If a single condition is not true, then the flow statement moves onto the next condition.

Let’s see how we can check if multiple conditions are true in Python:

Let’s break down what the code block above is doing:

  • A variable, age , is defined with the value 32
  • An if-else statement first checks if the age is 0 or older and less than 20. If either of these arent true, the next block is checked.
  • The elif statement checks if the age is between 20 and 30. If this isn’t true, the else block is executed

With and conditions, Python will check each item sequentially. If one condition is not true, Python will not need to check the others and move onto the next block.

This is actually the same as running the all() function in a block, which will check if all items that are passed into the function are True. We could rewrite the if-else statement above using the all() function, as shown below:

Checking For Some Conditions to be True in Python if-else Statements

The Python or operator can be used to check if only one condition is true. This can allow you to write programs which can, for example, check if a weekday is a weekend day or not. This can allow us to check if a value passed meets either condition. Let’s see what this looks like:

In the code block above, we wrote an if-else block that checks whether the weekday we passed in is either Saturday or Sunday. If neither of these conditions evaluate to be true, the else block is executed.

This is actually the same as using the Python any() function, which will check if any of the items passed in are true. Let’s see how we can re-write our if-else block using the any() function:

In the next section, you’ll learn how to write complex if-else statements that combine and and or in creative ways.

Writing Complex if-else Statements with Multiple Conditions

We can write complex if-else statements with multiple conditions that combine using and and or operators. This can be very helpful when you’re writing complex conditional code that allows for some conditions to be true, while enforcing others.

Let’s take a look at an example of how this works:

In the code block above, we wrap the or statement in brackets. This means that this or condition only applies to the code in the brackets. Following that, Python will check if the user is active.

Let’s take a look at what this conditional flow looks like:

  • Since age is 67, the code in the brackets will evaluate to True , since it meets the age >= 65 condition.
  • Python then checks if the user is active, which evaluates to True as well

By doing this, Python allows you write complex conditions. By combining and and or operators, you can write if-else statements without nesting your conditions.

In this tutorial, you learned how to write complex if-else statements with multiple conditions. Python if-else statements allow you to control the flow of your code. By using multiple conditions, you can write more sophisticated code.

You first learned how to check if all conditions were true, using the and operator. Then, you learned how to check if any conditions were true, using the or operator. Finally, you learned how to write complex if-else statements by combining and and or .

Additional Resources

To learn more about related topics, check out the tutorials below:

  • NumPy where: Process Array Elements Conditionally
  • Python While Loop with Multiple Conditions
  • Python if-else statements: Official Documentation

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials. View Author posts

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries
  • CBSE Class 11 Informatics Practices Syllabus 2023-24
  • CBSE Class 11 Information Practices Syllabus 2023-24 Distribution of Marks
  • CBSE Class 11 Informatics Practices Unit-wise Syllabus
  • Unit 1:Introduction to Computer System
  • Introduction to Computer System
  • Evolution of Computer
  • Computer Memory
  • Unit 2:Introduction to Python
  • Python Keywords
  • Identifiers
  • Expressions
  • Input and Output
  • if else Statements
  • Nested Loops
  • Working with Lists and Dictionaries
  • Introduction to List
  • List Operations
  • Traversing a List
  • List Methods and Built in Functions
  • Introduction to Dictionaries
  • Traversing a Dictionary
  • Dictionary Methods and Built-in Functions
  • Unit 3 Data Handling using NumPy
  • Introduction
  • NumPy Array
  • Indexing and Slicing
  • Operations on Arrays
  • Concatenating Arrays
  • Reshaping Arrays
  • Splitting Arrays
  • Saving NumPy Arrays in Files on Disk
  • Unit 4: Database Concepts and the Structured Query Language
  • Understanding Data
  • Introduction to Data
  • Data Collection
  • Data Storage
  • Data Processing
  • Statistical Techniques for Data Processing
  • Measures of Central Tendency
  • Database Concepts
  • Introduction to Structured Query Language
  • Structured Query Language
  • Data Types and Constraints in MySQL
  • CREATE Database
  • CREATE Table
  • DESCRIBE Table
  • ALTER Table
  • SQL for Data Manipulation
  • SQL for Data Query
  • Data Updation and Deletion
  • Unit 5 Introduction to Emerging Trends
  • Artificial Intelligence
  • Internet of Things
  • Cloud Computing
  • Grid Computing
  • Blockchains
  • Class 11 IP Syllabus Practical and Theory Components

Python If Else Statements – Conditional Statements

In both real life and programming, decision-making is crucial. We often face situations where we need to make choices, and based on those choices, we determine our next actions. Similarly, in programming, we encounter scenarios where we must make decisions to control the flow of our code.

Conditional statements in Python play a key role in determining the direction of program execution. Among these, If-Else statements are fundamental, providing a way to execute different blocks of code based on specific conditions. As the name suggests, If-Else statements offer two paths, allowing for different outcomes depending on the condition evaluated.

Types of Control Flow in Python

Python If Statement

Python if else statement, python nested if statement, python elif, ternary statement | short hand if else statement.

The if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not.

Flowchart of If Statement

Let’s look at the flow of code in the Python If statements.

Flowchart of Python if statement

Flowchart of Python if statement

Syntax of If Statement in Python

Here, the condition after evaluation will be either true or false. if the statement accepts boolean values – if the value is true then it will execute the block of statements below it otherwise not.

As we know, Python uses indentation to identify a block. So the block under the Python if statements will be identified as shown in the below example:  

Example of Python if Statement

As the condition present in the if statements in Python is false. So, the block below the if statement is executed.

The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But if we want to do something else if the condition is false, we can use the else statement with the if statement Python to execute a block of code when the Python if condition is false. 

Flowchart of If Else Statement

Let’s look at the flow of code in an if else Python statement.

ezgifcom-optijpeg

Syntax of If Else in Python

Example of python if else statement.

The block of code following the else if in Python, the statement is executed as the condition present in the if statement is false after calling the statement which is not in the block(without spaces).

If Else in Python using List Comprehension

In this example, we are using an Python else if statement in a list comprehension with the condition that if the element of the list is odd then its digit sum will be stored else not.

A nested if is an if statement that is the target of another if statement. Nested if statements mean an if statement inside another if statement.

Yes, Python allows us to nest if statements within if statements. i.e., we can place an if statement inside another if statement.

Flowchart of Python Nested if Statement

Flowchart of Python Nested if statement

Flowchart of Python Nested if statement

Example of Python Nested If Statement

In this example, we are showing nested if conditions in the code, All the If condition in Python will be executed one by one.

Here, a user can decide among multiple options. The if statements are executed from the top down.

As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final “else” statement will be executed.

Flowchart of Elif Statement in Python

Let’s look at the flow of control in if-elif-else ladder:

python short if else assignment

Flowchart of if-elif-else ladder

Example of Python if-elif-else ladder

In the example, we are showing single if in Python, multiple elif conditions, and single else condition.

Whenever there is only a single statement to be executed inside the if block then shorthand if can be used. The statement can be put on the same line as the if statement. 

Example of Python If shorthand

In the given example, we have a condition that if the number is less than 15, then further code will be executed.

Example of Short Hand If Else Statements

This can be used to write the if-else statements in a single line where only one statement is needed in both the if and else blocks. 

In the given example, we are printing True if the number is 15, or else it will print False.

Similar Reads:

  • Python3 – if , if..else, Nested if, if-elif statements
  • Using Else Conditional Statement With For loop in Python
  • How to use if, else & elif in Python Lambda Functions

Please Login to comment...

Similar reads.

  • python-basics

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Advertisement

The Crystal Story Box | Ep. 250

Copy the code below to embed the wbur audio player on your site.

<iframe width="100%" height="124" scrolling="no" frameborder="no" src="https://player.wbur.org/circleround/2024/05/28/the-crystal-story-box"></iframe>

  • Rebecca Sheir

An ant holds a colorful bag overhead. (Sabina Hahn for WBUR)

Do you have a favorite story?

If so, what makes it your favorite? Does it have fascinating characters? A twisty-turny plot? Perhaps it tickles your funny bone or tugs at your heart.

We’re about to return to a time when the world didn’t have stories… until a sly little spider gave all of us a tale to tell!

Our story is called "The Crystal Story Box.” Versions of this legend originally come from the Ashanti people of Ghana in West Africa, and feature a trickster you’ve met in several other Circle Round stories, including “ The Magic Bowl ,” “ The Perfect Partnership ” and “ Pulling Strings ”: Anansi!

Voices in this episode include Ryan Dalusung, Shawn Richardz, Dawn Ursula and Bashir Salahuddin. Comedian, writer and actor Bashir Salahuddin co-created and co-stars in “South Side” on Max. He also appears as “Hondo” in the blockbuster film, “Top Gun: Maverick,” and as Anansi in the above-mentioned Circle Round episode, “Pulling Strings”!

This episode was adapted for Circle Round by Rebecca Sheir. It was edited by Sofie Kodner. Original music and sound design is by Eric Shimelonis. Our artist is Sabina Hahn.

A black-and-white image of an ant holding a bag overhead. (Sabina Hahn for WBUR)

GROWN-UPS! PRINT THIS so everyone can color while listening. We’re also keeping an album so please share your picture on Facebook and Instagram , and tag it with #CircleRoundPodcast. To access all the coloring pages for past episodes click HERE. Our resident artist is Sabina Hahn and you can learn more about her HERE.

Now it’s your turn!

Believe it or not, this story marks the grand finale of Circle Round’s seventh season! Now that we have 250 episodes under our belt, we want to know:

What’s your favorite Circle Round story? 

If you fast-forward to the end of this or any other Circle Round episode, you’ll hear a montage of listeners talking about their favorite Circle Round tales… and you can be one of them!

Grown-ups: grab a smartphone, open the Voice Memo app, hit record, and have your Circle round fan say their name, location, and favorite Circle Round story. When you’re done, email the sound file to [email protected] . We may feature your recording at the end of a future Circle Round episode!

Musical Spotlight: Talking Drum

Eric Shimelonis plays the talking drum, which has been used not just to play music, but to transmit messages! (courtesy of Rebecca Sheir)

When you play this hourglass-shaped drum from West Africa, you can change its pitch so that it sounds like – you guessed it – a person talking!

The talking drum’s two drumheads are connected by leather tension cords. You squeeze the cords between your arm and body to modulate the drum’s pitch. Experienced players can vary the pitch to mimic the sound, volume and rhythm of human speech.

Hourglass-shaped talking drums are some of the oldest instruments used by West African storytellers called griots . You’ll also find variations on talking drums in East Africa, Melanesia (a region in the southwest Pacific comprising the countries of Fiji, Vanuatu, Solomon Islands and Papua New Guinea) and Southeast Asia.

Story Transcript:

NARRATOR: Long, long ago… back in the earliest of times… the earth contained mountains and valleys, rivers and oceans, animals and people.

One thing it did NOT contain… was stories.

You see, every single story – every tale… every yarn… every mystery, fable, and myth – was kept locked in a crystal box high above the clouds way up in the Sky Kingdom: the heavenly, celestial realm of Sky Goddess.

So, you may ask… if everyone on earth knew about Sky Goddess’s crystal box, why didn’t they venture up to the Sky Kingdom? And ask Sky Goddess to let the stories go free?

Well, maybe because they all knew what the answer would be.

SKY GODDESS: (outraged, mocking) “Let the stories go free”!???? I will NEVER let the stories go free! They’re far too precious for you earth-bound beings. The stories shall remain up here, in the Sky Kingdom! FOREVER!

NARRATOR: But then… along came Anansi the spider.

Anansi loved weaving webs – and not just sticky webs made from strong, stretchy silk. Anansi loved weaving webs… of deception! The shrewd, cunning fellow lived by his wits – and was so clever, so resourceful, he could trick almost anyone into doing almost anything.

ANANSI: …But can I trick a heavenly deity like Sky Goddess into giving up the box of stories? I mean, don’t get me wrong. I’m GOOD… but I’m not DIVINE. (beat) Still. There must be SOME way I can use my wits to free the stories from Sky Goddess’s clutches. There MUST!

NARRATOR: So Anansi spun a strong, sticky web all the way from the earth to the sky. After wiggling his way through the clouds, he found himself face to face… with Sky Goddess.

SKY GODDESS: Anansi! What brings you all the way up to my Sky Kingdom?

ANANSI: Well, Sky Goddess... I have journeyed here to humbly ask for something. (beat) I have come to ask… for the crystal box of stories .

NARRATOR: Sky Goddess felt a rush of outrage. How dare this itty-bitty arachnid march up here and make such a demand!

So, she decided she would teach him a lesson. 

SKY GODDESS: Listen, Anansi. I will give you the crystal box of stories.

ANANSI: You will???

SKY GODDESS: I WILL! But only if YOU give ME something first. How about we make… a TRADE?

NARRATOR: Anansi flashed Sky Goddess a grin.

ANANSI : Sure thing, Sky Goddess! I’ll give you whatever you want. You name it, it’s yours.

SKY GODDESS: Very well then. I want you to give me…

NARRATOR: A sneaky smile crossed Sky Goddess's face.

SKY GODDESS : (dramatic) … Python.

NARRATOR : Anansi’s mouth dropped open. His heart hammered so hard in his abdomen, he could feel it in his thorax.

ANANSI : (nervous) Ummmm… I’m sorry, Sky Goddess. Did I hear you right? Do you really want me to give you… Python??? As in, the super-massive snake who squeezes the life out of her victims before swallowing them whole?

SKY GODDESS : That’s the one! (beat) And if you really want that box of stories, Anansi, you must bring me what I ask. (beat) Now GET TO IT!

NARRATOR: As Anansi lowered himself back to earth, he wasn’t sure which was spinning faster: his thread or his mind!

ANANSI: Python?!? How can I possibly bring Sky Goddess PYTHON? I mean, it’s clear I’m no match for that mammoth reptile in physical strength… so I’ll have to use my MENTAL strength. But how?

NARRATOR: Anansi thought and thought. And by the time he was back on solid ground, he had come up with a plan.

ANANSI: A-ha!!!

NARRATOR: Running as fast as his eight legs could go, Anansi scuttled into the thick, tangled forest. He found a long tree branch and some twisty vines, then he dragged them to the river. He knew Python often came to the water’s edge for a drink. And indeed, there was the giant snake, coiled up on the bank, lapping at the water with her flickering tongue.

PYTHON: (ad-lib lapping up water in river)

NARRATOR: Anansi drew in a breath, then spoke out in an extra-loud voice.

ANANSI: Ya know… Now that I think of it… maybe my friends were RIGHT! Maybe Python ISN’T that LONG after all!

NARRATOR: Python ceased her drinking. She lifted her enormous, diamond-shaped head and flicked it in Anansi’s direction.

PYTHON: (annoyed, angry, suspicious) WHAT did you say, Anansi????

NARRATOR: Anansi shrugged.

ANANSI: I said… maybe you AREN’T that LONG after all! (beat) You see this tree branch here?

NARRATOR: He pointed to the long branch. Python rolled her slitted eyes.

PYTHON: Of course I see the tree branch! We snakes don’t have the best eyesight, but that branch is so long I couldn’t possibly miss it!

ANANSI: And that’s the thing! I was talking with some friends, and THEY said this tree branch is SO long, it MUST be longer than YOU!

PYTHON: Longer than ME???

NARRATOR: Just as Anansi had hoped, the mighty snake’s pride was wounded.

PYTHON: How dare your friends sling about such insults? Don’t they know that I am the greatest snake in the land??? If not the WORLD??? I’m so big I could swallow all of your friends whole! After squeezing the life out of them, of course.

NARRATOR: Anansi suppressed a shudder.

ANANSI: That’s exactly what I told them, Python! But they wouldn’t listen to me. (beat) Gosh. If only there was some way to prove my silly friends wrong!

NARRATOR: Python’s face lit up.

PYTHON: But there IS a way! Place that tree branch on the ground, and I shall lie down beside it. I will stretch my prodigious body as long as it will go, then you can witness how puny the branch is in comparison! And you can tell your foolish friends!

NARRATOR: Anansi’s heart skipped a beat.

ANANSI: What a terrific idea, Python! I don’t know how I didn’t think of it myself! I’ll lay the branch right here, and we’ll see how you measure up!

NARRATOR: Python grinned, revealing a set of needle-sharp teeth. Then she slithered over to the tree branch and unfurled her hefty body beside it.

PYTHON: Well, Anansi? Which is longer: the branch or me?

NARRATOR: Anansi frowned.

ANANSI: Actually… I’m not sure! Your head and tail keep curling up. So I can’t tell how long you TRULY are! (beat) I’ll tell you what.

NARRATOR: He reached for the vines he had taken from the forest.

ANANSI: I’ll use these vines to tie you to the branch. That way, your body will be perfectly straight!

NARRATOR: Anansi set to work weaving the vines over and over, around and around, until Python’s scaly body was perfectly straight… and perfectly stuck!

PYTHON: Well…? Am I longer than the branch or not? What have you learned?

ANANSI: ‘What have I learned’...???

NARRATOR: Anansi beamed.

ANANSI: I’ve learned that a tiny critter like me can outwit a colossal creature like you – if he plays his cards right!

NARRATOR: Quick as a wink, he spun a thick layer of thread around Python’s tied-up body, from the tip of her tail to the top of her head. Then he wove another web, caught a strong wind, and carried the gargantuan snake all the way up to the Sky Kingdom… where Sky Goddess was so stunned she could hardly speak.

SKY GODDESS: Anansi??! You…! You’re…! You’re back!

ANANSI: That I AM, Sky Goddess! And as you can see, I’ve brought you what you asked for. So now it’s time for YOU to give ME what I asked for! The crystal box of stories!

NARRATOR: Sky Goddess gave Anansi a long stare. This slight little spider was more clever than she thought! Clearly she’d have to try a different tack.

SKY GODDESS: (thinking fast) Well… The thing is… I’ve given the matter some more thought. And I now realize that my box of stories is so valuable, so precious, it should come at a far greater price than just one silly snake. (beat) No offense, Python!

PYTHON: (downtrodden) None taken.

SKY GODDESS: (beat) Therefore, Anansi… I need you to bring me something else . (beat) (dramatic as we go to the break on a cliffhanger) And look out, my web-slinging friend. Because THIS one may very well STING!

NARRATOR: What will Sky Goddess ask Anansi to deliver next?

We’ll find out, after a quick break.

NARRATOR: Welcome back to Circle Round. I’m Rebecca Sheir. Today our story is called “The Crystal Story Box.”

Before the break, Sky Goddess was hoarding all the world’s stories in a crystal box in her Sky Kingdom.

Anansi the spider spun a web to the clouds and demanded that Sky Goddess give the box to him, so that he could bring it to earth. But the crafty, possessive deity wasn’t about to give up her precious stories. So she offered Anansi a seemingly impossible trade: the stories… for Python.

Ever the trickster, Anansi used his wits to capture the proud, vain snake and bring her to Sky Goddess. So the astonished, annoyed deity gave Anansi another assignment.

SKY GODDESS: I need you to bring me… Hornet.

NARRATOR: A shiver coursed through Anansi’s body. He began trembling so hard all eight of his knees knocked together.

ANANSI : (nervous) Ummmm… Sky Goddess? Did I hear you right? Do you really want me to give you… Hornet? As in, the big angry wasp with a stinger so sharp, it’s like a red-hot poker that would render a spider like me motionless? Paralyze me completely?

SKY GODDESS : That’s the one! (beat) But if you really want that box of stories, you must bring me what I ask. (beat) Now get to it!

NARRATOR: Once more, Anansi’s thread AND brain were spinning as he lowered back down to earth.

ANANSI: Well, I can’t do what I did with Python and wrap Hornet in vines; that buzzing, blustering critter will slip right through… and then he’ll be so furious, he’ll sting me! But there must be some way I can use my wits to catch him. But HOW?

NARRATOR: Anansi pondered and pondered. And by the time his eight feet touched the ground, he knew exactly what he would do.

NARRATOR: Once again, he set off through the tangled forest, this time in search of the smooth, round gourd known as… a calabash. Once he found one, he set to work scooping out the flesh and seeds. Then he filled the hollowed-out calabash with water, and scurried to the top of the tree where Hornet kept his hive.

As Anansi peered down through the branches, he couldn’t see Hornet. But he could see his hive , and he could hear Hornet buzzing around inside of it.

Quickly, Anansi took some water from the calabash and sprinkled it all over his body. Then he turned the calabash over, and poured the rest of the water onto the hive below!

HORNET: (mad) Jeeperzzzz and gee whizzzzz!

NARRATOR: Just as Anansi expected, Hornet came zipping out. He was as wet as a sponge and as mad as a… well… as mad as a hornet.

HORNET: (angry) Izzzzz the sky falling???? Becauzzzzze my hive izzzzz oozzzzzzing with water!

ANANSI: (calling down) It was a sudden storm, Hornet! It got me too. Look at me! I’m drenched! (beat) And I hear there’s another storm on the way!

NARRATOR: Hornet darted up to Anansi.

HORNET: Izzzzz that true, Anansi? Izzzz another storm coming in? (beat) Tell me quick — before I paralyzzzzzzze you with my stinger!

NARRATOR: Anansi swallowed hard, then forced his face into a smile.

ANANSI: Well, Hornet – if another storm does come in, that hive of yours isn’t going to do you much good. So how about you fly inside my calabash here? It’s big and hollow and completely water-proof!

NARRATOR: Hornet didn’t hesitate. He shook the water off his body, then made a beeline – or “hornet” line? – for the calabash.

Once he was inside, Anansi grabbed some leaves, plugged the gourd’s mouth, then spun a sticky thread around it. Next, he wove another web, caught a gentle breeze, and carried the calabash all the way up to the Sky Kingdom.

When Sky Goddess saw the calabash, and heard Hornet buzzing around inside it, she was more shocked than ever!

SKY GODDESS: (so stunned she can’t finish a sentence) Anansi!! You…! You…!

ANANSI: (relishing finishing her sentence) …I brought you Hornet? I sure did!

SKY GODDESS: (so stunned she can’t finish a sentence) But you… you’re…!

ANANSI: (relishing finished her sentence) …I am “amazing”...? That’s awfully high praise – especially coming from you, Sky Goddess! But I’ll take it. I’ll also take what you promised you’d give me. The crystal box of stories! 

NARRATOR: Sky Goddess was at a loss for words. Twice now she had challenged Anansi, neither time expecting the little spider to come through.

And yet… thanks to his big brains… he had.

Defeated, humbled, and nothing short of impressed, Sky Goddess fetched the crystal box of stories and handed it over.

SKY GODDESS: Anansi. My stories are now yours, to do with as you please.

ANANSI: Thank you, Sky Goddess. I promise they’ll all live happily ever after. 

NARRATOR: Anansi flashed Sky Goddess a smile, then spun another web and dove back down toward earth. On the way, he took the crystal box… held it out… and flipped it over!

Just like that, all the stories that had been locked up for so long went tumbling out of the box and down to the world below.

Happy stories, sad stories, surprising stories with twists, mysterious stories with  turns… They all scattered everywhere!

And that’s why… to this day… you and I and everyone else in the world have access to an endless number of stories that can entertain us, inspire us, make us laugh and cry, think and dream.

And we owe it all to a sly little spider who didn’t let an eensy-weensy body get in the way of an enormous mind.

Headshot of Rebecca Sheir

Rebecca Sheir Host, Circle Round Rebecca Sheir is the host "Circle Round," WBUR's kids storytelling podcast.

More from Circle Round

IMAGES

  1. Python if, if...else Statement (With Examples)

    python short if else assignment

  2. if else Statement in Python

    python short if else assignment

  3. How to Use If Else Statements in Python?

    python short if else assignment

  4. How to Use If Else Statements in Python?

    python short if else assignment

  5. The if-else Statement in Python

    python short if else assignment

  6. If Else Function In Python

    python short if else assignment

VIDEO

  1. python assign multiple value #shorts #python #assignment #multiple #value #pythonprogramming

  2. 12. Python Assignment Operators #shorts #beginners #phython #python #coding #pythonlearning

  3. python short introduction #python #introduction #programinglanguage #shortvideo #youtubevideo

  4. Python Snippets : Short & Precise Programs

  5. Class 8 (Nested If else & Assignment)

  6. 3#Assignment Operators in Python #pythonprogramming #computerlanguage

COMMENTS

  1. Python if-else short-hand

    The most readable way is. x = 10 if a > b else 11. but you can use and and or, too: x = a > b and 10 or 11. The "Zen of Python" says that "readability counts", though, so go for the first way. Also, the and-or trick will fail if you put a variable instead of 10 and it evaluates to False. However, if more than the assignment depends on this ...

  2. python

    One should not use this approach if looping through large data sets since it introduces an unnecessary assignment in case we end up in the else-statement. - dapc. Dec 12, 2019 at 9:23. Add a comment | ... Python statement of short 'if-else' 11. one line if else condition in python. 2. single line if statement - Python ...

  3. Mastering Python's If-Else Shorthand

    Python's if-else shorthand is a concise way of writing conditional statements. The syntax of if-else shorthand is as follows: The condition is evaluated first, and if it is True, the expression value_if_true is returned. If the condition is False, the expression value_if_false is returned. This shorthand can be used as a replacement for the ...

  4. Python If Else shorthand with examples

    In this article, we will see how to write Shorthands for if else statements in Python. Simple if condition. We can write a simple if condition in Python as shown below: 1 x = 10. 2 if x > 5: 3 print ("greater than 5") There are no shorthands for simple if statements. If else statements. Consider the following if else statement: 1 x = 10.

  5. Python if-else Shorthand

    There have been many shorthand notations that we have been using so far in Python. Let us take the example of the assignment operators. The expression a=a+b becomes a+=b; similarly, a=a/b becomes a/=b, and many more. Similar to such shorthand notations in Python, we have one more notation known as a ternary operator for the if-else statement in ...

  6. Shorthand syntax for if/else in Python (conditional expression)

    Nested shorthand if/else/elif. The shorthand syntax can also be nested to create a shorthand elif statement, but this is not recommended as it reduces readability and may cause errors. The syntax for a nested shorthand if/else/elif in Python is: value_if_true_1 if condition_1 else value_if_true_2 if condition_2 else value_if_false.

  7. Python shorthand if

    Shorthand if is a way to write if statements more concisely and readable. It's also known as the ternary operator or conditional expression. The syntax for shorthand if is as follows: The expression is the condition that you want to test. The value_if_true is the value assigned to a variable if the expression is true.

  8. Conditional Statements in Python

    In the form shown above: <expr> is an expression evaluated in a Boolean context, as discussed in the section on Logical Operators in the Operators and Expressions in Python tutorial. <statement> is a valid Python statement, which must be indented. (You will see why very soon.) If <expr> is true (evaluates to a value that is "truthy"), then <statement> is executed.

  9. Python If Else Shorthand

    Python is known for its easy-to-understand syntax and precise code. Be it loops or conditional statements like if-else, we can always cut down on the lines of code in Python. Python If-else shorthand is one such method to make those conditional statements more readable and to the point. We can also say that the Python if-else shorthand is like ...

  10. Python Shorthandf If Else

    Example Get your own Python Server. One line if else statement: a = 2. b = 330. print("A") if a > b else print("B") Try it Yourself ». You can also have multiple else statements on the same line:

  11. Mastering Python's If-Else Shorthand

    Example code snippet of nested if-else shorthand. Here's an example code snippet that demonstrates Python's nested if-else shorthand: x = 10. y = 5. z = 0. result = "x is greater than y" if x ...

  12. Python if-else Statements

    The output of this code will be 20, as y is greater than x. This approach simplifies the code and improves readability for straightforward conditional assignments. Short Hand if-else Statement. The short-hand if-else statement in Python, also known as the ternary operator, allows for concise decision-making in a single line.

  13. Python Conditional Assignment (in 3 Ways)

    Using an if-else statement, we can assign a value to a variable based on the condition we provide. Here is an example of replacing the above code snippet with the if-else statement. a = 10 b = 20 # assigning value to variable c based on condition if a > b: c = a else: c = b print(c) # output: 20 3. Using Logical Short Circuit Evaluation

  14. Conditional Statements

    In its simplest form, a conditional statement requires only an if clause. else and elif clauses can only follow an if clause. # A conditional statement consisting of # an "if"-clause, only. x = -1 if x < 0: x = x ** 2 # x is now 1. Similarly, conditional statements can have an if and an else without an elif:

  15. 12 Python if else Exercises for Beginners

    The condition can be any expression that evaluates to either True or False.For example, you can use comparison operators (==, !=, <, >, <=, >=) or logical operators (and, or, not) to create conditions.The code inside the if block will be executed only if the condition is True, otherwise the code inside the else block will be executed.. You can also use the elif keyword to add more conditions ...

  16. Python if, if...else Statement (With Examples)

    Python if Statement. An if statement executes a block of code only if the specified condition is met.. Syntax. if condition: # body of if statement. Here, if the condition of the if statement is: . True - the body of the if statement executes.; False - the body of the if statement is skipped from execution.; Let's look at an example. Working of if Statement

  17. Python

    In the above example, the elif conditions are applied after the if condition. Python will evalute the if condition and if it evaluates to False then it will evalute the elif blocks and execute the elif block whose expression evaluates to True.If multiple elif conditions become True, then the first elif block will be executed.. The following example demonstrates if, elif, and else conditions.

  18. Python If-Else Statements with Multiple Conditions • datagy

    Let's take a look at how we can write multiple conditions into a Python if-else statement: # Using Multiple Conditons in Python if-else val1 = 2 val2 = 10 if val1 % 2 == 0 and val2 % 5 == 0: print ("Divisible by 2 and 5.") else: print ("Not divisible by both 2 and 5.") # Returns: Divisible by 2 and 5. We can see that the first condition uses ...

  19. Python If Else Statements

    This can be used to write the if-else statements in a single line where only one statement is needed in both the if and else blocks. Syntax: statement_when_True if condition else statement_when_False. In the given example, we are printing True if the number is 15, or else it will print False. Python.

  20. Python statement of short 'if-else'

    The first line makes use of Python's version of a "ternary operator" available since version 2.5, though the Python documentation refers to it as Conditional Expressions. The second line is a little hack to provide inline functionality in many (all of the important) ways equivalent to ?: found in many other languages (such as C and C++ ).

  21. The Crystal Story Box

    PYTHON: Of course I see the tree branch! We snakes don't have the best eyesight, but that branch is so long I couldn't possibly miss it! We snakes don't have the best eyesight, but that ...

  22. Is there any shorthand if statement in python? (Be specific I didn't

    Python statement of short 'if-else' 0. Python if-or statement short hand. 1. Can I write an if else statement in one line in Python? 0. Python shorthand using only if, excluding the else part. 1. Python one-liner if else statement. 0. Is there any alternative to repetitive if statements in python. 2.