Skip to main content

Command Palette

Search for a command to run...

If, Else and While in Python

Updated
2 min read
If, Else and While in Python

As I continue learning Python, I couldn't have missed if, else, and while functions as they are real principles of all programming. I have learned about these in C++ while I was learning to code for Arduino. The concept is pretty similar.

If/Else Function

The if-else statement executes both the true and false parts of a given condition. The if block code is run if the condition is true, and the else block code is executed if the condition is false. I have seen a learned weight units converter in my tutorial. As inspired by that I have written a code of temperature converter. Code is below:

temperature = int(input("What's the temperature?: "))
unit = input ("(F)Fahrenheit or (C)Celcius: ")
if unit.upper() == "F":
    converted=(temperature-32)*0.5556
    print("Temperature in Celcius: " + str(converted))
else:
    converted=(temperature*1.8)+32
    print("Temperature in Fahrenheit : " + str(converted))

What's the temperature?: 200
(F)Fahrenheit or (C)Celcius: F
Temperature in Celcius: 93.3408

Also, weight units converter:

weight converter.png

While Function

In Python, the while loop is used to run through a block of code as long as the test expression (condition) is true. This loop is typically used when we don't know how many times to iterate ahead of time.

i=1
while i <=4:
print(i)
i=i+1

Result:

1
2
3
4

The value ıd "i" can also be multiplied. Here is a little "joke" that I have made to use this property.

multiply.png

T

that the beautiful illustration for a beginner the main that i like in this article is you try to explain the concept using code snippet though i am a c++ programmer still i can easily understand the concept keep writting and i got some inspiration from you for writting some article

1
İ

Thank you very much :)

More from this blog

B

Blog of İlke Candan Bengi

44 posts

I am writing about Python, machine learning, robotics and data science