4th Street Bar Hive-Bar

Hive-Bar Powered by Hive beta-fdb5b5b

Community post

Let's Learn Python - 2 ๐Ÿ | Loops

(This post is best viewed on Steempeak.com)

H


i once again !! ๐Ÿ‘‹
Hope you liked the previous article Let's Learn Python ๐Ÿ, and it helped give you a mild flavor of what Python is.

In this article we'll go ahead and try to learn loops in Python.

(This article will be a continuation of the last one, so if you have not read the last one, I strongly urge you to read it before you start this one.)
(The worst piece of code I could find on Pixabay! Never forget to properly space, indent and comment your code. It should be legible and readable!)

Starting where we left...

Last time, I left you with a problem: > **Problem:** Can you write Python code to print numbers from 1 - 1000? (Without explicitly stating all the numbers.) > Let's try solving it right away, I'll directly give you the code to ponder upon, later we'll see how it works when we formally describe *loops* and their different types.

Let's see if the following piece of code can do our work:

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

image.png
...and there, we got the desired output with just a 4-liner code!

Notice: The i+=1 in the code. This statement contains the compound augmented operator += we discussed in the previous article. i=1 gives i the initial value of 1. Rest is all logical.

NOTE: i is often referred to as the sentry variable or more generally a counter.


Okay! Before we move into loops, we'll try to learn a few interesting things:

  • Using range:
    Just look at this piece of code for a while, and you should be able to make out what it's doing...
print(*range(0, 10, 1))
print(*range(0, 10, 3))

print(range(0, 10, 1))
print(*range(1, 11, 1))
![image.png](https://files.steempeak.com/file/steempeak/aakashsinghbais/o1bZvAYu-image.png)
>**NOTE:** >1. The first line in the code simply prints no.s. from `0 to 10 with an interval of 1 unit`. >2. The second line prints no.s. from `0 to 10 with an interval of 3`. >3. The third prints the `range(0, 10) with interval of 1. This defaults to range(0, 10)`. >3. The fourth prints `range(1, 11) with interval of 1 which also defaults to range(1,11)`, but is printed explicitly due to *. >>**NOTE:** * is used to print the ranges explicitly. >> Now, you may be wondering why we used `for` Loop in the question I gave you! ๐Ÿ˜ƒ Well, yes frankly speaking even I am wondering! Haha! Never mind, it is true that we can print the numbers from 1 to 1000 using `range()` as well:
```python print(*range(1, 1001)) ```
![image.png](https://files.steempeak.com/file/steempeak/aakashsinghbais/UUlIGyXP-image.png)
- ****

ย  3.2. Loops in Python

Python has 2 basic loops: - **For Loop** --> `for` The syntax for this loop is: ```python for in : <...and this> ``` - **While Loop** --> `while` The syntax for *while loop* looks like this: ```python while : ```

(While Loop Flowchart | **Source:** Wikimedia Commons)
Okay, so now I guess though the `while` Loop is a bit self-explanatory, but the `for` Loop may need a bit of examples to understand.
So, let's see a few examples of both of these: - `for`Loop: >**Example - 1)** Let's try to print the numbers from 1-1000 using `for` Loop. >```python >for x in range(1, 1001, 1): > print(x) >``` >![image.png](https://files.steempeak.com/file/steempeak/aakashsinghbais/ifKKmZgA-image.png) >...that was easy! wasn't it?...we got all the numbers printed one below the other. Now, let's try a more useful and challenging program... > >**Example - 2)** Let's write a python program which allows the user to check whether we have a particular fruit in our basket containing apple, mango, guava, avocado, coconut, pineapple...or not. >```python >basket=("apple", "mango", "guava", "avocado", "coconut", "pineapple") >fruit=input("Please pick a fruit to see if it is in your basket. Type it's name to pick.") >for x in basket: > if(x==fruit): > print("CONGRATULATIONS! We have ", fruit, "in our basket") >``` >![image.png](https://files.steempeak.com/file/steempeak/aakashsinghbais/mdujaVvA-image.png) >>**NOTE:** >>1. In the above example we have defined the variable `basket` and have stored a set of strings in it. So, `basket` is technically speaking a ***tuple*** (as of now, you can consider it as a list of objects). >>2. `input()` is a function used to take input from the user. In our case, `input()` takes the name of the fruit from the user (anything specified within this function is printed as a text to direct the user to input the desired things. It acts just like `print()`), and assigns the string entered by the user to the variable `fruit`. >>3. The other thing that is important to notice is the fact that in `if(x==fruit)`, we are using operator `==` instead of `=`. Reason being that using the latter would assign `x` the value contained in `fruit`, while `==` only checks whether the two are equal. > - **`while` Loop:** >Okay, we have already seen a problem which we solved using `while`. Let's try one more: >**Example - 1)** Let's write a program to print the multiplication table of 2. >```python >i=1 >while(i<=10): > print("2 x ", i, "=", 2*i) > i+=1 >``` >![image.png](https://files.steempeak.com/file/steempeak/aakashsinghbais/cTLUtP7i-image.png) >Well!! That was simple wasn't it? If you are confused, try to read the code line-by-line, and logically think what each line is doing, and how the computer will understand the code. >

Okay, that was simple! But here is an important advice and a note of caution:

NOTE:
Indentation is very important in Python. If you wrongly indent the code, then the interpreter will understand it differently.

For example:

if(x==5):
	<do task-A>
	<do task-B>

..means, if x is equal to 5, do tasks A and B.
Whereas,

if(x==5):
	<do task-A>
<do task-B>

...would mean: if x is equal to 5, do task A. After if block has been implemented, do B (irrespective of the value of x).

Okay, now we somewhat have an idea of basic loops in Python. These loops can be put one-inside the other i.e. they can be nested.

I introduced the operator ==. So, now that we already know one, let's have a look at the others as well:

  • Logical Operators in Python:
    image.png
  • Boolean Operators in Python:

I hope that understanding these operators shouldn't be a difficult task, you can also try using them in if, for and while loops.


That's all for today, hope that you are enjoying these short lessons.
NOTE: Unless otherwise stated, all pictures are mine, and have been taken from my own notes, or are my VS Code screenshots.

With this I'll take your leave.

Thanks for sparing your time!
Keep slithering !!
Best,
Aakash
282 upvotes $1.76

Replies (6)

Review before signing

Posting as . Signing with . Keychain permission: Posting. Hive Keychain will ask you to approve this action next.


  
Technical details

Operation fingerprint: