3-1-3-2. Conditional Statements

We’ve been running code that simply executes every line one by one from the top down.

Many times however, we want to run code only if a particular condition holds.

To demonstrate this concept,

let’s take a look at this billing system for a pay-as-you-go mobile phone.

Say a customer has a credit balance for

their phone which they can use for calls and messages.

The customer can then set up a link to their bank account so that

if their phone credit balance goes below a threshold amount,

in this case five dollars,

then 10 more dollars of credit are added and their bank balance is build.

Here is a simple way of representing this billing system in code.

If the phone balance is below five,

add 10 to phone balance and subtract 10 from bank balance.

This is an example of an if statement.

An if statement is a conditional statement that runs or

skips code based on whether a condition is true or false.

In an if statement, the if keyword is followed by the condition to be checked,

in this case, phone balanced less than five,

and then a colon.

The condition is specified in

a Boolean expression that evaluates to either true or false.

After this line is an indented block of code to be executed if the condition is true.

So in this case,

these lines will only execute if it is true that phone balance is less than five.

If phone balance is three,

this condition evaluates to true and these indented lines of code are executed.

You can observe these changes in the output.

If phone balance is eight however,

this condition evaluates to false and these lines are not executed.

As you see in the output,

there were no changes to phone or bank balance,

which is what we expect to happen since the condition in this if statement was false.

우리는 위에서 아래로 모든 라인을 단순히 실행하는 코드를 실행했습니다.

그러나 여러 번 특정 조건이 유지되는 경우에만 코드를 실행하려고 합니다.

이 개념을 보여주기 위해,

종량제 휴대전화에 대한 이 청구 시스템을 살펴보겠습니다.

고객에게 신용 잔액이 있다고 가정해 보겠습니다.

통화 및 메시지에 사용할 수 있는 전화.

그런 다음 고객은 은행 계좌에 대한 링크를 설정할 수 있습니다.

전화 크레딧 잔액이 기준 금액 미만인 경우

이 경우 5달러,

그런 다음 10달러의 신용이 더 추가되고 은행 잔고가 쌓입니다.

다음은 이 청구 시스템을 코드로 나타내는 간단한 방법입니다.

폰 잔고가 5미만이면

전화 잔액에 10을 더하고 은행 잔액에서 10을 뺍니다.

이것은 if 문의 예입니다.

if 문은 다음을 실행하는 조건문입니다.

조건이 참인지 거짓인지에 따라 코드를 건너뜁니다.

if 문에서 if 키워드 뒤에 검사할 조건이 옵니다.

이 경우 전화 균형이 5 미만,

그리고 콜론.


true 또는 false로 평가되는 부울 표현식입니다.

이 줄 뒤에는 조건이 참인 경우 실행할 들여쓰기된 코드 블록이 있습니다.

따라서 이 경우,

이 라인은 전화 잔고가 5 미만인 것이 사실인 경우에만 실행됩니다.

폰 잔고가 3이면

이 조건은 true로 평가되고 이러한 들여쓰기된 코드 행이 실행됩니다.

출력에서 이러한 변경 사항을 관찰할 수 있습니다.

하지만 폰 잔액이 8이라면,

이 조건은 거짓으로 평가되고 이 행은 실행되지 않습니다.

출력에서 볼 수 있듯이,

전화 또는 은행 잔고에 변동이 없었습니다.

이것은 이 if 문의 조건이 거짓이기 때문에 일어날 것으로 예상되는 일입니다.

그러면 우리는 식물이 정원임을 알 수 있습니다.

첫 번째 조건이 true로 평가될 때 인쇄됩니다.

또는 계절을 겨울로 설정하면

그러면 이러한 각 조건은 다음을 가질 때까지 false로 평가됩니다.

true로 평가되고 인쇄되는 이 조건은 실내에 유지됩니다.

여기에서 이중 등호를 다시 사용하고 있습니다.

