Conditional Statements in Python

Conditional Statements in Python

Table of Contents

Introduction to the if Statement

Python: it’s all about the indentation, what do other languages do, which is better, the else and elif clauses, one-line if statements, conditional expressions (python’s ternary operator), the python pass statement.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Conditional Statements in Python (if/elif/else)

From the previous tutorials in this series, you now have quite a bit of Python code under your belt. Everything you have seen so far has consisted of sequential execution , in which statements are always performed one after the next, in exactly the order specified.

But the world is often more complicated than that. Frequently, a program needs to skip over some statements, execute a series of statements repetitively, or choose between alternate sets of statements to execute.

That is where control structures come in. A control structure directs the order of execution of the statements in a program (referred to as the program’s control flow ).

Here’s what you’ll learn in this tutorial: You’ll encounter your first Python control structure, the if statement.

In the real world, we commonly must evaluate information around us and then choose one course of action or another based on what we observe:

If the weather is nice, then I’ll mow the lawn. (It’s implied that if the weather isn’t nice, then I won’t mow the lawn.)

In a Python program, the if statement is how you perform this sort of decision-making. It allows for conditional execution of a statement or group of statements based on the value of an expression.

The outline of this tutorial is as follows:

  • First, you’ll get a quick overview of the if statement in its simplest form.
  • Next, using the if statement as a model, you’ll see why control structures require some mechanism for grouping statements together into compound statements or blocks . You’ll learn how this is done in Python.
  • Lastly, you’ll tie it all together and learn how to write complex decision-making code.

Ready? Here we go!

Take the Quiz: Test your knowledge with our interactive “Python Conditional Statements” quiz. You’ll receive a score upon completion to help you track your learning progress:

Interactive Quiz

Test your understanding of Python conditional statements

We’ll start by looking at the most basic type of if statement. In its simplest form, it looks like this:

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. If <expr> is false, then <statement> is skipped over and not executed.

Note that the colon ( : ) following <expr> is required. Some programming languages require <expr> to be enclosed in parentheses, but Python does not.

Here are several examples of this type of if statement:

Note: If you are trying these examples interactively in a REPL session, you’ll find that, when you hit Enter after typing in the print('yes') statement, nothing happens.

Because this is a multiline statement, you need to hit Enter a second time to tell the interpreter that you’re finished with it. This extra newline is not necessary in code executed from a script file.

Grouping Statements: Indentation and Blocks

So far, so good.

But let’s say you want to evaluate a condition and then do more than one thing if it is true:

If the weather is nice, then I will: Mow the lawn Weed the garden Take the dog for a walk (If the weather isn’t nice, then I won’t do any of these things.)

In all the examples shown above, each if <expr>: has been followed by only a single <statement> . There needs to be some way to say “If <expr> is true, do all of the following things.”

The usual approach taken by most programming languages is to define a syntactic device that groups multiple statements into one compound statement or block . A block is regarded syntactically as a single entity. When it is the target of an if statement, and <expr> is true, then all the statements in the block are executed. If <expr> is false, then none of them are.

Virtually all programming languages provide the capability to define blocks, but they don’t all provide it in the same way. Let’s see how Python does it.

Python follows a convention known as the off-side rule , a term coined by British computer scientist Peter J. Landin. (The term is taken from the offside law in association football.) Languages that adhere to the off-side rule define blocks by indentation. Python is one of a relatively small set of off-side rule languages .

Recall from the previous tutorial on Python program structure that indentation has special significance in a Python program. Now you know why: indentation is used to define compound statements or blocks. In a Python program, contiguous statements that are indented to the same level are considered to be part of the same block.

Thus, a compound if statement in Python looks like this:

Here, all the statements at the matching indentation level (lines 2 to 5) are considered part of the same block. The entire block is executed if <expr> is true, or skipped over if <expr> is false. Either way, execution proceeds with <following_statement> (line 6) afterward.

Python conditional statement

Notice that there is no token that denotes the end of the block. Rather, the end of the block is indicated by a line that is indented less than the lines of the block itself.

Note: In the Python documentation, a group of statements defined by indentation is often referred to as a suite . This tutorial series uses the terms block and suite interchangeably.

Consider this script file foo.py :

Running foo.py produces this output:

The four print() statements on lines 2 to 5 are indented to the same level as one another. They constitute the block that would be executed if the condition were true. But it is false, so all the statements in the block are skipped. After the end of the compound if statement has been reached (whether the statements in the block on lines 2 to 5 are executed or not), execution proceeds to the first statement having a lesser indentation level: the print() statement on line 6.

Blocks can be nested to arbitrary depth. Each indent defines a new block, and each outdent ends the preceding block. The resulting structure is straightforward, consistent, and intuitive.

Here is a more complicated script file called blocks.py :

The output generated when this script is run is shown below:

Note: In case you have been wondering, the off-side rule is the reason for the necessity of the extra newline when entering multiline statements in a REPL session. The interpreter otherwise has no way to know that the last statement of the block has been entered.

Perhaps you’re curious what the alternatives are. How are blocks defined in languages that don’t adhere to the off-side rule?

The tactic used by most programming languages is to designate special tokens that mark the start and end of a block. For example, in Perl blocks are defined with pairs of curly braces ( {} ) like this:

C/C++, Java , and a whole host of other languages use curly braces in this way.

Perl conditional statement

Other languages, such as Algol and Pascal, use keywords begin and end to enclose blocks.

Better is in the eye of the beholder. On the whole, programmers tend to feel rather strongly about how they do things. Debate about the merits of the off-side rule can run pretty hot.

On the plus side:

  • Python’s use of indentation is clean, concise, and consistent.
  • In programming languages that do not use the off-side rule, indentation of code is completely independent of block definition and code function. It’s possible to write code that is indented in a manner that does not actually match how the code executes, thus creating a mistaken impression when a person just glances at it. This sort of mistake is virtually impossible to make in Python.
  • Use of indentation to define blocks forces you to maintain code formatting standards you probably should be using anyway.

On the negative side:

  • Many programmers don’t like to be forced to do things a certain way. They tend to have strong opinions about what looks good and what doesn’t, and they don’t like to be shoehorned into a specific choice.
  • Some editors insert a mix of space and tab characters to the left of indented lines, which makes it difficult for the Python interpreter to determine indentation levels. On the other hand, it is frequently possible to configure editors not to do this. It generally isn’t considered desirable to have a mix of tabs and spaces in source code anyhow, no matter the language.

Like it or not, if you’re programming in Python, you’re stuck with the off-side rule. All control structures in Python use it, as you will see in several future tutorials.

For what it’s worth, many programmers who have been used to languages with more traditional means of block definition have initially recoiled at Python’s way but have gotten comfortable with it and have even grown to prefer it.

Now you know how to use an if statement to conditionally execute a single statement or a block of several statements. It’s time to find out what else you can do.

