Chapter 2 : Learn Python Data Types, Variables & Operators
In Python Programming, Data type is an important concept.
Variables can store data of different types, and different types can do different things.
Let's dive into Python Data Types, Variables, and Operators!
Data Types
- Numeric:
- int: Integers (whole numbers) like 1, 2, -3
- float: Floating point numbers (decimals) like 3.14, 2.718
- String:
- str: Text data enclosed in single or double quotes, like "Hello", 'Python'
- Boolean:
- bool: Represents True or False values
- Sequence:
- list: Ordered collection of items, mutable (can be changed), like [1, 2, "Hello"]
- tuple: Ordered collection of items, immutable (cannot be changed), like (1, 2, "Hello")
- Mapping:
- dict: Key-value pairs, like {"name": "John", "age": 30}
- Set:
- set: Unordered collection of unique items, like {1, 2, 3} [1]
Variables
- A variable is a name that represents a value stored in memory.
- You assign values to variables using the = operator.
- Example: x = 10
Operators
- Arithmetic:
- +: Addition
- -: Subtraction
- *: Multiplication
- /: Division
- %: Modulus (remainder)
- **: Exponentiation
- //: Floor Division (integer division)
- Comparison:
- ==: Equal to
- !=: Not equal to
- >: Greater than
- <: Less than
- >=: Greater than or equal to
- <=: Less than or equal to
- Logical:
- and: True if both operands are true
- or: True if at least one operand is true
- not: Negates the operand
- Assignment:
- =: Assign value
- +=: Add and assign
- -=: Subtract and assign
- *=: Multiply and assign
- /=: Divide and assign
- %=: Modulus and assign
- **=: Exponentiation and assign
- //=: Floor Division and assign
Let's see some examples!
|
**2.1 Data Types in Python**
Python is a dynamically typed language, which means you don't need to declare the data type of a variable explicitly. The interpreter automatically infers the data type based on the value assigned to the variable.
Python supports several fundamental data types:
* **Numeric:**
* `int`: Integer numbers (e.g., 10, -5, 0)
* `float`: Floating-point numbers (e.g., 3.14, -2.5)
* `complex`: Complex numbers (e.g., 2+3j)
* **Boolean:**
* `bool`: Boolean values (True or False)
* **String:**
* `str`: Sequence of characters (e.g., "Hello, world!")
* **List:**
* `list`: Ordered collection of items (e.g., [1, 2, 3, "apple"])
* **Tuple:**
* `tuple`: Ordered, immutable collection of items (e.g., (1, 2, 3))
* **Set:**
* `set`: Unordered collection of unique items (e.g., {1, 2, 3})
* **Dictionary:**
* `dict`: Unordered collection of key-value pairs (e.g., {"name": "Alice", "age": 30})
**2.2 Variables in Python**
A variable is a named storage location used to store data values. In Python, you don't need to declare a variable explicitly. You simply assign a value to a variable name.
```python
x = 10 # Integer
y = 3.14 # Float
name = "Alice" # String
is_student = True # Boolean
```
**2.3 Global and Local Variables in Python**
* **Global Variables:**
- Declared outside any function.
- Accessible from anywhere in the program.
* **Local Variables:**
- Declared inside a function.
- Accessible only within that function.
```python
x = 10 # Global variable
def my_function():
y = 20 # Local variable
print(x) # Accessing global variable
print(y) # Accessing local variable
my_function()
```
**2.4 Operators in Python**
Python supports various operators to perform arithmetic, comparison, logical, and bitwise operations.
* **Arithmetic Operators:**
- `+` (Addition)
- `-` (Subtraction)
- `*` (Multiplication)
- `/` (Division)
- `%` (Modulus)
- `//` (Floor Division)
- `**` (Exponentiation)
* **Comparison Operators:**
- `==` (Equal to)
- `!=` (Not equal to)
- `>` (Greater than)
- `<` (Less than)
- `>=` (Greater than or equal to)
- `<=` (Less than or equal to)
* **Logical Operators:**
- `and` (Logical AND)
- `or` (Logical OR)
- `not` (Logical NOT)
* **Bitwise Operators:**
- `&` (Bitwise AND)
- `|` (Bitwise OR)
- `^` (Bitwise XOR)
- `~` (Bitwise NOT)
- `<<` (Left shift)
- `>>` (Right shift)
**2.5 Operator Overloading in Python**
Operator overloading allows you to redefine the behavior of operators for custom data types. This is achieved using special methods called magic methods.
```python
class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __add__(self, other):
return ComplexNumber(self.real + other.real, self.imag + other.imag)
# Example usage:
num1 = ComplexNumber(2, 3)
num2 = ComplexNumber(5, 7)
result = num1 + num2 # Overloading the '+' operator
print(result.real, result.imag)
```
**2.6 Python Programming Examples for Practice**
1. **Calculate the area of a circle:**
```python
radius = float(input("Enter the radius of the circle: "))
area = 3.14159 * radius * radius
print("The area of the circle is:", area)
```
2. **Swap two numbers without using a temporary variable:**
```python
x = 10
y = 20
x, y = y, x
print("x =", x)
print("y =", y)
```
3. **Check if a number is prime:**
```python
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, int(num**0.5) + 1):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
```
Conclusions:
Remember to practice these concepts by writing your own Python programs. Experiment with different data types, operators, and control flow statements to solidify your understanding.
References
Comments
Post a Comment
"Thank you for seeking advice on your career journey! Our team is dedicated to providing personalized guidance on education and success. Please share your specific questions or concerns, and we'll assist you in navigating the path to a fulfilling and successful career."