Variable Declaration:
In Python, the type of a variable is automatically inferred based on its assigned value, eliminating the need for explicit declaration.
Example:
x = 5 # Integer
name = "John" # String
price = 19.99 # Float
is_active = True # Boolean
Variable Naming Rules:
- Variable names must begin with a letter or underscore (_).
- Subsequent characters may be letters, numbers, or underscores.
- Variable names are case-sensitive (for example, name and Name are not the same variable).
- Python keywords (such as if, while, and for) are not allowed.
Common Variable Types:
Integer: Whole numbers, positive or negative.
x = 10
y = -5
Float: Numbers with a decimal point.
pi = 3.14159
temperature = -5.2
String: A set of characters. It should be enclosed within double quotes
greeting = "Hello, world!"
Boolean: Represents True or
False
.is_valid = True
has_error = False
None: This is similar to "null" in other languages
result = None
Multiple Assignments:
Likewise, in other programming languages, in python we can also be able to assign multiple values in a single line.
a, b, c = 1, 2, "apple"
Type Checking:
You can check the type of a variable using the type() function.
x = 5
print(type(x)) # Output: <class 'int'>
Type Casting:
You can convert between types using type casting functions like int(), float(), str() etc.
x = "123"
y = int(x) # Converts string to integer
Global and Local Variables:
- Global variables are defined outside of functions and are accessible throughout the program.
- Local variables are defined within functions and are accessible only within that function.
x = 10 # Global variable
def my_function():
x = 5 # Local variable
print(x) # 5 (local x is used)
print(x) # 10 (global x is used)
Changing Global Variables Inside Functions:
To modify a global variable within a function, you need to use the global
keyword.
x = 10
def modify_variable():
global x
x = 20
modify_variable()
print(x) # 20
0 Comments