Introduction of
Python
ECE 181
Functions
Dr. Jhulan Kumar
Python Functions
• These are the block of statements that does a specific
task.
• Instead of repeating task again and again , we make a
function we call the function to reuse code contained in
it over and over again.
Syntax to declare a function
•def: Starts the function definition.
•function_name: Name of the function.
•parameters: Inputs passed to the function
(inside ()), optional.
•Indented code: The function body that runs
when called.
def diwali():
print("wish you a very happy Diwali")
Calling a Function
• After creating a function in Python we can call it by
using the name of the functions followed by parenthesis
containing parameters of that particular function.
Function Arguments
• Arguments are the values passed inside the parenthesis
of the function.
• A function can have any number of arguments
separated by a comma.
Example
WAP to check whether the number passed as an
argument to the function is even or odd.
Example
Example
Write a function that accepts two numbers and returns the larger one.
Example
Create a function calculator(a, b, operation) that performs addition,
subtraction, multiplication, or division based on the operation passed.
Reverse a String
string[start:end:step]
Start: index to begin (default = start of string)
End: index to stop (default = end of string
Step: how much to move (positive = forward, negative = backward)
Reverse the string
text = “Lovely"
print(text[::1])
print(text[::-1])
Write a function that checks
whether a given string is a
palindrome
Problem
Write a function that calculates Simple Interest (SI) given Principal (P),
Rate of Interest (R), and Time (T).
Practice Problems
• Write a function that takes radius as input and returns both area and
circumference of a circle.
• Write a function that takes a number and returns the largest digit in it.
• Write a function that prints the multiplication table of a given number
up to 10.
• Write a function that takes a string and counts how many vowels it
has.
• Write a function that finds the sum of digits of a number.
• Write a function to check if a number is an Armstrong number.
(Example: 153 → 1³+5³+3³ = 153 → Armstrong)