Python does not require manual type declaration for variables. The type is automatically inferred from the assigned value.
x = 5 # Integer variable name = "Python" # String variable pi = 3.14 # Floating-point variable
Python supports dynamic typing—variable types change based on the value assigned:
x = 5 print(type(x)) # Output:x = "Hello" print(type(x)) # Output:
Type | Example | Description |
---|---|---|
int | 5 | Whole number |
float | 3.14 | Decimal number |
complex | 2 + 3j | Complex number (real + imaginary) |
Mathematical operations can be performed directly:
a = 10 b = 3.5 print(a + b) # Output: 13.5
Strings are sequences of characters and can be defined using single or double quotes:
text = "Hello, Python!"
Common string operations:
message = "Python Programming" print(len(message)) # Count characters print(message.upper()) # Convert to uppercase print(message.lower()) # Convert to lowercase print(message.replace("Python", "Java")) # Replace word
Strings use zero-based indexing:
word = "Python" print(word[0]) # Output: P print(word[-1]) # Output: n (last character)
Slicing extracts specific portions of a string:
message = "Programming" print(message[0:5]) # Output: Progr print(message[:7]) # Output: Program print(message[3:]) # Output: gramming