×

One Liner If-Else Statements in Python

Before learning one liner if else Python, let us first know what Python is. Python is a broadly helpful, object-oriented and dependable language having a large number of utilizations from web improvement and numerical processing to work area graphical UIs. It is an interpreted language which means it checks codes line by line and provides output.

The syntax of Python language is clean, and the length of code relatively shorter than any other programming language. It permits us to think about the problem rather than focusing on syntax only. It has a wide range of applications such as web applications, desktop GUI applications, scientific and numeric calculations, image processing applications, etc. It is an open-source language and is easy to understand. It is free and portable.

Python statements

Statements are instructions which python interpreters will execute. There are many types of Python statements, and one of them is conditional statements. Let us learn why conditional statements. A conditional statement is utilized to decide if a specific condition exists or not before the code is executed. Conditional statements are otherwise called dynamic statements. It performs various calculations or activities relying upon whether the given condition is true or false.

The types of conditional statements are as follow

  1. The if statement
  2. The if else statement
  3. The if elif statement
  4. The nested if else

1) The if statement: It is used to check whether the given statement is True or not.

Syntax

If boolean expressions:
        Statements

Example

a = 20
b = 20
if a == b:
      print("yes")
else:
     print("no")

Output

yes

2) The if else statement: It is used to check whether the given statement is true or false.

Syntax

If boolean expressions1:
         Statement-A
Else:
      Statement B

Example

a = 20
b = 23
if a < b:
        print(" a is less than b")
else:
     print("a is greater than or equal to b")

Output

a is less than b

3) The if elif statements: The if elif statements allow you to check multiple expressions for True or False and execute a block of code as soon as one of the conditions, evaluates to True.

Syntax  

If boolean expressions2:
           Statement A
Elif boolean expressions3:
           Statement B
Elif boolean expressions4:
           Statement C
Else:
     Statement D 

Example

a = int(input("Enter an integer"))
if a <  0:
        print(" a is negative")
elif a==0:
         print(" a is null")
else:
      print("a is positive")

Output

Enter an integer 34
a is less than b

4) The nested if else statement: When we write an if else statement in another if else statement, then that statement is known as a nested if else statement.

Syntax

If boolean expressions2:
        Statement A
Else:
If boolean expressions3:
       Statement B
Else:
     Statement C

Example

num = 21
if num < 25:
    if num%2==0:
        print("num is even number less than 25")
    else:
        print("num is an odd number less than 25")
else:
    print("num is greter than 25")

Output

num is an odd number less than 25

Boolean expression: It is a Python inbuilt data type used to represent an expression's True value.

Note: The colon is vast and required. It isolates the header of the compound statement from the body. The line after the colon should be indented.

One liner if else Python

It is a type of if else statement in which we write if else statements in one line. It means that if statements and other statements are in the same line. It is otherwise called the ternary administrator. The ternary operator is available in some programming languages, which allows us to shorten the If else block. The one-line statement syntax is

<instruction A> If (conditions) else <instruction B>
           
And


If (conditions A):
       Statements
Else:
      Statements

Let us understand by an example.

val = int(input("Enter an integer"))
if val > 45:
    print(" Value entered by the user is greater than 45")
else:
    print("Value is less than or equal to 45")

Output

One Liner If-Else Statements in Python

We have implemented both if and else in the above example. We have taken inputs from the user; if the user types a number greater than 45, it will give output as the value is more significant than val, and the “if” statement will execute. If the user type number is less than 45, then the “else” statement will run and give output as the value entered by the user is less than 45. Also, the else statement will execute when the user types a number equal to 45 and will give an output value equal to 45. So this is how we can use a one-liner if else statement.     

Let us take more examples to understand it better.

val = int (input (“Enter an integer”))
If val < 90:
        print (“Entered value is less than 90”)
Else:
        print (“Entered value is greater than 90”)

Output

One Liner If-Else Statements in Python

In this example, the input () command has been used to get input from the user. If the data is under 90, the “if” statement will execute, and if the value is more than 90, then the “else” statement will execute. Its value relies on the input given by the user.

Note: - The execution of a one-liner if-else statement starts from left to right.

Let us take one other example

