Day 11: Functions in Python

Functions are reusable blocks of code. We do that by defining a function block and invoke it in later stages of the code.

Defining a function

Default function (without params)

def greet_user(): # Define code block
    print ("Greetings user!")

greet_user(); # Invoke

# Greetings user!

Defining function with parameters

def greet_user(name):
    print ("**" * 20)
    print (f"Greetings {name}!")
    print ("**" * 20)

greet_user("Darth Vader");

****************************************
Greetings Darth Vader!
****************************************

Default params

def greet_user(name = "Luke"):
    print ("**" * 20)
    print (f"Greetings {name}!")
    print ("**" * 20)

greet_user();

****************************************
Greetings Luke!
****************************************

Multiple params

def create_greeting( greet_text, user_name ):
    print ("**" * 20)
    print (f"{greet_text} {user_name}!")
    print ("**" * 20)

create_greeting( "Namaste", "Soumil" )

****************************************
Namaste Soumil!
****************************************

Return values

def exp(a, b):
    return a ** b;

num = exp(5, 3)
print (num) # 125

Note: A function that doesn’t have a return statement, returns None

Scope

name = "this var in global"

print ("Global scope variable:", name)

def my_func():
   print ("1. Local scope variable:", name)
 
my_func();

def my_func2():
   name = "this var in func2"
   print ("2. Local scope variable:", name)
   def my_func3():
      name = "this var in func3"
      print ("2.1 Local scope variable:", name)
   my_func3()
 
my_func2()
   print ("Global scope variable:", name)

# variables are not scoped inside loops or conditional statements
# this is not like javaScript where variables are block scoped

for char in "soumil":
   last_name = "roy"
   print (char)
 
if True:
   message = "I'm in if block"
  
print ("Global scope variable:", last_name) # roy
print ("Global scope variable:", char) # l
print ("Global scope variable:", message) # I'm in if block
What’s your Reaction?
+1
0
+1
0
+1
0

Published by Soumil Roy

I'm a Full-Stack Developer with 7+ years of experience in Web design & development .Currently building expertise in React, TypeScript & GraphQL

Leave a comment

Your email address will not be published.

Open WhatApp
Hello 👋 Click the button below connect with me.