- Home
- /
- Python Variables
Python Tutorial
Introduction
Python Data Types & Oper...
Python Strings
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Conditional Statements
Python Loops
Python Functions
Python Modules
Python OOPS
Advanced Topics
File Handling
- Home
- /
- Python Variables
Python Variables
In Python, a variable acts like a label you stick on a box to identify what’s inside. This label holds a value, and you can change or use that value any time in your program.
The best part? Python doesn’t ask you to declare the data type when creating a variable. You just assign the value, and Python figures it out for you.
Examples
student_name = "Hamza" # String
student_age = 17 # Integer
is_enrolled = True # Boolean
Python knows student_name
is a string just by seeing the quotes. No need to write string student_name
.
Variable Naming Rules
When naming variables, follow these guidelines:
Names can have letters, digits, and underscores.
They must start with a letter or underscore — never a digit.
Python is case-sensitive, so
Marks
andmarks
are different.Avoid special characters like
$
,@
, or%
.
Valid vs. Invalid Examples
roll_no = 101 # valid
RollNo = 102 # valid (different from roll_no)
_student = "Ali" # valid
5students = "Error" # ❌ invalid: starts with a digit
@grade = "A+" # ❌ invalid: uses special character
Variable Name Styles
For readability, you can write multi-word variable names in one of the following styles:
PascalCase:
UserScore
camelCase:
userScore
snake_case:
user_score
← most common in Python
Scope of Variables
The scope tells where a variable exists and can be used. Python has two main types of scope:
Local Variables
Local variables are defined inside a function and can’t be used outside of it.
def login_message():
user = "Arshyan"
print("Welcome, " + user)
login_message()
# print(user) ❌ This will cause an error — user is local
Global Variables
Global variables are declared outside any function, and you can use them anywhere in your code.
app_name = "Learn With Arshyan"
def display_app():
print("You're using: " + app_name)
display_app()
print("App name is still: " + app_name)
Mixed Scope Example
course = "Python Programming" # global
def about_course():
instructor = "Mr. Arshyan" # local
print("Course:", course)
print("Instructor:", instructor)
about_course()
# print(instructor) ❌ Error - only accessible inside function
Final Thoughts
Variables in Python are flexible and don’t need data types declared.
Follow naming rules to avoid errors.
Understand variable scope to manage data efficiently in your program.
Stay consistent, practice writing meaningful variable names, and explore how variable scope affects your code’s behavior.