Computer Science

if else in Python

In Python, the "if else" statement is used to create conditional logic. It allows the program to execute different blocks of code based on whether a specified condition is true or false. If the condition is true, the code within the "if" block is executed; otherwise, the code within the "else" block is executed. This provides a way to control the flow of the program based on specific conditions.

Written by Perlego with AI-assistance

10 Key excerpts on "if else in Python"

  • Book cover image for: Job Ready Python
    eBook - PDF
    • Haythem Balti, Kimberly A. Weiss(Authors)
    • 2021(Publication Date)
    • Wiley
      (Publisher)
    In our banking application, there may be times when we need to correct errors or provide specific notifications depending on the situation, and this is where if-else statements can assist. WORKING WITH NESTED CONDITIONS Python uses the elif keyword as a contraction of “else if,” which allows us to string together many different conditions, each of which must be True or False on their own. The syntax for using an elif is: if expression1 : statement(s) # Expression1's code block elif expression2 : statement(s) # Expression2's code block elif expression3 : statement(s) # Expression3's code block else: statement(s) While if and if-else provide acceptable ways to produce a specific outcome based on current conditions, they are most useful for situations where the outcome is clear ( True or False ), and it is harder to include gray areas in the conditions. In reality, though, we often need a program to choose between a variety of outcomes rather than just one or two. A program requirement could be to provide a specific statement based on a person’s income, yet there is also a need to include options for income ranges— to apply income-dependent dis-counts for childcare— or something that Python can display as an error message if the user enters a value that cannot represent an age (like a name or a date). The elif operator allows us to nest a series of conditions in a conditional block and produce one of several different options. While the construction must include at least one elif statement, it can contain as many as necessary to address all the positional conditions. When evaluating this structure, Python does the following: 1. If the condition in expression1 evaluates to True , Python executes the statement(s) in expression1 ’s code block and skips the rest of the code in the structure. 2. If conditional1 is False , Python evaluates each elif statement in sequence until it finds a condition that is True .
  • Book cover image for: Programming in Python
    eBook - ePub

    Programming in Python

    Learn the Powerful Object-Oriented Programming

    Table 4.1 . depicts a list of decision making control structures supported by Python language. Now, we will learn each of the control structure in detail.
    Statement Description
    if statement An if statement consists of an expression (which results in either true or false) followed by a block of one or more statements.
    if…else statement An if statement followed by an else statement, which executes when the boolean expression turns false.
    if…elif…else statement An if statement can be followed by an optional elif and else statements, where elif is accompanied with a test condition similar to if statement.
    nested if statement It contains if statement inside another if or else if statement(s).
    Table 4.1. Python decision making control structures

    Note

    Python programming language assumes any nonzero and non-null values as TRUE, and if it is either zero or null, then it is assumed as FALSE value.

    4.1.1. Python if Statement

    The Python if statement can execute either a simple or compound statement depending on the result of the expression. The syntax of Python if statement is given as follows:
    if test condition: statement(s)
    Here, the program evaluates the test condition (expression) and will execute statement(s) only if the test expression evaluates to True. If the test expression is False, the statement(s) does not get executed. As we know that, in Python, indentation is necessary. The beginning of a block is always marked with the indented statement and the closing of a block is marked by the unindented statement. Therefore, the body of the if statement is indicated by the indentation. Body starts with an indentation and the first unindented line marks the end. Python interprets non-zero values as True. None and 0 are interpreted as False. The flow diagram of if statement is given in Fig. 4.1
  • Book cover image for: Introduction to Computing Using Python
    eBook - PDF

    Introduction to Computing Using Python

    An Application Development Focus

    • Ljubomir Perkovic(Author)
    • 2012(Publication Date)
    • Wiley
      (Publisher)
    In Chapter 3 we introduced the Python if statement. We first saw it in its simplest form, the one-way decision format: if : The statements in are executed only if is True; if is False, no alternative code block is executed. Either way, execution resumes with the statement that is below and with the same indentation as the if statement. The two-way decision format of the if statement is used when two alternative code blocks have to be executed depending on a condition: if : else: If condition is true, is executed; otherwise, is executed. Note that the conditions under which the two code blocks get executed are mutually exclusive. In either case, execution again resumes with the statement . Three-Way (and More!) Decisions The most general format of the Python if statement is the multiway (three or more) deci- sion control structure: if : elif : elif : else: # there could be more elif statements This statement is executed in this way: • If is true, then is executed. • If is false but is true, then is executed. • If and are false but is true, then is executed. • If no condition is true, then is executed. In all cases, the execution will resume with the statement . Section 5.1 Decision Control and the if Statement 135 The elif keyword stands for “else if”. An elif statement is followed by a condition just like the if statement.
  • Book cover image for: Basic Core Python Programming
    eBook - ePub

    Basic Core Python Programming

    A Complete Reference Book to Master Python with Practical Applications (English Edition)

    There is a block of code associated with every control flow statement. This block of code is defined by a colon (‘:’) and indentation. You are aware that Python uses four spaces (PEP-8 standard) of indentation to mark the beginning of a block of code. Usage of a tab instead of four spaces is not recommended as per the best practices defined in PEP-8. In all languages, indentation is required only to improve the readability and the block of code is defined in a curly brace ({}). However, in Python programming indentation is crucial.

    8.1 Working with ‘if’

    While programming you will often come to a point where you will have to decide how your program will work under different scenarios. For example, you build campus management software for your school but you cannot give the same privileges to all the users. You will have different privileges for students and teachers. So, if a student logs in then there are one set of privileges available and if the teacher logs in then another set of privileges are available.

    8.1.1 If .. elif..else

    In this section, you will learn about the if..elif..else statement. This statement is used when there are multiple scenarios. The syntax for working with if..elif..else statement is given as follows:
    Syntax: if this_condition_is_true: #Execute the code provided in this block --------------------------------------- --------------------------------------- elif this_condition is true: #Execute the code provided in this block ---------------------------------------- ---------------------------------------- else: #Execute the code provided in this block ---------------------------------------- ----------------------------------------
    Figure 8.1
    Now, let’s put this information to some good use. Look at example 8.1 .
    Example 8.1 Look at the following code: qty = int(input("How many apples do you have? : ")) price = float(input("What is the total cost? : ")) value_of_one = price/qty if value_of_one >= 20: print("one apple costs {} and it is too expensive".format(value_of_one)) elif (value_of_one <20) & (value_of_one >= 10): print("one apple costs {} and it is reasonable".format(value_of_one)) else: print("one apple costs {} and it is unbelievable".format(value_of_one)) The preceding code has three conditions:
    • if
    • elif
    • else
    The if block will execute only if the price of one apple is greater than or equal to 20. If the price of one apple is less than 20, then the condition of the if block evaluates to false . If the cost of one apple is less than 20 but greater than or equal to 10, then the condition for elif block evaluates to true and that block is executed. If the cost of one apple is less than 10, then the condition of the elif block also evaluates to false and the else
  • Book cover image for: Introduction to Python Programming
    3 Control Flow Statements
    AIM Understand if, if…else and if…elif…else statements and use of control flow statements that provide a means for looping over a section of code multiple times within the program. LEARNING OUTCOMES At the end of this chapter, you are expected to •  Use if, if…else and if…elif…else statements to transfer the control from one part of the program to another. •  Write while and for loops to run one or more statements repeatedly.
    •  Control the flow of execution using break and continue statements.
    •  Improve the reliability of code by incorporating exception handling mechanisms through try-except blocks.
    Python supports a set of control flow statements that you can integrate into your program. The statements inside your Python program are generally executed sequentially from top to bottom, in the order that they appear. Apart from sequential control flow statements you can employ decision making and looping control flow statements to break up the flow of execution thus enabling your program to conditionally execute particular blocks of code. The term control flow details the direction the program takes.
    The control flow statements (FIGURE 3.1 ) in Python Programming Language are
    1.  Sequential Control Flow Statements: This refers to the line by line execution, in which the statements are executed sequentially, in the same order in which they appear in the program.
    2.  Decision Control Flow Statements: Depending on whether a condition is True or False, the decision structure may skip the execution of an entire block of statements or even execute one block of statements instead of other (if, if…else and if…elif…else).
    3.  Loop Control Flow Statements: This is a control structure that allows the execution of a block of statements multiple times until a loop termination condition is met (for loop and while
  • Book cover image for: A Functional Start to Computing with Python
    A block of statements is a group that is indented by the same amount or more. In the figure, all the statements below def R(a,b,c) are a block: they are all indented more than the def statement. Likewise, following if a==b there is a block of five statements, all indented more than this if statement. Else and Elif Python’s if statement is adequate for the conditional logic in any function definition imag-inable. Yet, the language can do better than just having if alone, because certain patterns of conditional logic occur frequently in programs. A recurring theme in the evolution of programming languages is to watch how people use the language, then ask if some change in the language, perhaps a new feature added to the language, will simplify things. The else statement is a good example of this theme. 126 A Functional Start to Computing with Python First, consider a function questin(s) returning True if string s contains a question mark. def questin(s): return '?' in s This function does not even need conditional logic! But, just to make a point, we rewrite it using if and add some print statements. def questin(s): if '?' in s: print(positive) return True if not ('?' in s): print(negative) return False The pattern here, occurring quite often, recalls the flowchart diamond shapes, where a decision has two outcomes. The decision is a condition (boolean). Above, the pattern is expressed with if s, one for the case true , the other for the case not true ( false ). A drawback to this style is that the condition ( '?' in s ) had to be typed in twice. An else statement overcomes this drawback. The same function is rewritten by: def questin(s): if '?' in s: print(positive) return True else: print(negative) return False Notice that the else statement aligns (same indentation) as the if statement— this is crucial in Python. The only way that Python can know what condition else refers to is by the indentation.
  • Book cover image for: Python Programming for Biology
    eBook - PDF

    Python Programming for Biology

    Bioinformatics and Beyond

    This might also involve subsidiary checks using the ‘elif’ statement (the English equivalent of which might be ‘or else if the following’) to control an alternative block if the previous expression turns out to be False. There can even be a final ‘else’ statement (in English ‘otherwise if all else fails’) to do something if none of the checks are passed. To give a solid example, the following uses statements that test whether a number is less than zero, greater than zero or otherwise equal to zero and will print out a different message in each case: if x > 0: print("Value is positive") elif x < 0: print("Value is negative") else: print("Value is zero") The general form of writing out such combined conditional statements is as follows: if conditionalExpression1: # codeBlock1 elif conditionalExpression2: # codeBlock2 plus any number of additional elif statements, then finally: else: # codeBlockEnd The elif statements are optional and independently the else statement is also optional, so you can just have an isolated if statement, which is a fairly common situation. Each block has to be indented relative to the if/elif/else. Note also the colon (‘:’) that appears after the if/else/else statements. This is a mandatory part of the syntax, though it is easy to forget. Each block must contain at least one line of code, but can have more. Python has a ‘pass’ statement that qualifies as a line of code but does nothing. So when you are first setting 46 Program control and logic out your code, you can use this as a placeholder until you get around to adding the actual desired code: if someExpression: pass # fill code in later Comparisons and truth The question naturally arises as to which expressions are deemed to be true and which false. Naturally, for the special Python logic items named True and False (often referred to as Boolean values) the answer is obvious.
  • Book cover image for: Python For Everyone
    • Cay S. Horstmann, Rance D. Necaise(Authors)
    • 2019(Publication Date)
    • Wiley
      (Publisher)
    In this chapter, you will learn how to program simple and complex decisions. You will apply what you learn to the task of checking user input. 3.1 The if Statement The if statement is used to implement a decision (see Syntax 3.1). When a condition is fulfilled, one set of statements is executed. Otherwise, another set of statements is executed. Here is an example using the if statement: In many countries, the number 13 is considered unlucky. Rather than offending superstitious ten- ants, building owners sometimes skip the thirteenth floor; floor 12 is immediately followed by floor 14. Of course, floor 13 is not usually left empty or, as some conspiracy theorists believe, filled with secret offices and research labs. It is simply called floor 14. The computer that controls the building elevators needs to compensate for this foible and adjust all floor numbers above 13. Let’s simulate this process in Python. We will ask the user to type in the desired floor number and then compute the actual floor. When the input is above 13, then we need to decrement the input to obtain the actual floor. An if statement is like a fork in the road. Depending upon a decision, different parts of the program are executed. © Media Bakery. © DrGrounds/iStockphoto. This elevator panel “skips” the thirteenth floor. The floor is not actually missing—the computer that controls the elevator adjusts the floor numbers above 13. The if statement allows a program to carry out different actions depending on the nature of the data to be processed. 3.1 The if Statement 75 Figure 1 Flowchart for if Statement floor > 13? True False actualFloor = floor - 1 actualFloor = floor Condition For example, if the user provides an input of 20, the program determines the actual floor as 19. Otherwise, we simply use the supplied floor number. actualFloor = 0 if floor > 13 : actualFloor = floor - 1 else : actualFloor = floor The flowchart in Figure 1 shows the branching behavior.
  • Book cover image for: Python Fundamentals
    No longer available |Learn more

    Python Fundamentals

    A practical guide for learning Python, complete with real-world projects for you to explore

    • Ryan Marvin, Mark Ng'ang'a, Amos Omondi(Authors)
    • 2018(Publication Date)
    • Packt Publishing
      (Publisher)
    3

    Control Statements

    Learning Objectives

    By the end of this chapter, you will be able to:
    • Describe the different control statements in Python
    • Control program execution flow using control statements such as if and while
    • Use looping structures in your Python programs
    • Implement branching within looping structures such as for and range
    • Implement breaking out of loops
    This lesson describes the Python program flow and how we can change the flow of execution using control statements such as if, while, for, and range.

    Introduction

    Previously in this book, we covered the following topics:
    • The Python interpreter
    • Python syntax
    • Values and data types
    In this chapter, we are going to build on the knowledge that we have acquired so far to dive deeper into the beautiful language that is Python. In this chapter, we will explore how Python handles control statements—in simple terms, how Python handles decision making, for instance, resulting to True if 2 + 3 = 5 .
    In this chapter, we will also dive deeper into program flow control. In particular, we will look at how we can run code repeatedly or in a loop. Specifically, we will cover the following topics:
    • Python program flow
    • Python control statements, that is, if and while
    • The differences between if and while
    • The for loop
    • The range function
    • Nesting loops
    • Breaking out of loops

    Control Statements

    Like most programming languages, Python supports a number of ways to control the execution of a program by using control statements. Some of them might already be familiar, while others are unique to Python either in terms of syntax or execution.
    In this chapter, we will delve into controlling program flow and start working on building more structured programs. This should also prepare us for learning various kinds of loops later in this chapter. To start us off, we are going to define some terms:
    • Program flow
    • Control statement

    Program Flow

    Program flow describes the way in which statements in code are executed. This also includes the priority given to different elements.
  • Book cover image for: Python for Linguists
    If it is false, none of them is executed. A simple augmentation of the if structure is the else clause. This is a block of code that executes if the if test evaluates to false. The else statement follows the first block of code and is at the same level of indentation as the initial if clause. For example: if 2+2==5: #only else block executes print("this won't print") 3.2 if 33 else: print('but this will') print('...and so will this') control12.py If the if clause evaluates to true, the else block will not execute: if 2+2==4: #else-block does not execute print('this will print') else: print("but this won't") print('...and neither will this') control13.py Finally, one can add any number of elif clauses to an if structure. These add additional contingent tests to the structure. The syntax is like this: if test1 block1 elif test2 block2 elif test3 block3 ... else blockn We can represent graphically which blocks in the example just above are executed depending on which tests evaluate to true: test1 test2 test3 what applies? True True True block1 True True False block1 True False True block1 True False False block1 False True True block2 False True False block2 False False True block3 False False False blockn 34 Control Structures Notice how if test1 is true, block1 applies regardless of the truth or fal- sity of any other test. If test1 is false and test2 is true, block2 applies regardless of whether test3 is true. Finally, the else block applies only if all previous tests are false. A final complication is that it may sometimes be convenient to have an empty block. Imagine you want to test a string for whether the first letter is 'a', but then do something in all other cases. One way to do this is to test for that, but then put your code in the else block. The problem with this is that you would then have an empty block following the if test, which is not allowed in Python.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.