Conditionals


Python.

Python program control flow is regulated by various types of statements. By default the instructions in a program are executed in a sequential manner (step-by-step), from start to end. However, sequentially executing programs can perform only simplistic tasks.

We would like the program to have decision-making ability, so that it performs different steps depending on different conditions. Python provides this functionality through two different statements: Decision Making Statements (Conditional Statements) and Iterative Statements (Loops).

This module is all about learning Python supported conditional statements. Topics to be included:


Challenges

An if statement in Python evaluates if some conditional is true or false. It contains a logical expression that compares some data (variables, program state, etc.), and a decision is made based on the result of that expression.

Python if statement syntax:

if EXPRESSION:
	# statement(s) to be executed if EXPRESSION is true

If the expression evaluates to true, then the statement(s) inside of the if block are executed. If the expression evaluates to false, then the code inside the if block is essentially skipped and the code after the end of the if block is executed.

Example of Python if statement:

discount = 0
total = 1200

if amount > 1000:
	discount = amount * 10 / 100
  
print("Total: {}".format(amount-discount))

Challenge:

Use python to determine which number is greater than another number. Remember that if an if statement doesn't evaluate to True, then the inside code doesn't run!

  1. Create a new file with the file extension .py
  2. Write python code to accept two integers (x, y) from user input
  3. Write python code that prints out which number is larger, using if statements.
# Example Running of the program
python yourScript.py
X: 15
Y: 23
23 is greater than 15
# Another Example
python yourScript.py
X: 15
Y: 5
15 is greater than 5
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

An if-else statement operates similarily to an if statement, except it provides an additional block of code to run if the conditional evaluates to false.

Python if-else statement syntax:

if EXPRESSION:
	# statement(s) to be executed if EXPRESSION is true
else:
	# statement(s) to be executed if EXPRESSION is false

If the expression evalues to true, then the statement(s) inside of the if block are executed. If the expression evaluates to false, then the code inside of the else block are executed.

Example of Python if-else statement:

age = 25
print("age: ", age)

if age >= 18:
	print("Eligible to Vote!")
else:
	print("Not Eligible to Vote!")

Challenge:

Use python to determine if a number is even or odd

  1. Create a new file with the file extension .py
  2. Write python to accept an integer from user input
  3. Write the python code to determine if the number entered is even or odd
# Example Running of the program
python yourScript.py
Enter a number: 15
15 is odd
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Python also supports nested conditional statements which means we can use an if or if-else statement inside of an existing if or if-else statement.

Python Nested Conditional Statement Syntax:

if EXPRESSION1:
	# statement(s) to be executed if EXPRESSION1 is true
  if EXPRESSION2:
  	# statement(s) to be executed if EXPESSION1 and EXPRESSION2 is true

Example of Python Nested Conditional Statements:

number = 36
print("number= ", number)

if number % 2 == 0:
	if number % 3 == 0:
  		print("Divisible by 3 and 2")

Again, nesting isn't just limited to if statements. Say we have the following example: We offer different rates of discount on different purchase prices. - 20% on amounts exceeding 10000 - 10% on amounts between 5000 - 10000 - 5% on amounts between 1000 - 5000 - No discounts on amounts under 1000

amount = 2500
print("Amount: ", amount)

if amount > 10000:
  discount = amount * 20 / 100
else:
  if amount > 5000:
    discount = amount * 10 / 100
  else:
    if amount  > 1000:
      discount = amount * 5 / 100
    else:
      discount = 0

print("Total: ", amount - discount)

Challenge:

Use python to write a simple ATM system

  1. Create a new file with the file extension .py
  2. Write python code that gets two integers from the user (current balance, and amount to withdraw)
  3. Write a simple python ATM system, using nested conditionals, that can do the following:
    1. If a user requests to withdraw an amount greater than their current balance, print an insufficient funds message
    2. If a user requests to withdraw a negative amount, print an error message
    3. If the user requests to withdraw an amount that is not a multiple of 20, print an error message
    4. If the withdrawal is successful, deduct the amount from the balance and print the new balance
  4. Write the python code that print a message indicating the result of the transaction