Sometimes, you want to evaluate a condition and take one path if it is true but specify an alternative path if it is not. This is accomplished with an else clause:

If <expr> is true, the first suite is executed, and the second is skipped. If <expr> is false, the first suite is skipped and the second is executed. Either way, execution then resumes after the second suite. Both suites are defined by indentation, as described above.

In this example, x is less than 50 , so the first suite (lines 4 to 5) are executed, and the second suite (lines 7 to 8) are skipped:

Here, on the other hand, x is greater than 50 , so the first suite is passed over, and the second suite executed:

There is also syntax for branching execution based on several alternatives. For this, use one or more elif (short for else if ) clauses. Python evaluates each <expr> in turn and executes the suite corresponding to the first that is true. If none of the expressions are true, and an else clause is specified, then its suite is executed:

An arbitrary number of elif clauses can be specified. The else clause is optional. If it is present, there can be only one, and it must be specified last:

At most, one of the code blocks specified will be executed. If an else clause isn’t included, and all the conditions are false, then none of the blocks will be executed.

Note: Using a lengthy if / elif / else series can be a little inelegant, especially when the actions are simple statements like print() . In many cases, there may be a more Pythonic way to accomplish the same thing.

Here’s one possible alternative to the example above using the dict.get() method:

Recall from the tutorial on Python dictionaries that the dict.get() method searches a dictionary for the specified key and returns the associated value if it is found, or the given default value if it isn’t.

An if statement with elif clauses uses short-circuit evaluation, analogous to what you saw with the and and or operators. Once one of the expressions is found to be true and its block is executed, none of the remaining expressions are tested. This is demonstrated below:

The second expression contains a division by zero, and the third references an undefined variable var . Either would raise an error, but neither is evaluated because the first condition specified is true.

It is customary to write if <expr> on one line and <statement> indented on the following line like this:

But it is permissible to write an entire if statement on one line. The following is functionally equivalent to the example above:

There can even be more than one <statement> on the same line, separated by semicolons:

But what does this mean? There are two possible interpretations:

If <expr> is true, execute <statement_1> .

Then, execute <statement_2> ... <statement_n> unconditionally, irrespective of whether <expr> is true or not.

If <expr> is true, execute all of <statement_1> ... <statement_n> . Otherwise, don’t execute any of them.

Python takes the latter interpretation. The semicolon separating the <statements> has higher precedence than the colon following <expr> —in computer lingo, the semicolon is said to bind more tightly than the colon. Thus, the <statements> are treated as a suite, and either all of them are executed, or none of them are:

Multiple statements may be specified on the same line as an elif or else clause as well:

While all of this works, and the interpreter allows it, it is generally discouraged on the grounds that it leads to poor readability, particularly for complex if statements. PEP 8 specifically recommends against it.

As usual, it is somewhat a matter of taste. Most people would find the following more visually appealing and easier to understand at first glance than the example above:

If an if statement is simple enough, though, putting it all on one line may be reasonable. Something like this probably wouldn’t raise anyone’s hackles too much:

Python supports one additional decision-making entity called a conditional expression. (It is also referred to as a conditional operator or ternary operator in various places in the Python documentation.) Conditional expressions were proposed for addition to the language in PEP 308 and green-lighted by Guido in 2005.

In its simplest form, the syntax of the conditional expression is as follows:

This is different from the if statement forms listed above because it is not a control structure that directs the flow of program execution. It acts more like an operator that defines an expression. In the above example, <conditional_expr> is evaluated first. If it is true, the expression evaluates to <expr1> . If it is false, the expression evaluates to <expr2> .

Notice the non-obvious order: the middle expression is evaluated first, and based on that result, one of the expressions on the ends is returned. Here are some examples that will hopefully help clarify:

Note: Python’s conditional expression is similar to the <conditional_expr> ? <expr1> : <expr2> syntax used by many other languages—C, Perl and Java to name a few. In fact, the ?: operator is commonly called the ternary operator in those languages, which is probably the reason Python’s conditional expression is sometimes referred to as the Python ternary operator.

You can see in PEP 308 that the <conditional_expr> ? <expr1> : <expr2> syntax was considered for Python but ultimately rejected in favor of the syntax shown above.

A common use of the conditional expression is to select variable assignment. For example, suppose you want to find the larger of two numbers. Of course, there is a built-in function, max() , that does just this (and more) that you could use. But suppose you want to write your own code from scratch.

You could use a standard if statement with an else clause:

But a conditional expression is shorter and arguably more readable as well:

Remember that the conditional expression behaves like an expression syntactically. It can be used as part of a longer expression. The conditional expression has lower precedence than virtually all the other operators, so parentheses are needed to group it by itself.

In the following example, the + operator binds more tightly than the conditional expression, so 1 + x and y + 2 are evaluated first, followed by the conditional expression. The parentheses in the second case are unnecessary and do not change the result:

If you want the conditional expression to be evaluated first, you need to surround it with grouping parentheses. In the next example, (x if x > y else y) is evaluated first. The result is y , which is 40 , so z is assigned 1 + 40 + 2 = 43 :

If you are using a conditional expression as part of a larger expression, it probably is a good idea to use grouping parentheses for clarification even if they are not needed.

Conditional expressions also use short-circuit evaluation like compound logical expressions. Portions of a conditional expression are not evaluated if they don’t need to be.

In the expression <expr1> if <conditional_expr> else <expr2> :

  • If <conditional_expr> is true, <expr1> is returned and <expr2> is not evaluated.
  • If <conditional_expr> is false, <expr2> is returned and <expr1> is not evaluated.

As before, you can verify this by using terms that would raise an error:

In both cases, the 1/0 terms are not evaluated, so no exception is raised.

Conditional expressions can also be chained together, as a sort of alternative if / elif / else structure, as shown here:

It’s not clear that this has any significant advantage over the corresponding if / elif / else statement, but it is syntactically correct Python.

Occasionally, you may find that you want to write what is called a code stub: a placeholder for where you will eventually put a block of code that you haven’t implemented yet.

In languages where token delimiters are used to define blocks, like the curly braces in Perl and C, empty delimiters can be used to define a code stub. For example, the following is legitimate Perl or C code:

Here, the empty curly braces define an empty block. Perl or C will evaluate the expression x , and then even if it is true, quietly do nothing.

Because Python uses indentation instead of delimiters, it is not possible to specify an empty block. If you introduce an if statement with if <expr>: , something has to come after it, either on the same line or indented on the following line.

Consider this script foo.py :

If you try to run foo.py , you’ll get this:

The Python pass statement solves this problem. It doesn’t change program behavior at all. It is used as a placeholder to keep the interpreter happy in any situation where a statement is syntactically required, but you don’t really want to do anything:

Now foo.py runs without error:

With the completion of this tutorial, you are beginning to write Python code that goes beyond simple sequential execution:

  • You were introduced to the concept of control structures . These are compound statements that alter program control flow —the order of execution of program statements.
  • You learned how to group individual statements together into a block or suite .
  • You encountered your first control structure, the if statement, which makes it possible to conditionally execute a statement or block based on evaluation of program data.

