Python local example

Gary 102 Published: 06/23/2024

Python local example

Here is a Python example that demonstrates a simple calculator program:

def add(x, y):

return x + y

def subtract(x, y):

return x - y

def multiply(x, y):

return x * y

def divide(x, y):

if y == 0:

return "Error: Division by zero is not allowed"

else:

return x / y

print("Select operation:")

print("1.Add")

print("2.Subtract")

print("3.Multiply")

print("4.Divide")

while True:

choice = input("Enter your choice (1/2/3/4): ")

if choice in ('1', '2', '3', '4'):

num1 = float(input("Enter first number: "))

num2 = float(input("Enter second number: "))

if choice == '1':

print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':

print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':

print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':

print(num1, "/", num2, "=", divide(num1, num2))

else:

print("Invalid input")

This program is a simple calculator that allows users to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. It repeatedly prompts the user for input until they choose to quit.

In this code:

The add, subtract, multiply, and divide functions are defined to perform each operation. A while loop is used to continuously prompt the user for input and execute the chosen operation. If the user enters an invalid choice, it will print "Invalid input". When performing a division operation, the program checks if the second number (denominator) is zero and returns an error message accordingly.

This code can be run in any Python environment.

What is the difference between local and global variables in Python

I'd be happy to explain!

In Python, a variable can be either local or global, which affects its scope and accessibility.

Local Variables

A local variable is created within a function or block of code. It has a limited scope and exists only within the context of that function or block. When the function or block finishes executing, the local variables are automatically garbage collected.

Here's an example:

def my_function():

x = 5 # local variable

print(x) # prints 5

my_function()

print(x) # raises NameError: name 'x' is not defined

As you can see, the local variable x is only accessible within the scope of the my_function() function. Outside that scope, it's no longer recognized.

Global Variables

A global variable is declared outside any function or block. It has a broader scope and exists throughout the entire program.

Here's an example:

x = 5  # global variable

def my_function():

print(x) # prints 5

my_function()

print(x) # still prints 5

Notice how the global variable x is accessible within the my_function() function as well as outside it.

Key differences:

Scope: Local variables are limited to the scope of a function or block, while global variables have a broader scope and exist throughout the program. Accessibility: Local variables can only be accessed within their defining scope, whereas global variables can be accessed from anywhere in the program. Lifetime: Local variables are automatically garbage collected when they go out of scope, whereas global variables persist until the program terminates.

Best practices:

Use local variables whenever possible to avoid polluting the global namespace. Declare global variables only when necessary and keep their usage minimal to maintain code readability and maintainability. Be mindful of variable naming conventions (e.g., using _ as a prefix for private variables) to distinguish between global and local variables.

In summary, understanding the difference between local and global variables in Python is crucial for writing efficient, readable, and maintainable code. By choosing the right scope for your variables, you can avoid confusing errors and keep your program organized!