하나의 등호는 우리가 했던 것처럼 할당을 위한 것임을 기억하십시오.

여기에서 시즌을 특정 문자열로 설정했습니다.

두 개의 등호는 조건을 참 또는 거짓으로 평가하는 평가를 위한 것입니다.

If Statement

An if statement is a conditional statement that runs or skips code based on whether a condition is true or false. Here’s a simple example.

if phone_balance < 5:
    phone_balance += 10
    bank_balance -= 10

Let’s break this down.

  1. An if statement starts with the if keyword, followed by the condition to be checked, in this case phone_balance < 5, and then a colon. The condition is specified in a boolean expression that evaluates to either True or False.
  2. After this line is an indented block of code to be executed if that condition is true. Here, the lines that increment phone_balance and decrement bank_balance only execute if it is true that phone_balance is less than 5. If not, the code in this if block is simply skipped.

Use Comparison Operators in Conditional Statements

You have learned about Python’s comparison operators (e.g. == and !=) and how they are different from assignment operators (e.g. =). In conditional statements, you want to use comparison operators. For example, you’d want to use if x == 5 rather than if x = 5. If your conditional statement is causing a syntax error or doing something unexpected, check whether you have written == or =!

If, Elif, Else

In addition to the if clause, there are two other optional clauses often used with an if statement. For example:

if season == 'spring':
    print('plant the garden!')
elif season == 'summer':
    print('water the garden!')
elif season == 'fall':
    print('harvest the garden!')
elif season == 'winter':
    print('stay indoors!')
    print('unrecognized season')
  1. if: An if statement must always start with an if clause, which contains the first condition that is checked. If this evaluates to True, Python runs the code indented in this if block and then skips to the rest of the code after the if statement.
  2. elifelif is short for “else if.” An elif clause is used to check for an additional condition if the conditions in the previous clauses in the if statement evaluate to False. As you can see in the example, you can have multiple elif blocks to handle different situations.
  3. else: Last is the else clause, which must come at the end of an if statement if used. This clause doesn’t require a condition. The code in an else block is run if all conditions above that in the if statement evaluate to False.


Some other languages use braces to show where blocks of code begin and end. In Python we use indentation to enclose blocks of code. For example, if statements use indentation to tell Python what code is inside and outside of different clauses.

In Python, indents conventionally come in multiples of four spaces. Be strict about following this convention, because changing the indentation can completely change the meaning of the code. If you are working on a team of Python programmers, it’s important that everyone follows the same indentation convention!

Spaces or Tabs?

The Python Style Guide recommends using 4 spaces to indent, rather than using a tab. Whichever you use, be aware that “Python 3 disallows mixing the use of tabs and spaces for indentation.”

Try It Out!

Use Test Run to execute the following code, which includes several examples of if statements. Experiment with different inputs and see what is printed out. Can you follow the flow of logic to figure out which code lines will get run? If you’re not sure, you can insert additional print statements to help you figure out how it works.

#First Example - try changing the value of phone_balance
phone_balance = 10
bank_balance = 50

if phone_balance < 10:
    phone_balance += 10
    bank_balance -= 10


#Second Example - try changing the value of number

number = 145
if number
    print("Number " + str(number) + " is even.")
    print("Number " + str(number) + " is odd.")

#Third Example - try to change the value of age
age = 35

# Here are the age limits for bus fares
free_up_to_age = 4
child_up_to_age = 18
senior_from_age = 65

# These lines determine the bus fare prices
concession_ticket = 1.25
adult_ticket = 2.50

# Here is the logic for bus fare prices
if age <= free_up_to_age:
    ticket_price = 0
elif age <= child_up_to_age:
    ticket_price = concession_ticket
elif age >= senior_from_age:
    ticket_price = concession_ticket
    ticket_price = adult_ticket

message = "Somebody who is {} years old will pay ${} to ride the bus.".format(age, ticket_price)