Python for Beginners  Part-2

Python for Beginners Part-2

Lists, Loops & Control Statements and Functions - The Pillars of Python Programming

In my previous blog, you learned some basics about Python. So now let's cover some more important topics.


1) Working With List

Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data. It is created using square brackets:

list_1 = ["apple", "banana", "cherry"]
print(list_1)

List items are ordered, changeable, and allow duplicate values. When we say that lists are ordered, it means that the items have a defined order, and that order will not change.

If you add new items to a list, the new items will be placed at the end of the list.

Note: Some list methods will change the order, but in general: the order of the items will not change.

1.2) List Indexing

List items are indexed and you can access them by referring to the index number:

list_1 = ["apple", "banana", "cherry"]
print(list_1[1])

Negative Indexing:

Negative indexing means starting from the end.

-1 refers to the last item, -2 refers to the second last item etc.

list_1 = ["apple", "banana", "cherry"]
print(list_1[-1])

1.3) Check if Item Exists

To determine if a specified item is present in a list we use the in keyword:

list_1 = ["apple", "banana", "cherry"]
if "apple" in list_1:
  print("Yes, 'apple' is in the fruits list")

If you did not understand the above code, don't worry we will study the if statements in the next section.

1.4) Changing List Values

To change the value of a specific item, we need to refer to the index number. For Example:

list_1 = ["apple", "banana", "cherry"]
list_1[1] = "orange"
print(list_1)

1.5) Python - List Methods

Here is the set of built-in methods that you can use on lists.

MethodDescription
append()Adds an element at the end of the list
clear()Removes all the elements from the list
copy()Returns a copy of the list
count()Returns the number of elements with the specified value
extend()Add the elements of a list (or any iterable), to the end of the current list
index()Returns the index of the first element with the specified value
insert()Adds an element at the specified position
pop()Removes the element at the specified position
remove()Removes the item with the specified value
reverse()Reverses the order of the list
sort()Sorts the list

2) If...Else Statement

Here are some usual logical conditions from mathematics in Python:

  • Equals: a == b

  • Not Equals: a != b

  • Less than: a < b

  • Less than or equal to: a <= b

  • Greater than: a > b

  • Greater than or equal to: a >= b

These conditions are commonly used in "if statements" and loops.

If statement can be used in this way:

a = 33
b = 200
if b > a:
  print("b is greater than a")

Note: Python relies on indentation (whitespace at the beginning of a line) to define the scope of the code. Other programming languages like C++ use curly brackets for this purpose.

In this example, we use two variables, a and b, which are used as part of the if statement to test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print "b is greater than a".

2.1) Elif

The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition".

Example:

a = 33
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")

In the above example a is equal to b, so the first condition is not true, but the elif condition is true, so we printed "a and b are equal".

2.3) Else

The else keyword catches anything which isn't caught by the preceding conditions (if and elif).

Example:

a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

In the above example, a is greater than b, so the first condition is not true, also the elif condition is not true, so we go to the else condition and print "a is greater than b".

You can also have an else without the elif:

a = 200
b = 33
if b > a:
  print("b is greater than a")
else:
  print("b is not greater than a")

3) Working with Loops

Python has two loop commands:

  • while loops

  • for loops

3.1) The while Loop

With the while loop, we can execute a set of statements as long as a condition is true.

#Print i as long as i is less than 6
i = 1
while i < 6:
  print(i)
  i += 1

Note: Remember to increment i, or else the loop will continue forever.

The while loop requires relevant variables to be ready, in the above example we need to define an indexing variable, i, which we set to 1.

3.1.1) break Statement in while Loop

With the break statement, we can stop the loop even if the while condition is true:

#Exit the loop when i is 3
i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  i +=

3.1.2) continue Statement in while Loop

With the continue statement, we can stop the current iteration, and continue with the next:

#Continue to the next iteration if i is 3
i = 0
while i < 6:
  i += 1
  if i == 3:
    continue
  print(i)

3.1.3) else Statement

With the else statement, we can run a block of code when the condition is no longer true:

#Print a message once the condition is false
i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")

3.2) The For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

This is less like the 'for' keyword in other programming languages and works more like an iterator method as found in other object-orientated programming languages.

With for loop, we can execute a set of statements, once for each item in a list, tuple, set etc.

#Print each fruit in a fruit list
fruits = ["apple", "banana", "cherry"]
for i in fruits:
  print(i)

3.2.1) break Statement in for Loop

With the break statement, we can stop the loop before it has looped through all the items:

#Exit the loop when i is "banana":
fruits = ["apple", "banana", "cherry"]
for i in fruits:
  print(i) #Banana gets printed and then the loop will break 
  if i == "banana":
    break

# Output: 
# apple
# banana
#Exit the loop when i is "banana", but this time the break comes 
#before the print
fruits = ["apple", "banana", "cherry"]
for i in fruits:
  if i == "banana":
    break
  print(i) #this will only be executed if i is not banana

# Output: 
# apple

3.2.2) continue Statement in for Loop

With the continue statement, we can stop the current iteration of the loop, and continue with the next:

#Do not print banana
fruits = ["apple", "banana", "cherry"]
for i in fruits:
  if i == "banana":
    continue
  print(i)

# Output:
# apple
# cherry

3.2.3) Nested Loops

A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

#Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for i in adj:
  for j in fruits:
    print(i, j)
# Output:
# red apple
# red banana
# red cherry
# big apple
# big banana
# big cherry
# tasty apple
# tasty banana
# tasty cherry

4) Working with Functions

A function is a block of code that only runs when it is called. You can pass data, known as parameters, into a function.

A function can return data as a result.

4.1) Creating and Calling a Function

In Python, a function is defined using the def keyword:

def my_function():
  print("Hello from a function")

To call a function, use the function name followed by parenthesis:

def askQuestion():
  print("Hello, How are you?")

askQuestion()

4.2) Arguments

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (name). When the function is called, we pass along a name, which is used inside the function to print:

def greetings(name):
  print("Hello", name)

greetings("Vineet")
greetings("Sushant")
greetings("Arpit")

# Output:
# Hello Vineet
# Hello Sushant
# Hello Arpit

Parameters vs Arguments?

From a function's perspective:

A parameter is the variable listed inside the parentheses in the function.

An argument is the value that is sent to the function when it is called.

So, the terms parameter and argument can be used for the same thing: information that is passed into a function.

4.3) Number of Arguments

The function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.

#This function expects 2 arguments, and gets 2 arguments:
def fullName(f_name, l_name):
  print(f_name + " " + l_name)

fullName("Vineet Singh", "Negi")
fullName("Sushant", "Kumar")
fullName("Arpit", "Pandey")+

# Output:
# Vineet Singh Negi
# Sushant Kumar
# Arpit Pandey

If you try to call the function with 1 or 3 arguments, you will get an error.


So in this tutorial, we explored Lists, Loops & Control Statements and Functions in Python. By mastering these topics, you can enhance your Python programming skills.

In my upcoming blog, I will be covering File Handling in Python.

Until then take care, Happy Learning!

Thanks for Reading!