All of these concepts are crucial to developing more complex Python code.

The next two tutorials will present two new control structures: the while statement and the for statement. These structures facilitate iteration , execution of a statement or block of statements repeatedly.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About John Sturtz

John Sturtz

John is an avid Pythonista and a member of the Real Python tutorial team.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: basics python

Recommended Video Course: Conditional Statements in Python (if/elif/else)

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

python if else with assignment

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! 😊

python if else with assignment

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

  • 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:

Operation

Meaning

strictly less than

less than or equal

strictly greater than

greater than or equal

equal

not equal

object identity

not

negated object identity

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.

Python One Line Conditional Assignment

Problem : How to perform one-line if conditional assignments in Python?

Example : Say, you start with the following code.

You want to set the value of x to 42 if boo is True , and do nothing otherwise.

Let’s dive into the different ways to accomplish this in Python. We start with an overview:

Exercise : Run the code. Are all outputs the same?

Next, you’ll dive into each of those methods and boost your one-liner superpower !

Method 1: Ternary Operator

The most basic ternary operator x if c else y returns expression x if the Boolean expression c evaluates to True . Otherwise, if the expression c evaluates to False , the ternary operator returns the alternative expression y .

OperandDescription
<OnTrue>The return expression of the operator in case the condition evaluates to
<Condition>The condition that determines whether to return the <On True> or the <On False> branch.
<OnFalse>The return expression of the operator in case the condition evaluates to

Let’s go back to our example problem! You want to set the value of x to 42 if boo is True , and do nothing otherwise. Here’s how to do this in a single line:

While using the ternary operator works, you may wonder whether it’s possible to avoid the ...else x part for clarity of the code? In the next method, you’ll learn how!

If you need to improve your understanding of the ternary operator, watch the following video:

The Python Ternary Operator -- And a Surprising One-Liner Hack

You can also read the related article:

  • Python One Line Ternary

Method 2: Single-Line If Statement

Like in the previous method, you want to set the value of x to 42 if boo is True , and do nothing otherwise. But you don’t want to have a redundant else branch. How to do this in Python?

The solution to skip the else part of the ternary operator is surprisingly simple— use a standard if statement without else branch and write it into a single line of code :

To learn more about what you can pack into a single line, watch my tutorial video “If-Then-Else in One Line Python” :

If-Then-Else in One Line Python

Method 3: Ternary Tuple Syntax Hack

A shorthand form of the ternary operator is the following tuple syntax .

Syntax : You can use the tuple syntax (x, y)[c] consisting of a tuple (x, y) and a condition c enclosed in a square bracket. Here’s a more intuitive way to represent this tuple syntax.

In fact, the order of the <OnFalse> and <OnTrue> operands is just flipped when compared to the basic ternary operator. First, you have the branch that’s returned if the condition does NOT hold. Second, you run the branch that’s returned if the condition holds.

Clever! The condition boo holds so the return value passed into the x variable is the <OnTrue> branch 42 .

Don’t worry if this confuses you—you’re not alone. You can clarify the tuple syntax once and for all by studying my detailed blog article.

Related Article : Python Ternary — Tuple Syntax Hack

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills . You’ll learn about advanced Python features such as list comprehension , slicing , lambda functions , regular expressions , map and reduce functions, and slice assignments .

You’ll also learn how to:

  • Leverage data structures to solve real-world problems , like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array , shape , axis , type , broadcasting , advanced indexing , slicing , sorting , searching , aggregating , and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups , negative lookaheads , escaped characters , whitespaces, character sets (and negative characters sets ), and greedy/nongreedy operators
  • Understand a wide range of computer science topics , including anagrams , palindromes , supersets , permutations , factorials , prime numbers , Fibonacci numbers, obfuscation , searching , and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined , and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer , and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

10 if-else Practice Problems in Python

Author's photo

  • learn python
  • python programming

If you're trying to learn Python, you need to practice! These ten if-else Python practice problems provide you some hands-on experience. And don’t worry – we’ve provided full code solutions and detailed explanations!

Python is particularly good for beginners to learn. Its clear syntax can be read almost as clearly as a normal sentence. The if-else statement is a good example of this; it lets you build logic into your programs. This article will walk you through ten i f-else practice exercises in Python. Each one is specifically designed for beginners, helping you hone your understanding of if-else statements.

The exercises in this article are taken directly from our courses, including Python Basics: Part 1 . This course helps absolute beginners understand computer programming with Python; if you’ve never written a line of code, this course is a great place to start.

As the saying goes, practice makes perfect. Learning Python is no exception. As we discuss in Different Ways to Practice Python , doing online courses is a great way to practice a variety of topics. The more you practice writing code, the more comfortable and confident you'll become in your abilities. So – whether you aim to build your own software, delve into data science, or automate mundane tasks – dedicating time to practice is key.

The Python if-else Statement

Before we dive into the exercises, let's briefly discuss the workings of if-else statements in Python. An if-else statement allows your program to make decisions based on certain conditions. The syntax is straightforward:

  • You provide a condition to evaluate within the if
  • If that condition is true, the corresponding block of code is executed.
  • If the condition is false, the code within the optional else block is executed instead.

Here's a simple example:

In this example, if the value of x is greater than 5, the program will print "x is greater than 5"; otherwise, it will print "x is not greater than 5".

This concept forms the backbone of decision-making in Python programs.

To get the most benefit from this article, attempt the problems before reading the solutions. Some of these exercises will have several possible solutions, so also try to think about alternative ways to solve the same problem. Let’s get started.

10 if-else Python Practice Exercises

Exercise 1: are you tall.

Exercise: Write a program that will ask the user for their height in centimeters. Use the input() built-in function to do this. If the height is more than 185 centimeters, print the following line of code:

Explanation: This is a similar syntax to the above template example. The height variable stores the user input as an integer and tests if it’s greater than 185 cm. If so, the message is printed. Notice there is no else; this means if the height is less than or equal to 185, nothing happens.

Exercise 2: More Options

Exercise: Write a program that will ask the user the following question:

  • If the user answers y , print: Wrong! Canberra is the capital!
  • If the user answers n , print: Correct!
  • If the user answers anything else, print: I do not understand your answer!

Explanation: The if statement can be extended with an elif (i.e. else if) to check any answer that returns False to the first condition. If the elif statement also returns False , the indented block under the else is executed.

Exercise 3: Check If a Character Is in a String

Exercise: Write a program to ask the user to do the following:

  • Provide the name of a country that does not contain any lowercase a or e letters. (Use the prompt: The country is : )
  • If the user provides a correct string (i.e. one with no a or e inside it), print: You won... unless you made this name up!
  • Otherwise, print: You lost!

(By the way, possible answers include Hong Kong, Cyprus, and Togo.)

