Learning Python is fun

Welcome to ‘learning python is fun - for beginners’

Previous: Dictionaries

Next: For & While Loops

Conditional Programming

Lesson: 9

Besides numbers and strings, Python has several other types of data. One of them is the Boolean data type.
Booleans are extremely simple: they are either True or False.
Booleans, in combination with Boolean operators, make it possible to create conditional programs: programs that decide to do different things, based on certain conditions.

The Boolean data type was named after George Boole, the man that defined an algebraic system of logic in the mid 19th century.

Using Booleans

In computer science, booleans are used a lot. This has to do with how computers work internally. Many operations inside a computer come down to a simple “Yes or No” (True or False).
It’s important to note, that in Python a Boolean value starts with an upper-case letter: True or False.
This is in contrast to most other programming languages, where lower-case is the norm. In Python, we use booleans in combination with conditional statements to control the flow of a program:

>>> store_is_open = True
>>> if store_is_open:
...     print("buy milk")
...
buy milk

First, we defined a variable called store_is_open and set it to True. In the next line we made a conditional if-statement. It is followed by an expression that can evaluate to either True or False. If the expression evaluates to True, the block of code that follows is executed. If it evaluates to False, it is skipped. Go ahead and change store_is_open to Falseto see what happens.

>>> store_is_open = False
>>> if store_is_open:
...   print("buy milk")
...
>>>

if can be followed by an optional else block. This block is executed only when the expression evaluates to False. This way, you can run code for both options. Let’s try this:

>>> store_is_open = False
>>> if store_is_open:
...   print("buy milk")
... else:
...   print("learn python, you can buy milk later.")
...
learn python, you can buy milk later.

Thanks to our else-block, we can now print an alternative text if store_is_open is False. Here are some conditional challenges to exercise:

  1. Even or Odd: print whether a given number is even or odd.
  2. Positive or Negative: print whether a given number is positive, negative, or zero.
  3. Greater Number: print the greater of two given numbers.
  4. Largest of Three: print the largest of three given numbers.
  5. Vowel Check: print whether a given character is a vowel or not.
  6. Leap Year Check: print whether a given year is a leap year or not.
  7. Divisible Check: print whether a given number is divisible by another given number.
  8. Character Check: print whether a given character is an alphabet or not.
  9. Alphanumeric Check: print whether a given character is alphanumeric or not.
  10. Temperature Check: print whether a given temperature is freezing, normal, or hot based on Celsius scale.
click to run python

Conditional Operators

The ability to use conditions enables your software to make smart decisions, and allows it to change its behavior based on external input.

Decision making is done by using expressions that can evaluate to be True or False, And these expressions include some types of operators. There are multiple types of operators, We will now focus on Comparison operators and Logical operators

Comparison operators

OperatorDescriptionExample
>greater than2 > 1
<smaller than2 < 1
>=greater than or equal to5 >= 4
<=smaller than or equal to5 <= 5
==is equal3 == 3
!=is not equal1 != 2
>>> 2 > 1
True
>>> 2 < 1
False
>>> 1 < 2 < 3 < 4
True
>>> 1 < 5 > 2
True
>>> 5 <= 5
True
>>> 5 >= 4
True
>>> 3 == 3
True
>>> 1 != 2
True
>>> 'a' == 'a'
True
>>> 'a' > 'b'
False

As you might have noticed, these operators work on strings too. Strings are compared in the order of the alphabet, with 2 added rules:

  • Uppercase letters are ‘smaller’ than lowercase letters, e.g.: ‘M’ < ‘m’
  • Digits are smaller than letters: ‘1’ < ‘a’

Internally, theres logic behind these rules. each character has a number in a table, and the position in this table determines the order. You can checkout Wikipedia's Unicode page on to learn more about it.

Logical operators

OperatorDescriptionExample
andTrue if both statements are trueTrue and False == False
False and False == False
True and True == True
orTrue if one of the statements is trueTrue or False == True
True or True == True
False or False == False
notNegates the statement that followsnot True == False
not False == True
>>> True and True
True
>>> True or False
True
>>> not True
False
>>> not False
True
click to run python

Comparing different types

When you try to compare different types, you’ll often get an error:

>>> '10' > 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'str' and 'int'

This is how Python tells you it can’t compare integers to strings. There are types that can mix and match, but you should avoid mixing them as it makes your code much harder to understand. Here's an example of some bad practice with int and boolean:

>>> 1 == True
True
>>> 0 == False
True
>>> True + True
2
>>> False + False
0
>>> True + False
1
>>> True + 2
3

True has a value of 1 & False has a value of 0.
This is an internal representation of booleans as numbers in Python.

Proving your skills

I have gathered some basic conditional challenges for you

Try to solve these and sweet sale in confidence onto the next lesson.

  1. Number Range Check: print whether a given number is in the range [1, 10], [11, 20], or outside both ranges.
  2. Grade Check: print "Pass" if a given score is greater than or equal to 60, "Fail" otherwise.
  3. Time of Day: print "Good morning" if the current hour is before noon, "Good afternoon" if it's between noon and 5 PM, and "Good evening" otherwise.
  4. Weekday Check: print "Weekday" if the current day is Monday to Friday, "Weekend" otherwise.
  5. Month Check: print "30 days" for months with 30 days, "31 days" for months with 31 days, and "28/29 days" for February.
  6. Discount Check: print "No discount" if the price is less than $50, "10% discount" if it's between $50 and $100, and "20% discount" if it's over $100.
  7. BMI Category: print "Underweight" if BMI is less than 18.5, "Normal weight" if it's between 18.5 and 24.9, "Overweight" if it's between 25 and 29.9, and "Obese" if it's 30 or more.
  8. Ticket Price: print the ticket price based on age: "Free" for ages 0-5, "Child" for ages 6-12, "Adult" for ages 13-59, and "Senior" for ages 60 and above.
  9. Weather Forecast: print "Sunny" if the weather is clear, "Cloudy" if it's cloudy, and "Rainy" if it's raining.
  10. Password Strength: print "Weak" for passwords less than 6 characters, "Medium" for passwords between 6 and 10 characters, and "Strong" for passwords longer than 10 characters.
click to run python

Lesson Completed 👏

Great job! 🍺🍺“🎉“🎉

In the next lesson we will learn all about Python For Loops & While Loops

Previous: Dictionaries

Next: For & While Loops