Day5-Facilitation Guide(Functions)
Day5-Facilitation Guide(Functions)
(Functions)
Index
I. Recap
II. Functions
III. Built-in Functions
IV. Type Conversion Functions
V. Mathematical Functions
VI. User defined functions
I. Recap
In our last session we learned:
● Conditional constructs:Conditional constructs, also known as conditional
statements or control structures, are fundamental programming elements that
allow you to make decisions in your code based on specific conditions.
● if Statement:The if statement is used to execute a block of code if a specified
condition is true.
● Ladder if else: A "ladder" of if-else statements, also known as an "if-else if-else"
ladder, is a series of if, elif (short for "else if"), and else statements used to
evaluate multiple conditions in a hierarchical manner. Each condition is checked
one by one, and the first one that evaluates to true triggers the associated code
block to execute. If none of the conditions are true, the else block (if present) is
executed.
● Nested conditions:Nested conditions, also known as nested if statements,
occur when you place one or more if, elif, or else statements inside another if,
elif, or else block. This allows you to create more complex decision-making logic
by evaluating conditions within conditions
II. Functions
In Python, a function is a reusable block of code that performs a specific task or set of
tasks. Functions allow you to encapsulate logic, make your code more organized and
modular, and avoid redundancy by enabling you to call the same code multiple times
with different inputs.
def function_name(parameters):
# Function body (code that performs a task)
# ...
return result # Optional: Returns a value
function_name: Choose a descriptive name for your function to indicate its purpose.
Function names should follow Python naming conventions (e.g., use lowercase with
underscores for multi-word names).
parameters (also called arguments): These are optional inputs that you can pass to
the function. A function can have zero or more parameters.
: (colon): It marks the beginning of the function's body.
Function body: This is where you write the code that defines the functionality of the
function.
return (optional): This keyword is used to specify the value that the function should
return when it's called. If a function doesn't have a return statement, it implicitly returns
None.
Functions can also have default values for parameters, allowing you to call the function
without providing all the arguments:
greet_default = greet("Alice")
greet_custom = greet("Bob", "Hi")
Functions can be called within other functions, and you can create complex programs
by organizing your code into smaller, reusable functions.
Python provides built-in functions like print(), len(), and many others, and you can also
create your own custom functions to extend Python's functionality and make your code
more readable and maintainable.
def function_name(parameters):
""" Docstring (optional): Description of the function. """
# Function body: Statements to perform the task
result = ...
return result # Return statement (optional)
Python provides a wide range of built-in functions that are readily available for use
without the need to define them. These functions cover a variety of tasks, from
mathematical operations to working with data structures, input/output operations, and
more. Here are some commonly used built-in functions in Python:
3. Mathematical Functions:
- `abs()`: Returns the absolute value of a number.
- `max()`: Returns the maximum value in an iterable.
- `min()`: Returns the minimum value in an iterable.
- `pow()`: Raises a number to a specified power.
- `round()`: Rounds a floating-point number to the nearest integer.
Example:
max(4, 7, 2)
returns 7
4. String Functions:
- `len()`: Returns the length of a string.
- `str.upper()`: Converts a string to uppercase.
- `str.lower()`: Converts a string to lowercase.
- `str.split()`: Splits a string into a list of substrings.
- Example:
len("Hello")
returns 5
6. Input Functions:
- `input()`: Reads a line of text entered by the user from the console.
Example:
name = input("Enter your name: ")
8. List Functions:
- `append()`: Adds an element to the end of a list.
- `extend()`: Adds elements from an iterable to a list.
- `pop()`: Removes and returns an element from a list.
- `sort()`: Sorts the elements of a list.
Example:
my_list.append(42)
9. Dictionary Functions:
- `keys()`: Returns a list of keys in a dictionary.
- `values()`: Returns a list of values in a dictionary.
- `items()`: Returns a list of key-value pairs in a dictionary.
Example:
my_dict.keys()
Note :You will learn the above mention functions uses in your upcoming session
These are just a few examples of Python's built-in functions. Python has a rich standard
library with many more functions for various tasks. You can explore and use these
functions as needed to simplify and optimize your code.
Type conversion functions, also known as casting or conversion functions, are used in
programming to change the data type of a value or variable from one type to another.
These functions help you ensure that data is in the correct format for various operations.
The specific functions and syntax may vary depending on the programming language
you are using, but the concept remains consistent.
Here are common type conversion functions and their general descriptions:
Integer Conversion (int()): Converts a value or variable to an integer data type. If the
value cannot be converted to an integer (e.g., a non-numeric string), it may raise an
error.
Example :
x = int("123")
Example:
y = float("3.14")
String Conversion (str()): Converts a value or variable to a string data type. This is
commonly used to concatenate non-string values into strings for display or storage.
Example:
z = str(42)
Example:
It's important to use type conversion functions carefully to avoid unexpected errors or
loss of data precision. Always ensure that the conversion is meaningful and safe for
your specific use case.
V. Mathematical Functions
Python provides a rich set of mathematical functions and operations through the built-in
math module. You need to import the math module to access these functions. Here are
some commonly used mathematical functions and operations available in Python's math
module:
Trigonometric Functions:
Rounding Functions:
Constants:
x = 16
y = 2.5
# Trigonometric functions
sin_x = math.sin(math.pi / 6)
cos_x = math.cos(math.pi / 3)
tan_x = math.tan(math.pi / 4)
# Rounding functions
ceil_result = math.ceil(y)
floor_result = math.floor(y)
Remember to import the math module before using these functions. You can explore
more mathematical functions and constants provided by the math module in Python's
official documentation.
Exercise chatGPT
Help me develop a simple python program. I want to calculate the total electricity bill.
The rules are as follows: Installed load: The installed load is the maximum amount of
electricity that your home or business can use at any given time. This is measured in
kilowatts (kW). The higher your installed load, the higher your fixed charges will
be.Energy consumption: The energy consumption is the total amount of electricity that
you use in a billing period. This is measured in units (kWh). The more electricity you
consume, the higher your variable charges will be.Tariff slabs: The tariff slabs are the
different rates per unit of electricity that you are charged. There are currently 4 tariff
slabs in Bangalore:
Up to 50 units: Rs 4.75/unit
51 to 100 units: Rs 5.75/unit
101 to 200 units: Rs 7/unit
Above 200 units: Rs 8/unit
The actual electricity charges that you pay will depend on your installed load, energy
consumption, and the tariff slab that you fall into.
After the ILT, the student has to do a 30 min live lab. Please refer to the Day 5 Lab
doc in the LMS.