Python VariablesVariables 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:
Variables can store various types of data, such as numbers, strings, and boolean values. Here are some examples:
x = 5
Variables can be assigned new values at any time, simply by assigning a new value to the variable name. For example:
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 are essential for many programming tasks, and understanding how to use them is an important part of learning Python.
x = 5 x = 7 # re-assigns x to a new value of 7
Naming Conventions for Python VariablesVariable 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_Varare two different variables.
- Variable names should not use reserved words or built-in functions as their names.
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 CastingExplicit 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
# 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