Variables In Python
Variables are containers in which we can store information or data values such as words or numbers and also we can manipulate them.
Syntax
variable_name = value
In Python, we create a variable simply by giving it a name and assigning a value to it using the assignment operator (=).
Example
name = "Jason"
age = 25
Data Types
Python has many built-in data types, and variables can hold different types of data. Common data types include integers, floats, strings, booleans, lists, and dictionaries.
age = 25 # Integer
height = 5.9 # Float
name = "John" # String
is_adult = True # Boolean
print(age)
print(height)
print(name)
print(is_adult)
In the above example, we didn’t explicitly declare the data type of the variables. Instead, Python dynamically determines the data type based on the assigned values as python is dynamically typed language.
For instance, if you assign a variable a numerical value, Python automatically infers that the variable is of the integer data type.
Printing Variables
name = "Thanos"
age = 30
print(name)
print(age)
We can print the value of a variable using the print() function.
Reassigning Variables
count = 10
print(count) # Output: 10
count = count + 1
print(count) # Output: 11
We can change the value of a variable by reassigning it with another value.
Variable Concatenation
first_name = "Python"
last_name = "dex"
full_name = first_name + last_name
print(full_name) # Output: Pythondex
For variables type string we can concatenate or combine them using the + operator. If you run the above code the output will be Pythondex as both the first_name & last_name variables are now combined in full_name variable.
Variable Naming Rules
- Begin variable names with a letter (a-z, A-Z) or an underscore (_).
- Variable names should not begin with a number.
- Use letters, numbers, or underscores after the first character.
- Do not use Python keywords (reserved words) as variable names. For example, avoid names like
if
,else
,while
, etc. - Python is case-sensitive, so
myVar
andmyvar
would be considered different variables. - Do not use spaces or special characters (except underscores).
- Choose names that describe the variable’s purpose.
- For multi-word names, connect words with underscores (snake_case).
Example
# Good variable names
age = 25
user_age = 30
total_score = 95.5
is_logged_in = False
# Avoid these
2nd_try = "Invalid" # Starts with a number
special-char = "Invalid" # Contains special characters
if = 10 # Uses a keyword as a name
Variable Case Sensitive Example
name = "Jason"
Name = "Rohan"
print(name) # Output: Jason
print(Name) # Output: Rohan
The above example illustrates that python is case sensitive. This means that if you have a variable with the same name but differing in the case of at least one character, Python will consider them as 2 different variables.
So this is was the basic overview of variables in Python. By grasping these fundamentals, you’ve acquired the groundwork for handling data in python.