Breaking

Saturday, 14 August 2021

Chapter 9 || If Statements Python || Python Conditional Statements: IF...Else, ELIF

 Chapter 9

If Statements Python

 

Assume you need to know whether the string allocated to the variable species is "cat."

This is the code.

 

1 if species == "cat":

2 print ("Yep, it's a cat.")

If the string "feline" has been allocated to the variable species, Python shows the message Yep, it's feline. On the off chance that the string "feline" hasn't been appointed to the variable species, nothing occurs.

We should figure out down the code.

It starts with the catchphrase if. Note that it is all lowercase. If you compose If rather than if, it will not work. You'll get a blunder message.

Note that it's two equivalent signs, ==, not one. One equivalent sign, =, must be utilized to allocate an incentive to a variable, as in…




species = " cat "


At whatever point you're trying whether one thing is equivalent to another, the administrator must be ==. Else, you'll get a blunder message.

The mainline closes with a colon.

 

1 if species == " cat ":

 

If the test passes—if the string "feline" has been allocated to the variable species—you instruct Python. You place this on its own line, and you indentation the line one tab.

 


1 if species == "cat":

2 print ("Yep, it's cat.")

 

You can make quite a few things happen when the response to the if the question is "yes." Each thing that happens gets its own line. What's more, each line is indented.

 

1 if species == "cat":

2 status = "Alright"

3 kingdoms = "animal"

4 print ("Yep, it's cat.")

 

There are different things you can test, including numbers. It works the equivalent way…

 

1 if 2 + 2 == 4:

2 print ("Everything bodes well.")

 

That test, obviously, will consistently come out evident, and the message will be shown.

Here's another, that may not generally come out obvious.

 

1 if some husbands == 1:

2 print ("So far so great.")

 

In Python, indents aren't only for a pretty design. They have significance for Python. They aren't discretionary. All in all, any lines of code that take their orders from a line that closes in a colon is indented. Examples:

 

1 if a number of husbands == 1:

2 print ("So far so great.")

3 print("Congratulations.")

4 print ("All done")

 

In the code above, lines 2 and 3 execute just if the if test in line 1 passes.

Their execution is subject to what occurs in line 1, so they're indented. Line 4 executes regardless. It runs freely of line 1, so it isn't indented.

 

What I'm saying here isn't carefully precise. Later on, you'll see some code that doesn't exactly fit what I'm saying. However, it's a helpful method to consider indents in Python. As a dependable guideline.


Chapter 1; 

Chapter 2; 

Chapter 3; 

Chapter 4; 

Chapter 5;

Chapter 8;


No comments:

Post a Comment

Adbox