Python Variables
Python Variables
Variables are used to store values in a program. In Python, variables are created by assigning a value to a name. For example, the following code creates a variable named'x'
and assigns it the value of 5:
x = 5
my_num = 42 # stores an integer
my_float = 3.14 # stores a floating-point number
my_string = "Hello, world!" # stores a string
my_bool = True # stores a boolean value (True or False)
x = 5
x = 7 # re-assigns x to a new value of 7
Naming Conventions for Python Variables
Variable names must follow certain rules in Python. They must start with a letter or underscore, and can only contain letters, numbers, and underscores.In Python, variable names must follow the following rules:
- Variable names must start with a letter or underscore character.
- Variable names can only contain letters, numbers, and underscores.
- Variable names are case-sensitive, meaning that
my_var
andMy_Var
are two different variables. - Variable names should not use reserved words or built-in functions as their names.
my_var
myVar
_my_var
MYVAR
my_var_2
2my_var # starts with a number
my-var # contains a dash
my var # contains a space
my var! # contains a special character
import # uses a reserved word
Python Type Casting
Explicit Type Casting
Explicit type casting in Python is when you manually convert a variable from one data type to another. You can do this using the built-in functionsint()
, float()
, str()
, and bool()
.
# Integer to Float
a = 5
b = float(a)
print(b) # Output: 5.0
# Float to Integer
c = 3.5
d = int(c)
print(d) # Output: 3
# Integer to String
e = 10
f = str(e)
print(f) # Output: '10'
# String to Integer
g = '20'
h = int(g)
print(h) # Output: 20
# String to Float
i = '3.14'
j = float(i)
print(j) # Output: 3.14
# Boolean to Integer
k = True
l = int(k)
print(l) # Output: 1
# Integer to Boolean
m = 0
n = bool(m)
print(n) # Output: False