python-practicals (5)
python-practicals (5)
def inner_function():
# Local variable in inner function
inner_var = "I'm in inner function"
print("Inside inner_function:")
print(f"Inner variable: {inner_var}")
print(f"Can access outer variable: {outer_var}")
print("Inside outer_function:")
print(f"Outer variable: {outer_var}")
inner_function()
try:
print(inner_var) # This will raise an error
except NameError as e:
print(f"Cannot access inner_var from outer function: {e}")
demonstrate_local_variables()
Output:
Demonstrating local variables:
Inside outer_function:
Outer variable: I'm in outer function
Inside inner_function:
1
Inner variable: I'm in inner function
Can access outer variable: I'm in outer function
Cannot access inner_var from outer function: name 'inner_var' is not defined
def modify_global_correct():
global global_counter
global_counter += 1
print(f"Global counter inside function: {global_counter}")
def modify_global_incorrect():
try:
global_counter += 1 # This will raise an error
except UnboundLocalError as e:
print(f"Error without global keyword: {e}")
class CounterClass:
class_counter = 0 # Class variable (similar to global)
def increment(self):
CounterClass.class_counter += 1
return CounterClass.class_counter
2
print(f"Counter1 increment: {counter1.increment()}")
print(f"Counter2 increment: {counter2.increment()}")
print(f"Class counter value: {CounterClass.class_counter}")
demonstrate_global_variables()
Output:
Initial global counter: 0
Global counter inside function: 1
Global counter after modification: 1
@staticmethod
def get_company_info():
return f"Company: {Employee.company_name}, Employees: {Employee.employee_count}"
@classmethod
def change_company_name(cls, new_name):
cls.company_name = new_name
3
# Create employees
emp1 = Employee("Alice")
emp2 = Employee("Bob")
print("\nAfter creating employees:")
print(Employee.get_company_info())
demonstrate_static_variables()
Output:
Initial company info:
Company: TechCorp, Employees: 0
Instance variables:
Employee 1 department: IT
Employee 2 department: Not found - 'Employee' object has no attribute 'department'
Would you like me to continue with the next set of practicals? We can cover
4
method overloading, classes, modules, and file operations next.