# Example Running of the program
python yourScript.py
Balance: 15
Withdraw: 20
Error: Insufficient funds
# Another Example
pyton yourScript.py
Balance: 120
Withdraw: 20
New Balance: $100
# Another Example
pyton yourScript.py
Balance: 120
Withdraw: -20
Error: Withdraw Amount Must Be Positive
# Another Example
pyton yourScript.py
Balance: 150
Withdraw: 45
Error: Withdraw Amount Must Be a Multiple of 20
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Now, there might be a case in which you need to check multiple expressions to be true. If this is the case Python if-else statements support an additional way to check an expression - the elif block. This works similar to the else block, as the elif is also optional. However, an if-else block can contain only one else block, whereas there can be as many elif block as necessary following an if block.

Python if-elif-else statement syntax:

if EXPRESSION1:
	# statement(s) to be executed if EXPRESSION1 is true
elif EXPRESSION2:
	# statement(s) to be executed if EXPRESSION2 is true
else:
	statement(s) to be executed if EXPRESSION1 and EXPRESSION2 are false

The keyword elif is a short form of else if. It allows the logic to be arranged in a cascade of elif statements after the first if statement. If the first if statement evaluates to false, subsequent elif statements are evaluated one by one and comes out of the cascade if any one is satisfied. Lastly, the else block will be executed only if all the preceding if and elif conditions fail.

Using the example we covered in the Nested Conditional Section, we can get a simplied if-else statement that looks like this:

amount = 2500
print("Amount: ", amount)

if amount > 10000:
	discount = amount * 20 / 100
elif amount > 5000:
	discount = amount * 10 / 100
elif amount > 1000:
	discount = amount * 5 / 100
else:
	discount = 0
  
print("Total: ", amount - discount)

Challenge:

Use python to compare two numbers, printing the comparison result

  1. Create a new file with the file extension .py
  2. Write python to accept two integers (x, y) from user input
  3. Write the python code to determine if x is greater than, equal to, or less than y and prints the result
# Example Running of the program
python yourScript.py
X: 15
Y: 25
x (15) is less than y(25)
# Another Example Running of the program
python yourScript.py
X: 35
Y: 25
x (35) is greater than y(25)
# Example Running of the program
python yourScript.py
X: 15
Y: 15
x (15) is equal to y(15)
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Lastly, Python also supports logical operators. These allow you to combine two or more conditionals in one statement. These are the two supported logical operators we care about at this time:

Operator Name Example Meaning
and AND CONDITIONAL1 and CONDITIONAL2 Both CONDITIONAL1 and CONDITIONAL2 must be True to pass. If one is false it fails.
or OR CONDITIONAL1 or CONDITIONAL2 Either CONDITIONAL 1 or CONDITIONAL2 can be True to pass. If both are false it fails.

Example of Python Logical Operators:

number = 5
if number > 2 and number < 7:
    # Since 'number' is greater than 2
    # AND 'number' is less than 7
    # This if statement will equate to true
    # and print.
    print("True!")

if number < 1 or number >= 5:
    # Since this is an OR statement
    # only one of these conditions
    # needs to be satisfied in order
    # to equate to true.
    # The second statement is satisfied
    # because 'number' is greater than
    # or equal to 5.
    print("True!")

One thing to note, logical operators can be used inside of if and elif conditionals. If you use and the statement evaluates to true only if all the conditionals are true. If you use or the statement evaluates to true if one of the conditionals is true.

Challenge:

Use python to write a Student Classification System

  1. Create a new file with the file extension .py
  2. Write python code that gets two integers from the user (average test score, and attendence)
  3. Use conditionals with logical operators to determine a classification, under the following conditions:
    1. Average Test Score greater than or equal to 85 and an attendance greater than or equal to 90 means they are honors
    2. Average Test Score greater than or equal to 70 and an attendance greater than or equal to 75 means they are passing
    3. Anything else is falling
  4. Write the python code that prints the student's classification
# Example Running of the program
python yourScript.py
Average Test Score: 90
Attendance: 95
Student is a Honors Student
# Another Example
python yourScript.py
Average Test Score: 15
Attendance: 5
Student is a Failing Student
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py


30-Day Scoreboard:

This scoreboard reflects solves for challenges in this module after the module launched in this dojo.

Rank Hacker Badges Score