Explanation: This code prompts the user to input a country name using the built-in input() function. Then, it checks if the letters 'a' or 'e' is present in the inputted country name using the in operator. If either letter is found, it prints "You lost!". Otherwise, it prints "You won... unless you made this name up!" using the else statement.

Exercise 4: Count Letter Frequency in a String

Exercise: The letter e is said to be the most frequent letter in the English language. Count and print how many times this letter appears in the poem below:

John Knox was a man of wondrous might, And his words ran high and shrill, For bold and stout was his spirit bright, And strong was his stalwart will. Kings sought in vain his mind to chain, And that giant brain to control, But naught on plain or stormy main Could daunt that mighty soul. John would sit and sigh till morning cold Its shining lamps put out, For thoughts untold on his mind lay hold, And brought but pain and doubt. But light at last on his soul was cast, Away sank pain and sorrow, His soul is gay, in a fair to-day, And looks for a bright to-morrow. (Source: "Unidentified," in Current Opinion, July 1888)

Explanation: The solution starts by initializing a counter with the value of 0. Then a for loop is used to loop through every letter in the string variable poem. The if statement tests if the current letter is an e; if it is, the counter is incremented by 1. Finally, the result of the counter is printed. Note that there is no else needed in this solution, since nothing should happen if the letter is not an e.

Exercise 5: Format Recipes

Exercise: Anne loves cooking and she tries out various recipes from the Internet. Sometimes, though, she finds recipes that are written as a single paragraph of text. For instance:

When you're in the middle of cooking, such a paragraph is difficult to read. Anne would prefer an ordered list, like this:

  • Cut a slit into the chicken breast.
  • Stuff it with mustard, mozzarella and cheddar.
  • Secure the whole thing with rashers of bacon.
  • Roast for 20 minutes at 200C.

Write a Python script that accepts a recipe string from the user ('Paste your recipe: ') and prints an ordered list of sentences, just like in the example above.

Each sentence of both the input and output should end with a single period.

Explanation: The solution takes a recipe input from the user with input() , then iterates through each character in the recipe. Whenever it encounters a period ( '.' ), it increments a counter, adds a new line character ( '\n' ) and the incremented counter followed by a period to an ordered list. If it encounters any other character, it simply adds that character to the ordered list. Finally, it calculates the length of the counter, removes the last part of the ordered list to exclude the unnecessary counter, and prints the modified ordered list, which displays the recipe with numbered steps.

Exercise 6: Nested if Statements

Exercise: A leap year is a year that consists of 366 (not 365) days. It occurs roughly every four years. More specifically, a year is considered leap if it is either divisible by 4 but not by 100 or it is divisible by 400.

Write a program that asks the user for a year and replies with either leap year or not a leap year.

Explanation: This program takes a year from the user as input. It checks if the year is divisible by 4. If it is, it then checks if the year is divisible by 100. If it is, it further checks if the year is divisible by 400. If it is, it prints 'leap year' because it satisfies all the conditions for a leap year. This is all achieved with nesting.

If it's divisible by 4, but not by 100, or if it’s not divisible by 400, the program prints 'not a leap year'. If the year is not divisible by 100, it directly prints 'leap year' because it satisfies the basic condition for a leap year (being divisible by 4). If the year is not divisible by 4, it prints 'not a leap year'.

Exercise 7: Scrabble

Exercise: Create a function called can_build_word(letters_list, word) that takes a list of letters and a word. The function should return True if the word uses only the letters from the list.

Like in real Scrabble, you cannot use one tile twice in the same word. For example, if a list of letters contains only one 'a', ‘banana’ returns False. The function should also return False if the word contains any letters not in the list.

For example …

… should return True. On the other hand …

… should return False because there is only one 'f'.

One thing to keep in mind: Neither the provided letter list nor the word should be changed by your function. It may be tempting to remove letters from the letters list to remove the used tiles. This should not be the case. Instead, you should copy the passed list. Simply use the list() function and pass it another list:

This way we can safely operate on a copy of the list without changing the contents of the original list.

Explanation: The function starts by making a copy of the list of letters to avoid modifying the original. Then, it iterates through each letter in the word. For each letter, it checks if that letter exists in the list copy. If it does, it removes that letter from the copy, which ensures each letter is used only once.

If the letter doesn't exist in the copy of the letters list, it means the word cannot be formed using the available letters; it returns False. If all the letters in the word can be found and removed from the list copy, it means the word can indeed be formed; it returns True .

If you are looking for additional material to help you learn how to work with Python lists, our article 12 Beginner-Level Python List Exercises with Solutions has got you covered.

Exercise 8: for Loops and if Statements

Exercise: Write a program that asks for a positive integer and prints all of its divisors, one by one, on separate lines in ascending order.

A divisor is a number that divides a particular number with no remainder. For example, the divisors of 4 are 1, 2, and 4.

To check if a is a divisor of b , you can use the modulo operator %. a % b returns the remainder of dividing a by b . For example, 9 % 2 is 1 because 9 = (4 * 2) + 1, and 9 % 3 is 0 because 9 divides into 3 with no remainder. If a % b == 0 , then b is a divisor of a .

Explanation: This solution takes an input number from the user and then iterates through numbers from 1 to that input number (inclusive). For each number i in this range, it checks if the input number is divisible by i with no remainder ( number % i == 0 ). If the condition is satisfied, it means that i is a factor of the input number.

Looping is another important skill in Python. This problem could also be solved with a while loop. Take a look at 10 Python Loop Exercises with Solutions to learn more about for and while loops.

Exercise 9: if Statements and Data Structures

Exercise: Write a function named get_character_frequencies() that takes a string as input and returns a dictionary of lowercase characters as keys and the number of their occurrences as values. Ignore the case of a character.

Explanation: This function initializes an empty dictionary ( freq_dict ) to store the frequencies of characters. It iterates through each character in the input word using a for loop. Within the loop, it converts each character to lowercase using the lower() method; this ensures case-insensitive counting.

The program checks if the lowercase character is already a key in the dictionary. If it's not, it adds the character as a key and sets its frequency to 1. If it is already a key, it increments the frequency count for that character by 1 and returns the dictionary.

If you’re not familiar with how Python dictionaries work, Top 10 Python Dictionary Exercises for Beginners will give you experience working with this important data structure.

Exercise 10: if Statements and Multiple Returns

Exercise: Write a function named return_bigger(a, b) that takes two numbers and returns the bigger one. If the numbers are equal, return 0.

Explanation: When using if statements in a function, you can define a return value in the indented block of code under the if-else statement. This makes your code simpler and more readable – another great example of the clear syntax which makes Python such an attractive tool for all programmers.

Do You Want More Python Practice Exercises?

Learning anything new is a challenge. Relying on a variety of resources is a good way to get a broad background. Read some books and blogs to get a theoretical understanding, watch videos online, take advantage of the active Python community on platforms like Stack Overflow . And most importantly, do some hands-on practice. We discuss these points in detail in What’s the Best Way to Practice Python?

