Python_Concepts_8_Marks
Python_Concepts_8_Marks
greet('Alice', 25)
greet('Bob')
4. **Variable-length Arguments**:
- *args: Multiple positional args
- **kwargs: Multiple keyword args
def show(*args):
for i in args:
print(i)
Types:
1. **Built-in Namespace**: Includes built-in functions and exceptions.
Example: print(), len(), Exception
Example:
try:
x = int(input('Enter number: '))
result = 10 / x
print(result)
except ZeroDivisionError:
print('Division by zero error')
except ValueError:
print('Invalid input')
finally:
print('Execution completed')
try block contains risky code, except handles errors, finally executes cleanup code.
Syntax:
try:
# risky code
except ExceptionType:
# handling code
Example:
try:
a = 10 / 0
except ZeroDivisionError:
print('Cannot divide by zero')
print('Program continues...')
Multiple except blocks can handle different exceptions. You can also catch all exceptions using except Exception.
Example:
class NegativeValueError(Exception):
pass
def set_age(age):
if age < 0:
raise NegativeValueError('Age cannot be negative')
print('Age set to', age)
try:
set_age(-5)
except NegativeValueError as e:
print('Error:', e)
Global Variable:
- Declared outside all functions.
- Accessible across all functions.
Example:
x = 10 # global
def func():
y = 5 # local
print('Local y:', y)
print('Global x:', x)
Example:
import math
print(math.sqrt(16))
print(math.ceil(4.2))
Example:
class AgeTooSmallError(Exception):
pass
def check_age(age):
if age < 18:
raise AgeTooSmallError('Age must be 18 or above')
print('Access granted')
try:
check_age(16)
except AgeTooSmallError as e:
print('Exception:', e)