DEV Community

Haripriya V
Haripriya V

Posted on

TASK 2 – Constants and Variables

1.Create a variable named name and assign your name to it. Then print the value of the variable.

CODE:

name = "Haripriya"
print(name)

OUTPUT:

Haripriya

EXPLANATION:

  • A variable name is created and assigned the value "Harish"

  • print(name) displays the stored value

2.Create a variable age and assign your age to it. Later, reassign the variable with a new value and print the new value.

CODE:
`age = 20
print(age)

age = 21
print(age)`

OUTPUT:

20
21

EXPLANATION:

  • The variable age is first assigned 20

  • It is later updated to 21

  • Python allows variables to be reassigned

3.Assign the values 5, 10, and 15 to three variables a, b, and c in a single line. Print their values.

CODE:

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

OUTPUT:

5 10 15

EXPLANATION:

  • Multiple variables are assigned in one line

  • Values are assigned in order to a, b, and c

4.Swap the values of two variables x and y without using a third variable. Print their values before and after swapping.

CODE:

`x = 5
y = 10

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

x, y = y, x

print("After swap:", x, y)`

OUTPUT:

Before swap: 5 10
After swap: 10 5

EXPLANATION:

  • Values are swapped using x, y = y, x

  • No third variable is needed

5.Define constants PI with appropriate values and print them.

CODE:

PI = 3.14159
print(PI)

OUTPUT:

3.14159

EXPLANATION:

  • PI is written in uppercase to indicate a constant

  • Python treats it like a normal variable

6.Write a program that calculates the area of a circle using the constant PI and a variable radius. Print the area.

CODE:

`PI = 3.14159
radius = 5

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

OUTPUT:

Area of circle: 78.53975

EXPLANATION:

  • Formula: Area = π × r²

  • radius ** 2 means square of radius

7.Define constants for the length and width of a rectangle. Calculate and print the area.

CODE:

`LENGTH = 10
WIDTH = 5

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

OUTPUT:

Area of rectangle: 50

EXPLANATION:

  • Formula: Area = length × width

  • Constants are used for fixed values

8.Define a constant for π (pi) and a variable for the radius. Calculate and print the circumference of the circle.

CODE:

`PI = 3.14159
radius = 5

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

OUTPUT:

Circumference: 31.4159

EXPLANATION:

  • Formula: Circumference = 2 × π × r

  • The result is calculated and printed

Top comments (0)