How Do I Run the if Statement Again if User Pressed Wrong Choice in Python

This tutorial describes the use of conditional programming constructs such equally Python If Else, If-Elif-Else, and If-Else in Ane line. We'll provide their syntax and explain with the assist of flowchart and examples.

You would also get to learn more complex forms of determination-making statements. Some of these are Nested if, use of 'not,' 'in' and 'and' operators.

A provisional statement (like if X > Y:) envelopes effectually a cake of code. Information technology lets Python evaluate the logical expression (X > Y) beginning. If the effect is Truthful, then merely the code indented under the conditional block gets executed.

Let's now briefly meet what this tutorial is going to cover.

Python Conditions/Decision-Making Statements

Table of Content

  • if Statement
    • Syntax
    • Flowchart
    • Example
  • if Else in One Line
  • if Else Argument
    • Syntax
    • Flowchart
    • Instance
  • if-Elif-Else Argument
    • Syntax
    • Flowchart
    • Example
  • Nested If-Else Argument
    • Syntax
    • Flowchart
    • Case
  • Using Not Operator with If Else
    • Examples
  • Using And Operator with If Else
    • Flowchart
    • Example
  • Using In Operator with If Else
    • Examples

Go back to ☛ Python Tutorial

Python if Statement

A bare Python if statement evaluates whether an expression is True or False. It executes the underlying code just if the result is True.

Given below is the syntax of Python if statement.

Syntax

if Logical_Expression :     Indented Lawmaking Cake

Flowchart

Basic Python if Statement Flowchart
Basic Python if Statement Flowchart

Example

days = int(input("How many days in a jump yr? ")) if days == 366:     print("You accept cleared the exam.") print("Congrats!")

The output of the in a higher place code is –

How many days in a leap year? 366 Y'all have cleared the test. Congrats!

Python if Else Statement

A Python if else statement takes action irrespective of what the value of the expression is.

If the result is Truthful, and so the lawmaking block following the expression would run. Otherwise, the lawmaking indented under the else clause would execute.

Given below is the syntax of Python if Else argument.

Syntax

if Logical_Expression :     Indented Code Block 1 else :     Indented Lawmaking Cake 2

Flowchart

Python If-Else Statement Flowchart
If-Else Statement Flowchart

Example

respond = input("Is Python an interpreted language? Yes or No >> ").lower()  if answer == "yes" :     print("You take cleared the test.") else :     print("You lot have failed the test.")  print("Thanks!")

When you run the above code, it asks for your input. Information technology converts the entered value it into lower case and runs the if-else condition.

If you enter a 'aye,' and then the output of the above code would be –

Is Python an interpreted language? Yeah or No >> aye You have cleared the exam. Thanks!

If you enter a 'no,' then the outcome of the above code would be –

Is Python an interpreted language? Yeah or No >> no Yous accept failed the test. Thanks!

Python If Else in One Line

Python provides a way to shorten an if/else statement to ane line. Permit's run across how can you lot do this.

The one-liner If-else has the following syntax:

# If Else in i line - Syntax value_on_true if status else value_on_false

See the below example of If-Else in ane line.

>>> num = 2 >>> 'Even' if num%2 == 0 else 'Odd' 'Even' >>> num = three >>> 'Even' if num%2 == 0 else 'Odd' 'Odd' >>> num = 33 >>> 'Even' if num%ii == 0 else 'Odd' 'Odd' >>> num = 34 >>> 'Even' if num%ii == 0 else 'Odd' 'Even' >>>

Python if-Elif-Else Statement

The first iii if-else constructs can simply address 2 outcomes, i.e., True or Simulated. Even so, the expression next to "if" can also evaluate to a value different from the boolean. Information technology ways to take more weather, non just a unmarried "else" block.

Python supports to specify multiple conditions by using an "elif" clause with each of the expression.

Given beneath is the syntax of Python if-elif-else statement.

Syntax

if Logical_Expression_1 :     Indented Code Block one elif Logical_Expression_2 :     Indented Code Cake 2 elif Logical_Expression_3 :     Indented Lawmaking Cake 3 ... else :     Indented Code Block N

Flowchart

If Elif Else Statement Flowchart
If Elif Else Statement Flowchart

Example

while Truthful:     response = input("Which Python data type is an ordered sequence? ").lower()     print("Yous entered:", response)          if response == "list" :         impress("You have cleared the exam.")         break     elif response == "tuple" :         print("Yous have cleared the test.")         break     else :         print("Your input is wrong. Delight try once more.")

This plan has a while loop where it is querying nigh Python data types. It wants yous to enter the name of an ordered sequence. If y'all provide a wrong value, then it would again prompt you for the correct input.

Only by entering the correct value, the loop could break. Nevertheless, y'all can too press the CTRL+C to exit the plan.

Had you entered a incorrect answer, and so the output would be :

Which Python data type is an ordered sequence? dictionary Yous entered: lexicon Your input is wrong. Please try again. Which Python data type is an ordered sequence?

One time you provide the correct reply, the program would end with the following output.

Which Python data type is an ordered sequence? tuple You entered: tuple You take cleared the test.

Nested If-Else in Python

Some programs may accept a code block under an "if" clause. And information technology could have subsequent conditional blocks.

In such a case, Python allows nesting of an if-else or if-elif-else inside another conditional clause.

