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:
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.