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
Variables can store various types of data, such as numbers, strings, and boolean values. Here are some examples:
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)
Variables can be assigned new values at any time, simply by assigning a new value to the variable name. For example:
                    
                        x = 5
                        x = 7  # re-assigns x to a new value of 7
                        
Variables are essential for many programming tasks, and understanding how to use them is an important part of learning Python.
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:
  1. Variable names must start with a letter or underscore character.
  2. Variable names can only contain letters, numbers, and underscores.
  3. Variable names are case-sensitive, meaning that my_var and My_Var are two different variables.
  4. Variable names should not use reserved words or built-in functions as their names.
Here are some examples of valid variable names in Python:
my_var
myVar
_my_var
MYVAR
my_var_2
And here are some examples of invalid variable names in Python:
                            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 functions int(), 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
Explicit Type Casting