Python doesn't limit the level of nested conditions in a program. Given below is the syntax of a multi-level nested if-elif-else argument.

Syntax

if Logical_Expression_1 :     if Logical_Expression_1.1 :         if Logical_Expression_1.1.1 :             Indented Code Block 1.one.1         else             Indented Lawmaking Block     elif Logical_Expression_1.2 :         Indented Lawmaking Cake 1.2     else :         Indented Code Block elif Logical_Expression_2 :     Indented Code Cake 2 elif Logical_Expression_3 :     Indented Code Block 3 ... else :     Indented Code Block

Flowchart

Nested Condition Statement Flowchart
Nested Status Statement Flowchart

The in a higher place diagram represents the following lawmaking flow.

ten = 10 y = 20 z = 30  print("First") if x == ten:     print(" Nested If")     if y == 20:         print(" Cease of Nested If Block ")     else:         print(" End of Nested If-Else Cake ") elif y == twenty:     impress(" Elif block ") else:     impress(" Nested If")     if z == xxx:         print(" End of Nested If Block ")     else:         impress(" Finish of Nested If-Else Block ") print("Cease")

Example

while True:     response = int(input("How many days are in that location in a leap year? "))     impress("You entered:", response)          if response == 366 :         print("You have cleared the get-go level.")         response = input("What month has an extra solar day in jump yr?? ").lower()         if response == "february" :             impress("Y'all have cleared the exam.")             break         else :             print("Yous have failed the test.")             break     else :         print("Your input is wrong, please attempt again.")

The above code demonstrates the use of nested if in Python. It first asks a question from the user. After that, there is an if statement to check whether the respond is correct or non. In case the user provides the right input, then he faces another question. Now, the nested IF comes into the pic checking the latest response from the user.

Using Non Operator with Python If Else

The 'non' is a negation logical operator in Python. It reverses the result of its operand and converts to a boolean consequence, i.e., True or Fake. The operand could be a variable or an expression evaluating to a numeric type.

Example-1

a = ten b = xx if non a > b :     print("The number %d is less than %d" %(a, b))/
The output of the above code is -
The number x is less than 20

Case-2

X = 0 if non 10 :     impress("X is not %d" %(X)) else :     print("X is %d" %(X))

The output of the to a higher place lawmaking is –

X is not 0

Using And Operator with If Else

By using the 'and' operator, y'all can bring together multiple expression in a Python if condition. It is also a logical operator which evaluates as True if both/all the operands (x and y and z) are Truthful.

Flowchart

You tin find the code of this flowchart in the underlying example.

Using And Operator in Python Conditions
Using And Operator in Python Conditions

Example

Check out the post-obit example to see the 'and' operator in action.

a = x b = xx c = 30  avg = (a + b + c) / three print("avg =", avg)  if avg > a and avg > b and avg > c:     print("%d is higher than %d, %d, %d" %(avg, a, b, c)) elif avg > a and avg > b:     print("%d is higher than %d, %d" %(avg, a, b)) elif avg > a and avg > c:     impress("%d is higher than %d, %d" %(avg, a, c)) elif avg > b and avg > c:     print("%d is higher than %d, %d" %(avg, b, c)) elif avg > a:     print("%d is only higher than %d" %(avg, a)) elif avg > b:     print("%d is just higher than %d" %(avg, b)) elif avg > c:     print("%d is just college than %d" %(avg, c))

The output of the higher up code is –

avg = twenty.0 twenty is just higher than 10

Using In Operator with If Else

Python "in" operator allows comparison a variable confronting multiple values in a single line. Information technology makes conclusion making more than comfortable by reducing the employ of many if-elif statements.

In Python, nosotros oft refer to it as the membership operator. It tin let you check value from objects of dissimilar types. They could be a list, tuple, string, lexicon types.

Examples

This example first creates a listing of six numbers. After that, there is a for loop which is traversing information technology and prints values.

The loop has an if statement which prints specific numbers from the list which are non in the tuple used in the condition.

Hence, nosotros've also used the "not" forth with the "in" operator.

#Example of "in" operator with Python If statement  num_list = [ane, 10, two, 20, 3, 30] for num in num_list:     if not num in (2, 3):         print ("Allowed Item:", num)

The output of the above code is equally follows.

Immune Item: 1 Allowed Item: x Immune Item: 20 Allowed Particular: xxx

Let'southward bank check out one more than example. Information technology has two teams of players (team1 and team2) for two games. In hither, we've to find who from the "team1" likewise plays for the "team2".

# Find players who play both games  team1 =["Jake", "Allan", "Nick", "Alex", "Dave"] team2 =["David", "John", "Chris", "Alex", "Nick"]  for aplayer in team1:     if aplayer in team2:         print("%s also plays for team2." %(aplayer))

The output of the above code is as follows.

Nick too plays for team2. Alex also plays for team2.

Summary

Aye, the software programs tin make decisions at runtime. Merely their correctness depends on how finer accept you added the weather condition.

In this tutorial, we covered Python If Else, If-Elif-Else and a couple of its variations using diverse Python operators.

If y'all found this tutorial useful, and so exercise share it with your colleagues. Also, connect to our social media (Facebook/Twitter) accounts to receive timely updates.

All-time,

TechBeamers

parraoved1971.blogspot.com

Source: https://www.techbeamers.com/python-if-else/

0 Response to "How Do I Run the if Statement Again if User Pressed Wrong Choice in Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel