Sunday, April 20, 2025

Python If, elif, else

With if statements we will do all kind of checks. For example, if x is smaller than y, we will just print: "x is smaller than y", and so on:


x = 20
y = 20

if x < y:
    print("x is smaller than y")
if x > y:
    print("x is bigger than y")
if x == y:
    print("They are Equal")

Result: 


They are Equal
>>> 

We can add "else" at the end of check, as the last possible case. In the middle of check you can use "elif", which is short for "else if":


x = 20
y = 20

if x < y:
    print("x is smaller than y")
elif x > y:
    print("x is bigger than y")
else:
    print("They are Equal")

Result: 


They are Equal
>>> 

It's fun to take input from keyboard:


x = input("Please enter x: ")
y = input("Please enter y: ")

if x < y:
    print("x is smaller than y")
elif x > y:
    print("x is bigger than y")
else:
    print("They are Equal")

Result: 


Please enter x: 555
Please enter y: 10
x is bigger than y
>>> 

When you know that you will need numbers, and not strings, convert what you take from keyboard into integers/floats with int() or float() function.


x = input("Please enter x: ")
y = input("Please enter y: ")

print("Before x and y are strings: ")
print(type(x))
print(type(y))

print("After we convert them, they are integers: ")
x = int(x)
y = int(y)

print(type(x))
print(type(y))

Result: 


Please enter x: 10
Please enter y: 50
Before x and y are strings: 
<class 'str'>
<class 'str'>
After we convert them, they are integers: 
<class 'int'>
<class 'int'>
>>> 

Now, we are absolutely sure that things from keyboard will be used as numbers, and not as strings (words):


x = int(input("Please enter x: "))
y = int(input("Please enter y: "))

if x < y:
    print("x is smaller than y")
elif x > y:
    print("x is bigger than y")
else:
    print("They are Equal")

Result: 


Please enter x: 50
Please enter y: 100
x is smaller than y
>>> 

In next tutorial, we will learn about While Loops.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...