Python Variable

In this tutorial, you will learn about Python variables.

What is a Python Variable?

Python variable is used to store data, and you can manipulate them according to your requirements.

A Python variable refers to a value or object in memory.

In Python, you can assign values to variables without explicitly declaring their data types because Python is dynamically typed.

When you run an assignment statement such as a = 2 in Python, it works even if you’ve never told Python to use the name a as a variable or that a should stand for an integer-type object.

Variable Assignment

In Python, you can create a variable by simply assigning a value to it using the = operator.

Example:


x = 20          # Assigns integer 20 to variable x
name = "John"  # Assigns string "John" to variable name
pi = 3.14       # Assigns floating-point number 3.14 to variable pi

What are the rules to declare Naming Variables

1. Variable names must start with a letter (a-z, A-Z) or an underscore _.

2. They can contain letters, digits (0-9), and underscores.

3. Variable names are case-sensitive (name, Name, and NAME are different variables).

4. Python reserved keywords (such as if, while, for, etc.) cannot be used as variable names.

Example:


age = 38 # Integer variable
height = 6.2  # Float variable
is_employee = True  # Boolean variable
greeting = "Hello, Friends!"  # String variable

Reassigning Variables

Variables can be reassigned to new values at any time. Since Python is dynamically typed, the type of a variable can also change when reassigned.


x = 10      # x is an integer
x = "Hello!"  # Now x is a string

Variables are essential for storing and manipulating data in Python programs.

Python Variable – Questions and Answers

Q 1: What is a variable in Python?

Ans: A variable is a name used to store data values in Python.

Q 2: Do we need to declare variable types in Python?

Ans: No, Python automatically assigns the data type at runtime.

Q 3: How do you assign a value to a variable?

Ans: By using the assignment operator =.

Q 4: Can a variable name start with a number?

Ans: No, Python variable names cannot start with a number.

Q 5: Are Python variables case-sensitive?

Ans: Yes, age and Age are treated as different variables.

Python Variable – Objective Questions (MCQs)

Q1. Which of the following is the correct way to create a variable in Python?






Q2. What will be the output of the following code?

x = 10
y = "10"
print(x + int(y))






Q3. Which of the following variable names is invalid in Python?






Q4. What is the data type of the variable x in the code below? x = 3.5






Q5. Which statement is true about Python variables?






Related Python Variable Topics