๐ Python Variables – A Beginner's Guide
๐น What Is a Variable?
A variable in Python is like a container that holds data. Think of it as a label you stick on a box, so you know what’s inside.
๐ง Why Use Variables?
Variables help you:
-
Store information
-
Reuse it later
-
Change it easily
๐ Creating a Variable
To create a variable in Python, just write a name, an equal sign =
, and a value.
name = "Alice"
age = 25
height = 5.6
Here:
-
name
is a variable storing a string -
age
is storing an integer -
height
is storing a floating-point number
๐ Variable Naming Rules
✅ You can:
-
Use letters, numbers, and underscores (
_
) -
Start with a letter or underscore
❌ You can’t:
-
Start with a number
-
Use spaces or symbols like
@
or!
✅ Valid:
first_name = "John"
user2 = "Jane"
_temp = 50
❌ Invalid:
2user = "Error"
user-name = "Oops"
๐ Changing a Variable's Value
You can update a variable at any time:
score = 10
score = 20 # Now score is 20
๐งช Python Is Dynamically Typed
You don’t have to tell Python the type of variable. It figures it out on its own:
x = 10 # int
x = "ten" # now it's a string
This is called dynamic typing.
๐งฎ Example with Numbers
a = 5
b = 3
sum = a + b
print("Sum is:", sum) # Output: Sum is: 8
๐ฃ Example with Strings
first = "Python"
second = "Rocks"
message = first + " " + second
print(message) # Output: Python Rocks
๐งน Best Practices
-
Use descriptive names:
x = 10 # Bad user_age = 10 # Good
-
Stick to lowercase_with_underscores for readability
๐ Quick Recap
Feature | Example |
---|---|
Create variable | name = "Alice" |
Update value | name = "Bob" |
Use in math | total = a + b |
Combine text | msg = first + last |
✅ Try It Yourself
Copy and paste this code into a Python editor:
name = "Charlie"
age = 30
print(name, "is", age, "years old.")
You’ll see: Charlie is 30 years old.
watch following video if you like to understand in video format.
In this video you can see :
What is a variable ?
Why to use variables?
What are python variables and how they are used?
How python deals with variables and how these are declared?
No comments:
Post a Comment