The Python practice exercises and solutions shown here were taken directly from several of our interactive online courses, including Python Basics Practice , Python Practice: Word Games , and Working with Strings in Python . The courses build up your skills and knowledge, giving you exposure to a variety of topics.

And if you’re already motivated to take your skills to the next level, have a go at another 10 Python Practice Exercises for Beginners with Solutions . Happy coding!

You may also like

python if else with assignment

How Do You Write a SELECT Statement in SQL?

python if else with assignment

What Is a Foreign Key in SQL?

python if else with assignment

Enumerate and Explain All the Basic Elements of an SQL Query

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.

Conditional expression (ternary operator) in Python

Python has a conditional expression (sometimes called a "ternary operator"). You can write operations like if statements in one line with conditional expressions.

  • 6. Expressions - Conditional expressions — Python 3.11.3 documentation

Basics of the conditional expression (ternary operator)

If ... elif ... else ... by conditional expressions, list comprehensions and conditional expressions, lambda expressions and conditional expressions.

See the following article for if statements in Python.

  • Python if statements (if, elif, else)

In Python, the conditional expression is written as follows.

The condition is evaluated first. If condition is True , X is evaluated and its value is returned, and if condition is False , Y is evaluated and its value is returned.

If you want to switch the value based on a condition, simply use the desired values in the conditional expression.

If you want to switch between operations based on a condition, simply describe each corresponding expression in the conditional expression.

An expression that does not return a value (i.e., an expression that returns None ) is also acceptable in a conditional expression. Depending on the condition, either expression will be evaluated and executed.

The above example is equivalent to the following code written with an if statement.

You can also combine multiple conditions using logical operators such as and or or .

  • Boolean operators in Python (and, or, not)

By combining conditional expressions, you can write an operation like if ... elif ... else ... in one line.

However, it is difficult to understand, so it may be better not to use it often.

The following two interpretations are possible, but the expression is processed as the first one.

In the sample code below, which includes three expressions, the first expression is interpreted like the second, rather than the third:

By using conditional expressions in list comprehensions, you can apply operations to the elements of the list based on the condition.

See the following article for details on list comprehensions.

  • List comprehensions in Python

Conditional expressions are also useful when you want to apply an operation similar to an if statement within lambda expressions.

In the example above, the lambda expression is assigned to a variable for convenience, but this is not recommended by PEP8.

Refer to the following article for more details on lambda expressions.

  • Lambda expressions in Python

Related Categories

Related articles.

  • Shallow and deep copy in Python: copy(), deepcopy()
  • Composite two images according to a mask image with Python, Pillow
  • OpenCV, NumPy: Rotate and flip image
  • pandas: Check if DataFrame/Series is empty
  • Check pandas version: pd.show_versions
  • Python if statement (if, elif, else)
  • pandas: Find the quantile with quantile()
  • Handle date and time with the datetime module in Python
  • Get image size (width, height) with Python, OpenCV, Pillow (PIL)
  • Convert between Unix time (Epoch time) and datetime in Python
  • Convert BGR and RGB with Python, OpenCV (cvtColor)
  • Matrix operations with NumPy in Python
  • pandas: Replace values in DataFrame and Series with replace()
  • Uppercase and lowercase strings in Python (conversion and checking)
  • Calculate mean, median, mode, variance, standard deviation in Python

Rolex Pearlmaster Replica

One line if statement in Python (ternary conditional operator)

In the real world, there are specific classifications and conditions on every action that occurs around us. A twelve-year-old person is a kid, whereas a thirteen-year-old person is a teenager. If the weather is pleasant, you can make plans for an outing. But if it isn’t, you will have to cancel your plans. These conditions control the coding world as well. You will encounter various coding problems where you will have to print the output based on some conditions.

Luckily, Python has a straightforward command and syntax to solve such kinds of problems. These are called conditional statements. So let’s begin our discussion on conditional statements, their syntax, and their applications.

Basic if Statement (Ternary Operator) 

Many programming languages have a ternary operator , which defines a conditional expression. The most common usage is to make a terse, simple dependent assignment statement. In other words, it offers a one-line code to evaluate the first expression if the condition is true; otherwise, it considers the second expression. Programming languages derived from C usually have the following syntax:

Basic if Statement

The Python BDFL (creator of Python, Guido van Rossum) rejected it as non-Pythonic since it is hard to understand for people not used to C. Moreover, the colon already has many uses in Python. So, when PEP 308 was approved, Python finally received its shortcut conditional expression:

if else

It first evaluates the condition; if it returns True , the compiler will consider expression1 to give the result, otherwise expression2 . Evaluation is lazy, so only one expression will be executed.

Let's take a look at this example:

Conditions 1

Here we have defined the age variable whose value is fifteen. Now we use the if-else command to print if the kid is an adult or not. The condition for being an adult is that the person’s age should be eighteen or greater than that. We have mentioned this condition in the if-else command. Now let’s see what the output is:

Conditions 2

As we can see, we have obtained the output as “kid” based on the value of the age variable.

We can chain the ternary operators as well:

print 1

Here we have incorporated multiple conditions. This form is the chained form of ternary operators. Let’s check the output:

print 2

This command is the same as the program given below : 

if else statement

The compiler evaluates conditions from left to right, which is easy to double-check with something like the pprint module:

pprint module

Alternatives To The Ternary Operator

For Python versions lower than 2.5, programmers developed several tricks that somehow emulate the behavior of the ternary conditional operator. They are generally discouraged, but it's good to know how they work: 

ternary conditional operator 1

These are various ways to impose conditions in your code :

ternary conditional operator 2

We can see that for various inputs, the same output is obtained for the exact value of the variable.

The problem of such an approach is that both expressions will be evaluated no matter what the condition is. As a workaround, lambdas can help:

print age 1

We obtain the output as follows :

print age 2

Another approach is using 'and' or 'or' statements:

print age 3

Yes, most of the workarounds look ugly. Nevertheless, there are situations when it's better to use 'and' or 'or' logic than the ternary operator. For example, when your condition is the same as one of the expressions, you probably want to avoid evaluating it twice:

void evaluating it twice

Indentations And Blocks

Python is very careful of the syntax of programming statements. We have to maintain proper indentation and blocks while we write composite statements like if-else . The correct indentation syntax of the if-else statement is given as follows:

syntax of programming statements

The statements under 'if' are considered a part of one 'block.' The other statements are not part of the if block and are not considered when statements of 'if' are evaluated.

Python will automatically change the text color if you deviate from this indentation and display an error when you run your code. Let's take an example where we intentionally differ from the proper indentation:

IndentationError 1

We can see here that Python delivers an error message as: "Expected an indented block ."

IndentationError 2

Also, note the color of 'print' in line 3. All the other text is green, while 'print' has the color red. The color variation happens because of the abrupt indentation of 'print.'

Now let us correct the indentation :