def oddeven(a):
    if a % 2 == 0:
        print(a, " even number ")
    else:
        print(a, "odd number ")
oddeven(27)

Output

One Liner If-Else Statements in Python

In the above example, we have executed a simple function to understand it in a better way. If the number is not distinct by 2, it will return an odd number and the “if” statement will execute. If the number is distinct by 2, it will return an even number, and the else statement will execute. We have passed 27, a number which will be returned as an odd number.


Related Topics

Python Graph

Python Graph: In Computer Science and Mathematics, a Graph is a pictorial representation of a group of objects or elements where some elements are connected using the links. A graph...

5 minutes read.

Python Syntax Error Invalid Syntax

Python is renowned for its simple and direct syntax. However, we might come across some things that Python doesn't allow if we are learning Python for the very first time or if...

14 minutes read.

How to Concatenate Two Strings in Python

How to Concatenate Two Strings in Python Like the other data types, operations on strings are quite useful when we deal with some real-life applications. Here we will talk about a simple...

4 minutes read.

Python Program to check whether a given number is Armstrong or not

Program to check whether a given number is Armstrong or not A number is said to be an Armstrong if the sum of each digit's cube of a given number equals...

1 minute read.

Difference between Package and Module in Python

What are Python modules? A file with the “.py” suffix that includes Python or C executable code is known as a module. Multiple Python commands and expressions make compose a module....

3 minutes read.

Weight Conversion GUI using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Cursor in Python

The cursor is an item that aids in query execution and records retrieval from databases. The cursor is crucial to the execution of the query. In-depth information on the execution...

7 minutes read.

Python Fit Transform

In machine learning, fit (), transform(), fit transform () methods are provided by scikit learn package. This package is used in model fitting and data processing. These methods are implemented...

2 minutes read.

Python whois

What is whois? Whois is a protocol used to identify the owner of the registered domain name. It is a querying database that is used to record the registered users. WHOIS is...

4 minutes read.

Add Dictionary to Dictionary in Python

Dictionary in python: Python's execution of a data model, known more commonly as an implicit array, is a dictionary. A dictionary is made up of a group of key-value pairs. Each...

4 minutes read.

Converting Set to List in Python

Converting ‘set’ datatype to ‘list’ datatype is called typecasting. Typecasting in programming is a method to convert one datatype into another datatype. It may happen implicitly by the defined language, called...

3 minutes read.

Subprocess Module in Python

What is a Process? Every program will have its respective system state, i.e., the state in which it is running. A program that is in a running state or in a...

7 minutes read.

Python Not Equal Operator

Python provides us with many operators to make tasks easier. There are about 7 categories of operators in Python. One of the 7 classifications is the comparison operators. Just as...

3 minutes read.

Python ascii() Function

Python ascii() Function The ascii() function returns a readable version of any object (Strings, Tuples, Lists, etc). This function will replace any non-ascii characters with escape characters. Syntax ascii(object) Parameter object:  An object, like String, List, Tuple, Dictionary, etc. Return This...

1 minute read.

Selection Sort Using Python

Selection sort is a type of sorting algorithm which is based on sorting elements in increasing order or ascending order through comparison. This sorting technique does not take extra space...

3 minutes read.

Python Indentation

Overview The spaces at the start of a code line are known as an indentation in Python programming. Indentation is only used for readability in other programming languages like C, C++,...

8 minutes read.

Python MongoDB Tutorial

An Introduction to MongoDB MongoDB is a document-oriented database application. It is an Open-source and platform-independent program. MongoDB is similar to few NoSQL databases that store the data in the documents...

17 minutes read.

List Index out of Range Python for Loop

The List is generally used in Python to store multiple items or elements inside one single variable. The List is ordered in nature, the List can contain the elements inside...

3 minutes read.

Python Setup guide and installation

Python Installation guide Step by Step Python is widely used high-level programming language. The first version of Python was launched in 1991. Since then, Python has been gaining popularity. It is considered as...

4 minutes read.

Convert Float to Int in Python using Pandas

Introduction To play with huge amounts of data, in python we require a tool. The tool which is available in Python is pandas. A panda is an open-source library. It is...

4 minutes read.