Understanding Python(Part-3)

Ignoramus
4 min readAug 18, 2020

Loops:

Often while programming we come across repetition of codes. We need to repeat a set of lines again and again, here we use loops to shorten the lines of code and ease the effort. We have For loops, While loops and Nested loops. Let’s say we want to print a range of numbers from 0 to 2, we simply use range(3) command. The for loop enables you to execute a code multiple times.

we use for loop to print the numbers.

for number in range(3):

print(number)

# Example 2

for number in range(3):

print(“Attempt”,number+1)

# using condition in for loop

successful = True

for number in range(3):

print(“Attempt”)

if successful:

print(“Successful!”)

break

else:

print(“Attempted 3 times and failed!”)

successful = False

for number in range(3):

print(“Attempt”)

if successful:

print(“Successful!”)

break

else:

print(“Attempted 3 times and failed!”)

In above example we saw how the for loops runs when the condition is true and breaks out of the loop after first iteration, and how it iterates till the end when the condition is false and goes for else code to execute.

While loop is different from for loop, it runs as long as the conditions is true. And depending on the code it may get converted into infinite loop.

While loop

number = 100

while number > 0:

print(number)

number //= 2

# Integer division //

Here as long as the number is greater than 0, it will print the number and divide it with 2 and return an integer. Another example where we can see how while loop works.

# example 2

i = 1

while i <= 5:

print(i)

i+=1

print(“Done!”)

# example 3

i = 1

while i <= 5:

print(‘*’*i)

i += 1

print(“Done!”)

Nested loops:

They are loops in loop, have outer and inner loop. Iterates outer loop and they completes all iteration in inner loop and then outer loop execute the next iteration in which again the inner loop iterations are followed.

# example of nested loop

for x in range(5):

for y in range(3):

print(f”({x},{y})”)

Here we see how nested loop for iterating outer loop once and complete all in inner loop and going for the next outer iterations. Using for, while we can also iterate items in a list, can values in a list. The concept of infinite loop exist if we do not terminate the loop with a condition or break out of it.

Functions:

Functions are reusable block of code which performs specified operations. It let you break down task and allow you to reuse your code in different programs. There are many built in functions in python. The function name should be meaningful, descriptive, lowercase. It starts with defining shorten to def func_name( ): followed by code. We have to call the function to execute the code.

def greet():

print(“Hi There!”)

print(“Welcome!”)

greet()

Arguments: these are also called parameters. We list parameters when defining a function in between the parenthesis. Arguments are actual value of given parameters.

# example with arguments and parameters.

def greet(first_name,last_name):

print(f”Hi {first_name} {last_name}”)

print(“Welcome to Jumanji!”)

greet(“Rahul”,”Malhotra”)

# first_name & last_name are parameters

# “Rahul”,”Malhotra” are arguments

There are two types of functions predefined and user defined. Also we can say there are two type of functions, one which perform tasks and other that returns a value. In the above example we see that the function performs a task of greeting but returns no value. The default return to any function is none. Unless we mention any specific return value it always will return none.

# example of functions with return value.

def get_greet(name):

return f”Hi {name}”

message = get_greet(“Rahul”)

print(message)

# examples involving integers and floats types.

# Add function

def add(a):

b = a+1

print(a,”if you add one gives”, b)

return b

add(4)

# Multiply function

def multiply(a,b):

c = a*b

return c

multiply(3,4)

# We can try multiplying floats.

def multiply(a,b):

c = a*b

return c

multiply(10.0,3.14)

Function has variables. The ones declared inside it are called local variable, the ones declared outside the function definition are called global variable, and its value is accessible and modifiable throughout the program. Functions make things simple.

Pre-defined functions: existing function(built-in function) such as sum( ), print( ), etc. We can also use if/else statements and loops in a function definition. Lets see a example:

# if/else:

def type_of_album(artist,album,year_released):

print(artist,album,year_released)

if year_released > 1980:

return “Modern”

else :

return “Oldie”

y = type_of_album(“Drake”,”God’s Plan”,2007)

print(y)

# loops:

def print_list(the_list):

for element in the_list:

print(element)

print_list([“Cooking oil”,”Garlic”,”Spices”,”Flour”])

We can see how the loops and if/else statement are implemented in a function definition and works when the function is called. And if only there is any print statement included or return of values then the output will be shown otherwise we will have to store the function in a variable and print the variable. Default arguments can also be set while defining a function and can be replaced by other values otherwise will return the default value.

--

--

Ignoramus

“If you torture the data long enough, it will confess to anything.”