print in line

When we have maintained the indentation of Python, we get the output hassle-free.

The else And elif Clauses

Suppose your ‘ if ’ condition is false and you have an alternative statement ready for execution. Then you can easily use the else clause. Now, suppose you have multiple if conditions and an alternative for each one. Then, you can use the elif clause and specify any number of situations. Now let us take an example for each case :

Use of else clause:

The syntax of the   if-else statement is straightforward and has been used multiple times in this tutorial. Let us take a fundamental problem: There is a football team selection. The most critical condition for a candidate's eligibility is that he should be seventeen years or older. If his age is greater than or equal to seventeen, the output will be " You are eligible." If the boy is younger than seventeen years of age, the result will be " Sorry. You are not eligible."

Now let’s look at the code for this problem :

int input 1

Let’s run this code and see what the output is :

int input 2

The program first asks for the user input of age. We first enter the age as sixteen.

int input 3

Now let us enter the age as eighteen and observe the output.

int input 4

Thus we can see that the code assesses the input entered("age") and checks the value against the if-else conditions. If the condition is true, the compiler considers the statement under 'if ' and other statements are ignored. If the condition is false, the compiler executes the statement under 'else ,' and all the other statements are ignored.

Use of elif clause :

We use this clause when we have multiple conditions to check before printing the output. The word elif is compact for ‘ else-if .' When we use the elif clause, the else clause is optional. But if we want to use else clause, there has to be only one clause and that too at the end of the program.

Let us take a problem. We ask the user to enter a number between one and seven, and we display the corresponding weekday name. Let's look at the program for this problem.

int input 5

The above-given code has elif as well as else clause.

Now let’s check the output:

int input 6

The program first asks for user input of a number. Let’s enter four.

int input 7

Now, let's check the output for the input value twelve.

int input 8

Thus, the code works for any user-entered input value.

Conditions dominate every aspect of our real-life situations. To simulate these real-life conditions properly in our virtual world of coding, we, the programmers, need a good grasp on the control statements like if-else . We hope that this article helped you in understanding conditional statements and their syntax in Python. The various problems discussed in this article will help you understand the fundamental concepts of if-else statements and their applications.

About The Author

Anton Caceres

Anton Caceres

  • Python Tips and Tricks

Related Articles

  • Introduction to Python Classes (Part 1 of 2)
  • How to Sort a List, Tuple or Object (with sorted) in Python
  • Best Text Editors for Python development
  • Introduction to SQLite in Python
  • Introductory Tutorial of Python’s SQLAlchemy

Signup for new content

Thank you for joining our mailing list!

Latest Articles

  • Top Insurance Software Solutions for Streamlining Your Business
  • Revolutionizing Learning: Top AI-Powered Online Education Opportunities
  • Automating Investment Strategies with Python and Management Software: A Helpful Guide
  • Protecting Your Website from Cyber Problems: A Python Programmer's Perspective
  • How Python Can Help Secure Your Business's Cloud Infrastructure
  • Programming language
  • remove python
  • concatenate string
  • Code Editors
  • reset_index()
  • Train Test Split
  • Local Testing Server
  • Python Input
  • priority queue
  • web development
  • uninstall python
  • python string
  • code interface
  • round numbers
  • train_test_split()
  • Flask module
  • Linked List
  • machine learning
  • compare string
  • pandas dataframes
  • arange() method
  • Singly Linked List
  • python scripts
  • learning python
  • python bugs
  • ZipFunction
  • plus equals
  • np.linspace
  • SQLAlchemy advance
  • Data Structure
  • csv in python
  • logging in python
  • Python Counter
  • python subprocess
  • numpy module
  • Python code generators
  • python tutorial
  • csv file python
  • python logging
  • Counter class
  • Python assert
  • numbers_list
  • binary search
  • Insert Node
  • Python tips
  • python dictionary
  • Python's Built-in CSV Library
  • logging APIs
  • Constructing Counters
  • Matplotlib Plotting
  • any() Function
  • linear search
  • Python tools
  • python update
  • logging module
  • Concatenate Data Frames
  • python comments
  • Recursion Limit
  • Data structures
  • installation
  • python function
  • pandas installation
  • Zen of Python
  • concatenation
  • Echo Client
  • NumPy Pad()
  • install python
  • how to install pandas
  • Philosophy of Programming
  • concat() function
  • Socket State
  • Python YAML
  • remove a node
  • function scope
  • Tuple in Python
  • pandas groupby
  • socket programming
  • Python Modulo
  • Dictionary Update()
  • datastructure
  • bubble sort
  • find a node
  • calling function
  • GroupBy method
  • Np.Arange()
  • Modulo Operator
  • Python Or Operator
  • Python salaries
  • pyenv global
  • NumPy arrays
  • insertion sort
  • in place reversal
  • learn python
  • python packages
  • zeros() function
  • Scikit Learn
  • HTML Parser
  • circular queue
  • effiiciency
  • python maps
  • Num Py Zeros
  • Python Lists
  • HTML Extraction
  • selection sort
  • Programming
  • install python on windows
  • reverse string
  • python Code Editors
  • pandas.reset_index
  • Infinite Numbers in Python
  • Python Readlines()

How to Use Conditional Statements in Python – Examples of if, else, and elif

Oluseye Jeremiah

Conditional statements are an essential part of programming in Python. They allow you to make decisions based on the values of variables or the result of comparisons.

In this article, we'll explore how to use if, else, and elif statements in Python, along with some examples of how to use them in practice.

How to Use the if Statement in Python

The if statement allows you to execute a block of code if a certain condition is true. Here's the basic syntax:

The condition can be any expression that evaluates to a Boolean value (True or False). If the condition is True, the code block indented below the if statement will be executed. If the condition is False, the code block will be skipped.

Here's an example of how to use an if statement to check if a number is positive:

In this example, we use the > operator to compare the value of num to 0. If num is greater than 0, the code block indented below the if statement will be executed, and the message "The number is positive." will be printed.

How to Use the else Statement in Python

The else statement allows you to execute a different block of code if the if condition is False. Here's the basic syntax:

If the condition is True, the code block indented below the if statement will be executed, and the code block indented below the else statement will be skipped.

If the condition is False, the code block indented below the else statement will be executed, and the code block indented below the if statement will be skipped.

Here's an example of how to use an if-else statement to check if a number is positive or negative:

In this example, we use an if-else statement to check if num is greater than 0. If it is, the message "The number is positive." is printed. If it is not (that is, num is negative or zero), the message "The number is negative." is printed.

How to Use the elif Statement in Python

The elif statement allows you to check multiple conditions in sequence, and execute different code blocks depending on which condition is true. Here's the basic syntax:

The elif statement is short for "else if", and can be used multiple times to check additional conditions.

Here's an example of how to use an if-elif-else statement to check if a number is positive, negative, or zero:

Use Cases For Conditional Statements

Example 1: checking if a number is even or odd..

