Variable Exercises
These exercises are designed to strengthen your understanding of Python variables.
They focus on variable creation, assignment, reassignment, type handling, and real-world usage.
Exercise 1: Create and Print Variables
Create variables to store your name, age, and city, then print them.
python
name = "Jayesh"
age = 25
city = "Pune"
print(name)
print(age)
print(city)
Exercise 2: Assign Multiple Values
Assign values to three variables in one line and print them.
python
a, b, c = 10, 20, 30
print(a, b, c)
Exercise 3: One Value to Multiple Variables
Assign the same value to three variables and print them.
python
x = y = z = 100
print(x, y, z)
Exercise 4: Change Variable Type
Assign an integer to a variable, then change it to a string and print both.
python
value = 10
print(value)
value = "Ten"
print(value)
Exercise 5: Get the Type of Variables
Use the
type() function to check the data type of variables.python
x = 10
y = 10.5
z = "Python"
print(type(x))
print(type(y))
print(type(z))
Exercise 6: Use Casting
Convert a float into an integer and print the result.
python
num = 9.8
result = int(num)
print(result)
Exercise 7: Case-Sensitive Variables
Create two variables with the same name but different cases and print them.
python
value = 50
Value = 100
print(value)
print(Value)
Exercise 8: Valid vs Invalid Variable Names
Identify which variable names are valid.
python
user_name = "Admin"
_user = "Python"
user1 = "Code"
# Invalid:
# 1user = "Error"
# user-name = "Error"
Exercise 9: Swap Two Variables
Swap values of two variables without using a temporary variable.
python
a = 5
b = 10
a, b = b, a
print(a, b)
Exercise 10: Global and Local Variable
Create a global variable and access it inside a function.
python
x = 20
def show():
print(x)
show()
Exercise 11: Modify Global Variable
Use the
global keyword to change a global variable inside a function.python
count = 0
def increase():
global count
count += 1
increase()
print(count)
Exercise 12: Variable Naming Practice
Create variables using:
- Snake case
- Camel case
- Pascal case
python
user_name = "Python"
userName = "Python"
UserName = "Python"
Exercise 13: Store and Calculate
Store two numbers in variables and print their sum, difference, and product.
python
x = 15
y = 5
print(x + y)
print(x - y)
print(x * y)
Exercise 14: Constant Variable
Create a constant variable and use it in a calculation.
python
PI = 3.14
radius = 5
area = PI * radius * radius
print(area)
Exercise 15: Variable Reassignment
Reassign a variable multiple times and print its final value.
python
data = 10
data = 20
data = 30
print(data)