TASK-2 CONSTANTS AND VARIABLES IN PYTHON

Constants and Variables in Python 

Introduction

In Python, variables are used to store data that can change during program execution, while constants represent fixed values that should not be modified. Even though Python does not strictly enforce constants, we follow naming conventions to represent them. In this task, different operations using variables and constants are explored along with the reasoning behind each approach.

1. Creating and printing a variable

name = "Neha"
print(name)

Approach: Assigning value to a variable and printing it
Why: Variables allow us to store and reuse data instead of hardcoding values multiple times.

2. Reassigning a variable

age = 18
print(age)

age = 20
print(age)

Approach: Updating variable value
Why: Variables are dynamic in Python, meaning their values can be changed anytime during execution. This makes programs flexible.

3. Assigning multiple variables in a single line

a, b, c = 5, 10, 15
print(a, b, c)

Approach: Multiple assignment
Why chosen: This is a concise way to assign multiple values at once instead of writing separate lines. It improves readability and reduces code length.

4. Swapping two variables without a third variable

x = 5
y = 10

print("Before swapping:", x, y)

x, y = y, x

print("After swapping:", x, y)

Approach: Tuple unpacking
Why chosen: Python allows direct swapping without a temporary variable, making the code shorter and cleaner.
Alternative: Using a third variable, but this approach is more efficient.

5. Defining constants

PI = 3.14159
print(PI)

Approach: Using uppercase variable name
Why: Python does not have true constants, so uppercase naming is used as a convention to indicate that the value should not be changed.

6. Area of a circle

PI = 3.14159
radius = 5

area = PI * radius * radius
print("Area of circle:", area)

Approach: Formula-based calculation
Why: Using variables and constants makes the formula reusable. Only the radius needs to be changed for different results.

7. Area of a rectangle

LENGTH = 10
WIDTH = 5

area = LENGTH * WIDTH
print("Area of rectangle:", area)

Approach: Using constants
Why: Since length and width are fixed in this case, treating them as constants improves clarity.

8. Circumference of a circle

PI = 3.14159
radius = 5

circumference = 2 * PI * radius
print("Circumference of circle:", circumference)

Approach: Mathematical formula
Why: Separating constants and variables makes the program easier to understand and modify.

Conclusion

This task demonstrates how variables and constants are used in Python to store and manipulate data. Variables provide flexibility by allowing value changes, while constants help maintain fixed values. Using proper approaches like multiple assignment and tuple unpacking makes the code more efficient and readable.

Comments

Popular posts from this blog

THE DELIVERY MAN

EC2 LAUNCHING

SORT A LINKED LIST USING MERGE SORT