Programming Basics - Comprehensive Explanation
1. Data Types
Data types define the nature of data that can be stored and manipulated in a programming
language.
Types of Data:
1. Primitive Data Types - Basic types of data that represent single values.
2. Composite Data Types - Collections or groupings of values.
3. Abstract Data Types (ADTs) - Data structures designed for specific functionalities.
Primitive Data Types:
- Integer (int): Whole numbers (e.g., 10, -5, 200)
Example:
```python
age = 25
print(age)
```
- Floating-Point (float): Numbers with decimal points (e.g., 3.14, -0.001, 2.0)
```python
pi = 3.14159
print(pi)
```
- Boolean (bool): Represents True or False values
```python
is_raining = True
print(is_raining)
```
- String (str): Sequence of characters (e.g., "Hello, World!", 'Python')
```python
name = "Alice"
print(name)
```
Composite Data Types:
- List (list): Ordered, mutable collection of elements.
```python
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
```
- Tuple (tuple): Ordered, immutable collection.
```python
coordinates = (10, 20)
print(coordinates[1]) # Output: 20
```
- Dictionary (dict): Key-value pairs, unordered, mutable.
```python
person = {"name": "Alice", "age": 30}
print(person["name"]) # Output: Alice
```
- Set (set): Unordered collection of unique elements.
```python
numbers = {1, 2, 3, 4, 4, 5}
print(numbers) # Output: {1, 2, 3, 4, 5}
```
2. Casting and Operators
Casting:
- Integer to String:
```python
num = 100
str_num = str(num)
print(str_num) # Output: "100"
```
- String to Integer:
```python
str_value = "50"
int_value = int(str_value)
print(int_value) # Output: 50
```
Operators:
- Arithmetic Operators:
```python
a = 10
b=3
print(a + b) # Addition -> 13
print(a - b) # Subtraction -> 7
```
- Comparison Operators:
```python
x=5
y = 10
print(x == y) # False
print(x < y) # True
```
- Logical Operators:
```python
a = True
b = False
print(a and b) # False
print(a or b) # True
```
3. Constants and Variables
Variables:
```python
name = "John"
age = 25
print(name, age)
```
Constants (Python uses uppercase convention):
```python
PI = 3.14159
print(PI)
```
4. Strings
String Operations:
- Concatenation:
```python
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: John Doe
```
- String Indexing:
```python
text = "Hello"
print(text[0]) # Output: H
print(text[-1]) # Output: o
```
- String Methods:
```python
text = "hello world"
print(text.upper()) # HELLO WORLD
print(text.capitalize()) # Hello world
```
Conclusion
Understanding these programming basics is crucial for working with data effectively.