python 3
python 3
Calling a Function
To call a function, use its name followed by parentheses (). If the function
expects arguments, they are passed within the parentheses.
Example
greet("Alice") # Output: Hello, Alice!
greet("Bob") # Output: Hello, Bob!
result = add(5, 3)
print(result) # Output: 8
Function Arguments
Functions can accept arguments, which are values passed to the function
when it is called. Arguments can be positional or keyword-based.
Example
def describe_person(name, age, city="Unknown"):
"""This function describes a person."""
print(f"Name: {name}, Age: {age}, City: {city}")
Here, the sum variable is created inside the function, so it can only be
accessed within it (local scope). This type of variable is called a local
variable.
Based on the scope, we can classify Python variables into three types:
1. Local Variables
2. Global Variables
3. Nonlocal Variables
# local variable
message = 'Hello'
print('Local', message)
greet()
Here, the message variable is local to the greet() function, so it can only
be accessed within the function.
That's why we get an error when we try to access it outside
the greet() function.
To fix this issue, we can make the variable named message global.
def greet():
# declare local variable
print('Local', message)
greet()
print('Global', message)
Run Code
Output
Local Hello
Global Hello
Now, message will be accessible from any scope (region) of the program.
# nested function
def inner():
message = 'nonlocal'
print("inner:", message)
inner()
print("outer:", message)
outer()
Run Code
Output
inner: nonlocal
outer: nonlocal
Here,
argument(s) - any value passed to the lambda function
expression - expression is executed and returned
Let's see an example,
greet = lambda : print('Hello World')
The lambda function above simply prints the text 'Hello World'.
result = a + b
return result
import example
This does not import the names of the functions defined in example directly
in the current symbol table. It only imports the module
name example there.
Using the module name we can access the function using the
dot . operator. For example:
example.add(4,5) # returns 9
Output
Random Number: 9
Explanation:
import random brings in Python’s built-in random module.
random.randint(1, 10) generates a random integer between 1 and 10.
Types of Errors
Output:
Analysis
Expected Output: The average of the numbers [10, 20, 30, 40,
50] should be 30.
Actual Output: The program will output The average is: 29.0.
Runtime Errors:
A runtime error in a program is an error that occurs while the program
is running after being successfully compiled.
Runtime errors are commonly called referred to as “bugs” and are often
found during the debugging process before the software is released.
When runtime errors occur after a program has been distributed to the
public, developers often release patches, or small updates designed to
fix the errors.
Anyone can find the list of issues that they might face if they are a
beginner
While solving problems on online platforms, many run time errors can
be faced, which are not clearly specified in the message that comes
with them. There are a variety of runtime errors that occur such
as logical errors, Input/Output errors, undefined object
errors, division by zero errors, and many more.
except ZeroDivisionError:
print("Can't be divided by zero!")
Output
Can't be divided by zero!
Explanation: In this example, dividing number by 0 raises
a ZeroDivisionError. The try block contains the code that might cause an
exception and the except block handles the exception, printing an error
message instead of stopping the program.
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Enter a valid number!")
else:
print("Result is", res)
finally:
print("Execution complete.")
Output
You can't divide by zero!
Execution complete.
Explanation:
try block asks for user input and tries to divide 100 by the input
number.
except blocks handle ZeroDivisionError and ValueError.
else block runs if no exception occurs, displaying the result.
finally block runs regardless of the outcome, indicating the completion
of execution.