In this example, we use the modulus operator (%) to check if num is evenly divisible by 2.

If the remainder of num divided by 2 is 0, the condition num % 2 == 0 is True, and the code block indented below the if statement will be executed. It will print the message "The number is even."

If the remainder is not 0, the condition is False, and the code block indented below the else statement will be executed, printing the message "The number is odd."

Example 2: Assigning a letter grade based on a numerical score

In this example, we use an if-elif-else statement to assign a letter grade based on a numerical score.

The if statement checks if the score is greater than or equal to 90. If it is, the grade is set to "A". If not, the first elif statement checks if the score is greater than or equal to 80. If it is, the grade is set to "B". If not, the second elif statement checks if the score is greater than or equal to 70, and so on. If none of the conditions are met, the else statement assigns the grade "F".

Example 3: Checking if a year is a leap year

In this example, we use nested if statements to check if a year is a leap year. A year is a leap year if it is divisible by 4, except for years that are divisible by 100 but not divisible by 400.

The outer if statement checks if year is divisible by 4. If it is, the inner if statement checks if it is also divisible by 100. If it is, the innermost if statement checks if it is divisible by 400. If it is, the code block indented below that statement will be executed, printing the message "is a leap year."

If it is not, the code block indented below the else statement inside the inner if statement will be executed, printing the message "is not a leap year.".

If the year is not divisible by 4, the code block indented below the else statement of the outer if statement will be executed, printing the message "is not a leap year."

Example 4: Checking if a string contains a certain character

In this example, we use the in operator to check if the character char is present in the string string. If it is, the condition char in string is True, and the code block indented below the if statement will be executed, printing the message "The string contains the character" followed by the character itself.

If char is not present in string, the condition is False, and the code block indented below the else statement will be executed, printing the message "The string does not contain the character" followed by the character itself.

Conditional statements (if, else, and elif) are fundamental programming constructs that allow you to control the flow of your program based on conditions that you specify. They provide a way to make decisions in your program and execute different code based on those decisions.

In this article, we have seen several examples of how to use these statements in Python, including checking if a number is even or odd, assigning a letter grade based on a numerical score, checking if a year is a leap year, and checking if a string contains a certain character.

By mastering these statements, you can create more powerful and versatile programs that can handle a wider range of tasks and scenarios.

It is important to keep in mind that proper indentation is crucial when using conditional statements in Python, as it determines which code block is executed based on the condition.

With practice, you will become proficient in using these statements to create more complex and effective Python programs.

Let’s connect on Twitter and Linkedin .

Data Scientist||Machine Learning Engineer|| Data Analyst|| Microsoft Student Learn Ambassador

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

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 if else with 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
  • 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 if else with 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

Python If Else Statements – Conditional Statements – FAQs

What is the conditional statement of if-else.

The if-else statement in Python is used to control the flow of the program based on a condition. It has the following syntax: if condition: # Execute this block if condition is True else: # Execute this block if condition is False For example: x = 10 if x > 5: print("x is greater than 5") else: print("x is not greater than 5")

How many else statements can a single if condition have in Python?

A single if condition can have at most one else statement. However, you can have multiple elif (else if) statements to check additional conditions if needed: x = 10 if x > 15: print("x is greater than 15") elif x > 5: print("x is greater than 5 but not greater than 15") else: print("x is 5 or less")

What are the different types of control statements in Python?

In Python, control statements are used to alter the flow of execution based on specific conditions or looping requirements. The main types of control statements are: Conditional statements : if , else , elif Looping statements : for , while Control flow statements : break , continue , pass , return

What are the two types of control statements?

The two primary types of control statements in Python are: Conditional statements : Used to execute code based on certain conditions ( if , else , elif ). Looping statements : Used to execute code repeatedly until a condition is met ( for , while ).

Are control statements and conditional statements the same?

No, control statements and conditional statements are not exactly the same. Conditional statements ( if , else , elif ) specifically deal with checking conditions and executing code based on whether those conditions are True or False . Control statements encompass a broader category that includes both conditional statements ( if , else , elif ) and looping statements ( for , while ), as well as other statements ( break , continue , pass , return ) that control the flow of execution in a program.

Please Login to comment...

Similar reads.

  • python-basics

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Assignments  »  Conditional Structures  »  Set1

Conditional Structures

1. Write a program that prompts the user to input a number and display if the number is even or odd. Solution

2. Write a Python program that takes an age as input and determines whether a person is eligible to vote. If the age is 18 or above, print "You are eligible to vote." Otherwise, print "You are not eligible to vote yet.". Solution

3. Write a program that prompts the user to input two integers and outputs the largest. Solution

4. Write a program that prompts the user to enter a number and determines whether it is positive, negative, or zero. The program should print "Positive" if the number is greater than 0, "Negative" if the number is less than 0, and "Zero" if the number is 0. Solution

5. Write a program that prompts the user to enter their age and prints the corresponding age group. The program should use the following age groups:

6. Write a program that prompts the user to input a number from 1 to 7. The program should display the corresponding day for the given number. For example, if the user types 1, the output should be Sunday. If the user types 7, the output should be Saturday. If the number is not between 1 to 7 user should get error message as shown in sample output. Solution

7. Write a program that prompts the user to enter their weight (in kilograms) and height (in meters). The program should calculate the Body Mass Index (BMI) using the formula: BMI = weight / (height * height). The program should then classify the BMI into one of the following categories:

8. The marks obtained by a student in 3 different subjects are input by the user. Your program should calculate the average of subjects and display the grade. The student gets a grade as per the following rules:

python if else with assignment

Write a program that prompts the user to input the value of a (the coefficient of x 2 ), b (the coefficient of x), and c (the constant term) and outputs the roots of the quadratic equation. Solution

10. Write a program that prompts the user to enter three numbers and sorts them in ascending order. The program should print the sorted numbers. Solution

11. Write a program that prompts the user to input three integers and outputs the largest. Solution

12. Write a program that prompts the user to input a character and determine the character is vowel or consonant. Solution

13. Write a program that prompts the user to input a year and determine whether the year is a leap year or not. Leap Years are any year that can be evenly divided by 4. A year that is evenly divisible by 100 is a leap year only if it is also evenly divisible by 400. Example :

14. Write a program that prompts the user to input number of calls and calculate the monthly telephone bills as per the following rule: Minimum Rs. 200 for up to 100 calls. Plus Rs. 0.60 per call for next 50 calls. Plus Rs. 0.50 per call for next 50 calls. Plus Rs. 0.40 per call for any call beyond 200 calls. Solution

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 if else.

The else keyword catches anything which isn't caught by the preceding conditions.

In this example a is greater than b , so the first condition is not true, also the elif condition is not true, so we go to the else condition and print to screen that "a is greater than b".

You can also have an else without the elif :

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.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

If-else conditional assignment in pandas

I want to assign values to a column depending on the values of an already-existing column. This code works, but I would like to do it not-in-place, perhaps using assign or apply .

