Variables in Python¶
- Variables are fundamental components in Python and many other programming languages. They are used to store data that can be manipulated and processed in your programs.
- A variable in Python is a named storage location that can hold data. It's like a container where you can store different types of information, such as numbers, text, lists, or more complex data structures.
- Variables are allow you to manipulate and work with data in your programs.
- The type of data a variable can hold is determined by Python based on the value you assign to it. This means you can use variables to store integers, decimals, characters, and more, without specifying a type.
- Variables are created automatically when you assign a value to them. Python doesn't require you to declare the type of a variable; it figures it out on its own based on the assigned value.
Variable Declaration and Assignment¶
- In Python, you don't need to declare the data type of a variable explicitly. You can create a variable and assign a value to it in a single step.
In [ ]:
# Variable assignment
my_variable_1 = 42
print(my_variable_1)
42
Variable Types¶
Python has various variable types, including:
- int: Integer values (e.g., 42, -7).
- float: Floating-point values (e.g., 3.14, -0.5).
- str: Strings (e.g., "Hello, World!").
- bool: Boolean values (True or False).
- list: Ordered, mutable collections of values.
- tuple: Ordered, immutable collections of values.
- dict: Key-value mappings (dictionaries).
In [ ]:
my_integer = 42
my_float = 3.14
my_string = "Hello, World!"
my_bool = True
my_list = [1, 2, 3]
my_tuple = (4, 5, 6)
my_dict = {"name": "Alice", "age": 30}
Type Function : type() function give data type of variables¶
In [ ]:
print(type(my_integer))
print(type(my_float))
print(type(my_string))
print(type(my_bool))
print(type(my_tuple))
print(type(my_dict))
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'tuple'> <class 'dict'>
Casting : If you want to specify the data type of a variable, this can be done with casting.¶
In [ ]:
x = str(5) # x will be '3'
y = int(5) # y will be 3
z = float(5) # z will be 3.0
Quotes in string : String variables can be declared either by using single or double quotes.¶
In [ ]:
x = "intensity"
# is the same as
x = 'intensity'
Variable Naming Conventions¶
- A variable can have a short name (like x and y) or a more descriptive name (my_variable,num1).
Variable Naming Rules:
- A variable name must start with a letter or the underscore character.
- They cannot start with a number.
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Variable names are case-sensitive (name and NAME are different variables)
- A variable name cannot be any of the Python keywords.
In [ ]:
# Valid Name
myvariable = "intensity"
my_variable = "intensity"
_my_variable = "intensity"
myVariable = "intensity"
MYVARIABLE = "intensity"
myvariable2 = "intensity"
In [ ]:
# Invalid Name which show Error
2myvariable = "intensity"
my-variable = "intensity"
my variable = "intensity"
File "<ipython-input-31-c79e2d4c8407>", line 2 2myvariable = "intensity" ^ SyntaxError: invalid decimal literal
In [ ]:
# Variable names are case-sensitive
name = 4
NAME = "intensity"
#NAME will not overwrite name
Multi Words Variable Names
- Variable names with more than one word can be difficult to read so there are several techniques you can use to make them more readable.
In [ ]:
# Camel Case : Each word, except the first, starts with a capital letter
myVariable = "intensity"
# Pascal Case : Each word starts with a capital letter
MyVariable = "intensity"
# Snake Case : Each word is separated by an underscore character
my_variable = "intensity"
Multiple Assignment¶
- One Value to Multiple Variables: You can assign the same value to multiple variables in one line
In [ ]:
x = y = z = 1
- Many Values to Multiple Variables: You can assign multiple variables at once using unpacking. Make sure the number of variables matches the number of values, or else you will get an error.
In [ ]:
x, y, z = 1, 2, 3
- Variable Packing and Unpacking : Python supports variable packing and unpacking, which allows you to assign multiple values to or from a single variable.
In [ ]:
coordinates = (3, 4)
x, y = coordinates # Unpack the tuple into variables
Local and Global Variable¶
- Local variables are defined inside functions and are only accessible within that function's scope.
- Global variables are defined outside functions and can be accessed from anywhere in the code.
In [ ]:
global_var = 10
def my_function():
local_var = 5 # This is a local variable
print(global_var) # Access global variable
print(local_var) # Access local variable
my_function()
print(global_var) # Access global variable outside the function
# print(local_var) # This will raise an error since local_var is not accessible here.
10 5 10
- If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.
In [ ]:
x = "Good"
def myfunc():
x = "Best"
print("Python is " + x)
myfunc()
print("Python is " + x)
Python is Best Python is Good
Keyword global:¶
If you need to create a global variable, but are stuck in the local scope, you can use the global keyword. The global keyword makes the variable global.
Also, use the global keyword if you want to make a change to a global variable inside a function.
In [ ]:
def my_func():
global x
x = 142
my_func()
print(x)
142
In [ ]:
x = 142
def my_func():
global x
x = 211
my_func()
print(x)
211
Print the Variables¶
In [ ]:
x = "How are you ?"
print(x)
How are you ?
In [ ]:
# You can put multiple variables, separated by a comma in print()
x = 1
y = 2
z = 3
print(x, y, z)
1 2 3
In [ ]:
# You can use + operator to print multiple variables in print()
x = "1 "
y = "2 "
z = "3 "
print(x + y + z)
1 2 3
In [ ]:
# For numbers the + character works as a mathematical operator
x = 3
y = 1
print(x + y)
4
In [ ]:
# If you combine a string and a number with the + operator, Python will give you an error
x = 5
y = "intensity"
print(x + y)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-29-ad057ec50799> in <cell line: 4>() 2 x = 5 3 y = "intensity" ----> 4 print(x + y) TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [ ]:
# The best way to print multiple variables in the print() function is to separate them with commas, which even support different data types
x = 5
y = "intensity"
print(x, y)
5 intensity
Deleting Variables¶
You can delete a variable using the del keyword.
You can delete a single object or multiple objects by using the del statement.
del var del var_a, var_b
In [ ]:
x = 10
del x
# Now x is undefined and trying to access it will raise an error.