This time we will work on if, elif, else.
The same content is also published in the video, so please have a look if you like.
When writing a program, there are situations where you want to make different operations depending on the conditions.
Now put 1 in the variable num.
If num is 1, 1 is output. When they are the same, they are written as ==.
num = 1
if num == 1:
print(1)
1
I haven't touched on the case where num is other than 1, so if you set it to 2, nothing will come out.
Create another condition to output the condition of 2 as it is at the time of 1.
Here we use elif.
num = 2
if num == 1:
print(1)
elif num == 2:
print(2)
2
There is no problem in writing any number of elif.
num = 3
if num == 1:
print(1)
elif num == 2:
print(2)
elif num == 3:
print(3)
3
However, if you write one by one, it may not be sharp.
At that time, use else.
num = 4
if num == 1:
print(1)
elif num == 2:
print(2)
elif num == 3:
print(3)
else:
print("others")
others
By doing this, the same operation will be performed uniformly under the conditions not mentioned by if or elif.
Up to this point, we used numbers, but of course we can also use letters.
At this time, the rules such as the principle of if, elif, else and == remain the same.
ans = "yes"
print("Thank you for subscribing to the channel")
if ans == "yes":
print("thanks")
else:
print("please")
Thank you for subscribing to the channel
thanks
If, elif, else will come out frequently in the future, so let's get used to it now.