If this could be done in one step it would also avoid the implicit conversion from int to float that occurs below.

I've included my attempt using assign , which raises a ValueError .

  • ternary-operator

Hatshepsut's user avatar

You can use numpy.where() :

pault's user avatar

  • 8 original.assign(new=lambda x: np.where(x["col"].isin(["b", "x"]), 1, 99)) is just what I wanted. Thanks. –  Hatshepsut Commented Apr 10, 2018 at 21:06

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python pandas ternary-operator or ask your own question .

  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • What Does Feynman Mean When He Says Amplitude and Probabilities?
  • Has the Journal of Fluid Mechanics really published more than 800 volumes?
  • Definability of acyclic graphs
  • LCR Meter U1733C "rn" Symbol Meaning
  • Fill the grid subject to product, sum and knight move constraints
  • Does the damage from Thunderwave occur before or after the target is moved
  • Short story about a traveler who receives shelter, but after some dialogue, the traveler turns out to be a ghost or maybe Odin
  • These two Qatar flights with slightly different times and different flight number must actually be the same flight, right?
  • Substitute HS Experiment for Synthesis/Decomposition of HgO
  • Can a big mass defect make the mass negative?
  • Is a "single" cpu safer than multiple cores?
  • Is "sinnate" a word? What does it mean?
  • Why does King Aegon speak to his dragon in the Common Tongue (English)?
  • What if Mars is the same size as Earth with an atmospheric pressure of 1 atm?
  • Can I include a variable related to the outcome variable into statistical analysis?
  • Understanding top memory bar
  • Can I put multiple journeys and dates on one train ticket in UK?
  • DHCP assigned addresses following devices/users and routing
  • Story Identification : student gets perfect score, fake helicopter plans, Bob Dylan song
  • What methods can quickly determine the coefficient of determination of the data?
  • Recommend an essay, article, entry, author, or branch of philosophy that addresses the futility of arguing for or against free will
  • Is it possible to understand in simple terms what a Symplectic Structure is?
  • Rolling median of all K-length ranges
  • How are Boggarts created?

python if else with assignment

IMAGES

  1. Explain if-else statement in python

    python if else with assignment

  2. Python

    python if else with assignment

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

    python if else with assignment

  4. Python if else Statement with Examples

    python if else with assignment

  5. Understanding Python If-Else Statement [Updated]

    python if else with assignment

  6. If Else Statement in Python

    python if else with assignment

VIDEO

  1. Topic 6: Python if else statement

  2. Grand Assignment 5

  3. Python Tip! Assignment operator in Python #python #programming #basic #shorts #django #coding

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

  5. Assignment and multiple Assignment operators in Python

  6. Pemrograman python: cara menggunakan IF, If...ELSE, IF...ELIF di python

COMMENTS

  1. python

    For the future time traveler from Google, here is a new way (available from Python 3.8 onward): b = 1 if a := b: # this section is only reached if b is not 0 or false. # Also, a is set to b print(a, b) This is known as "the walrus operator". More info at the What's New In Python 3.8 page.

  2. python

    PEP 572 seeks to add assignment expressions (or "inline assignments") to the language, but it has seen a prolonged discussion over multiple huge threads on the python-dev mailing list—even after multiple rounds on python-ideas.

  3. 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.

  4. Python Conditional Assignment (in 3 Ways)

    Let's see a code snippet to understand it better. a = 10. b = 20 # assigning value to variable c based on condition. c = a if a > b else b. print(c) # output: 20. You can see we have conditionally assigned a value to variable c based on the condition a > b. 2. Using if-else statement.

  5. How to Write the Python if Statement in one Line

    You may have seen this coming, but we can even write elif and else statements each in a single line. To do so, we use the same syntax as writing an if statement in a single line. Here's the general structure: if <expression_01>: <perform_action_01>. elif <expression_02>: <perform_action_02>.

  6. 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

  7. 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:

  8. Python One Line Conditional Assignment

    Method 1: Ternary Operator. The most basic ternary operator x if c else y returns expression x if the Boolean expression c evaluates to True. Otherwise, if the expression c evaluates to False, the ternary operator returns the alternative expression y. <OnTrue> if <Condition> else <OnFalse>. Operand.

  9. 10 if-else Practice Problems in Python

    The syntax is straightforward: You provide a condition to evaluate within the if. If that condition is true, the corresponding block of code is executed. If the condition is false, the code within the optional else block is executed instead. Here's a simple example: x = 10. if x > 5: print("x is greater than 5") else:

  10. 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 ...

  11. Conditional expression (ternary operator) in Python

    Basics of the conditional expression (ternary operator) In Python, the conditional expression is written as follows. X if condition else Y. The condition is evaluated first. If condition is True, X is evaluated and its value is returned, and if condition is False, Y is evaluated and its value is returned. If you want to switch the value based ...

  12. if , if..else, Nested if, if-elif statements

    Example 1: Handling Conditional Scenarios with if-else. In this example, the code assigns the value 3 to variable x and uses an if..else statement to check if x is equal to 4. If true, it prints "Yes"; otherwise, it prints "No," demonstrating a conditional branching structure. Python3. x = 3. if x == 4:

  13. One line if statement in Python (ternary conditional operator)

    Many programming languages have a ternary operator, which defines a conditional expression. The most common usage is to make a terse, simple dependent assignment statement. In other words, it offers a one-line code to evaluate the first expression if the condition is true; otherwise, it considers the second expression.

  14. How to Use Conditional Statements in Python

    How to Use the else Statement in Python. The else statement allows you to execute a different block of code if the if condition is False. Here's the basic syntax: if condition: # code to execute if condition is true else: # code to execute if condition is false

  15. 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.

  16. 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.

  17. Python if-else Exercises

    1. Write a program that prompts the user to input a number and display if the number is even or odd. Solution. 2. Write a Python program that takes an age as input and determines whether a person is eligible to vote. If the age is 18 or above, print "You are eligible to vote."

  18. One line if assignment in python

    3. following this topic One line if-condition-assignment. Is there a way to shorten the suggested statement there: num1 = (20 if intvalue else 10) in case that the assigned value is the same one in the condition? this is how it looks now: num1 = (intvalue if intvalue else 10) intvalue appears twice. Is there a way to use intvalue just once and ...

  19. Python If Else

    elif a == b: print("a and b are equal") else: print("a is greater than b") Try it Yourself ». In this example a is greater than b , so the first condition is not true, also the elif condition is not true, so we go to the else condition and print to screen that "a is greater than b". You can also have an else without the elif:

  20. python

    Python ternary operator and assignment in else. 2. ternary expression dependent on two columns. 0. if as a ternary operator python. 2. ... Python Pandas multiple condition assignment. 0. Pandas IF statement referencing other column value. 1. Using If /Else Statement Operator in Pandas/Python. Hot Network Questions Rule of Thumb meaning in ...