Logical EN

Logical EN Titelbild


We have already looked at the if condition and while loop and you should have noticed that they both have one thing in common, they need a condition. If this condition is true the intended code below will be executed.

Up to now we have only used the equal operator which checks if two values are the same.

myAge = 15  
if myAge == 15:
     print("Your are 15 years old!")

This condition is saying: “If the variable myAge is equal to 15 then execute everything which is intended, in our case line 3”. There are so many more operators than just the equal operator. Imagine you want to program a game and want to integrate an age limitation into your programming. This could look like something like below:

myAge = 15
if myAge > 15:
     print("You are old enough")

This condition is saying: “If the content of the variable myAge is bigger than 15, then execute everything which is intended.” In contrast, you could do the same for people who are not 15.

myAge = 15  
if myAge != 15:
print("You are not allowed to play the game")

This condition is saying: “If the content of the variable myAge is not equal to 15, then execute everything which is intended”.

And for people who like complicated problems:

myAge = 10

if (myAge == (36/6) + 4)):
     print ("You like math.")

These are just a few example but there are many more of these so called operators. In the following table we prepared some of them for you.

Operator Function Example
Mathematical Operators
+, - Add, subtract 1+1 = 2
2-1 = 1
*, / Mulitply, Divide 3*3 = 9
36/6 = 6
% Modulo 3 % 3 = 0
Logical Operators
>, Smaller or bigger as 512>42 is false
= smaller or equal, bigger or equal 6>=6 is true
!= Not equal 6 != 6 is false
5 != 42 is true
== equal 5 == 5 is true
4 == 8 is false

After all this theory we have some action for you. You may be asking yourself why there are so many operators and what they are good for. We prepared an example answer to help clarify this for you:

numberOne = input("Please enter the first number: ")
numberTwo = input("Please enter the second number: ")
result = int(numberOne) + int(numberTwo)
print("The result is: "+ str(result))

With this small program you have built yourself a really simple calculator.

It is your turn! Try out another mathematical calculator.

import time

seconds = input("Set the stop clock: ")
seconds = int(seconds)

while seconds > 0:
    seconds = seconds - 1

This is a simple stopwatch example. In the beginning you can decide how long the stopwatch will run and then you will see the countdown. It’s your turn: Can you use what you have learned to create a program that turns the eyes on the Unicorn Shield on when the countdown is reached?

Noch Fragen oder Feedback?

Bevor du eine Frage stellen kannst musst du dich zuerst Anmelden oder Regestrieren!