Python is a versatile programming language that offers powerful features for data manipulation. In this article, we’ll explore the basic operations in Python, focusing on strings, lists, dictionaries, control structures, and some advanced features.
String Operations
Strings are sequences of Unicode characters. Here are some common string operations in Python:
String Concatenation
Concatenation is the operation of merging two strings into one.
1
2
3
4
| first_name = "Eya"
last_name = "Garci"
full_name = first_name + " " + last_name
print(full_name) # Output: Eya Garci
|
Formatting allows inserting values into a string dynamically.
1
2
3
4
5
6
| city = "Paris"
population = 2_200_000
area = 105.4
formatted_string = f"The city of {city} has a population of {population} and covers an area of {area} square kilometers."
print(formatted_string) # Output: The city of Paris has a population of 2_200_000 and covers an area of 105.4 square kilometers.
|
String Methods
Python provides many built-in methods for manipulating strings, such as lower(), upper(), split(), strip(), replace(), etc.
1
2
3
4
| s = "Hello, World!"
print(s.lower()) # Output: hello, world!
print(s.upper()) # Output: HELLO, WORLD!
print(s.split(", ")) # Output: ['Hello', 'World!']
|
String Slicing
Slicing allows extracting a part of a string.
1
2
| s = "Hello, World!"
print(s[7:]) # Output: World!
|
List Operations
Lists are ordered sequences of mutable elements. Here are some common list operations in Python:
Creating Lists
Lists can be created by placing elements within square brackets [].
1
| my_list = [1, 2, 3, 4, 5]
|
Accessing List Elements
Elements of a list can be accessed by their index.
1
| print(my_list[0]) # Output: 1
|
Adding and Removing Elements
Elements can be added to a list with the append() method and removed with the remove() and pop() methods.
1
2
3
4
5
6
7
8
| my_list.append(6)
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
my_list.remove(3)
print(my_list) # Output: [1, 2, 4, 5, 6]
popped_element = my_list.pop()
print(popped_element) # Output: 6
|
Copying Lists
Be careful, using = does not create a new list but references the same list.
1
2
3
4
5
| list1 = [1, 2, 3]
list2 = list1
list2.append(4)
print(list1) # Output: [1, 2, 3, 4]
To create an independent copy, use the copy() method or slicing [:].
|
1
2
3
4
| list1 = [1, 2, 3]
list2 = list1.copy()
list2.append(4)
print(list1) # Output: [1, 2, 3]
|
Dictionary Operations
Dictionaries are unordered collections of key-value pairs. Here are some common dictionary operations in Python:
Creating Dictionaries
Dictionaries can be created using key-value pairs within braces {}.
1
| my_dict = {'name': 'Arti', 'age': 29, 'city': 'New York'}
|
Accessing Dictionary Elements
Elements of a dictionary can be accessed by their key.
1
| print(my_dict['name']) # Output: John
|
Adding and Removing Elements
Elements can be added to a dictionary by assigning a new value to a key and removed with the del keyword.
1
2
3
4
5
| my_dict['email'] = 'arti@example.com'
print(my_dict) # Output: {'name': 'Arti', 'age': 29, 'city': 'New York', 'email': 'arti@example.com'}
del my_dict['age']
print(my_dict) # Output: {'name': 'Arti', 'city': 'New York', 'email': 'arti@example.com'}
|
Iterating Over a Dictionary
You can iterate over a dictionary using a for loop.
1
2
| for key, value in my_dict.items():
print(key, value)
|
Control Structures
Python offers various control structures to direct the flow of execution of the program:
Conditions with if, elif, else
The if, elif, else statements are used to execute blocks of code based on conditions.
1
2
3
4
5
6
7
| x = 10
if x > 7:
print("x is greater than 7")
elif x == 7:
print("x is 7")
else:
print("x is less than 7")
|
for and while Loops
Python offers for loops to iterate over a sequence and while loops to execute a block of code as long as a condition is true.
1
2
3
4
5
6
7
8
9
| # For loop
for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4
# While loop
count = 0
while count < 5:
print(count)
count += 1
|
Error Handling with try and except
Basic try-except
1
2
3
4
| try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
|
Multiple Exceptions
1
2
3
4
5
| try:
# code that may raise an exception
x = 1 / 0
except (ZeroDivisionError, ValueError):
print("An error occurred")
|
Catch Exception and Get Error Message
1
2
3
4
5
| try:
# code
x = 1 / 0
except Exception as e:
print(f"An error occurred: {e}")
|
Functions
Basic Function
1
2
| def greet(name):
return f"Hello, {name}"
|
Function with Default Argument
1
2
| def greet(name="World"):
return f"Hello, {name}"
|
Function with Arbitrary Number of Arguments
1
2
| def sum_all(*args):
return sum(args)
|
Function with Keyword Arguments
1
2
3
4
| def greet_with_log(name, log=False):
if log:
print(f"Logging: Greeted {name}")
return f"Hello, {name}"
|
File Operations
Reading a File
1
2
| with open('file.txt', 'r') as f:
content = f.read()
|
Writing to a File
1
2
| with open('file.txt', 'w') as f:
f.write('Hello, World!')
|
Appending to a File
1
2
| with open('file.txt', 'a') as f:
f.write('\nAppending text')
|
Importing Modules and Libraries
Importing Entire Module
Importing Specific Function
Importing and Aliasing
Working with Dates
1
2
3
4
5
6
7
8
9
10
| from datetime import datetime, timedelta
# Get current date and time
now = datetime.now()
# Format date
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
# Date arithmetic
tomorrow = now + timedelta(days=1)
|
Basic Logging to Console
Basic Logging
1
2
3
4
| import logging
logging.basicConfig(level=logging.INFO)
logging.info('This is an info message')
|
Logging Levels
1
2
3
4
5
| logging.debug('Debug message')
logging.info('Informational message')
logging.warning('Warning message')
logging.error('Error message')
logging.critical('Critical error message')
|
Logging to a File
1
2
| logging.basicConfig(filename='app.log', level=logging.INFO)
logging.info('Logged to file')
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
| import logging
# Create logger
logger = logging.getLogger('my_logger')
logger.setLevel(logging.INFO)
# Create console handler and set level to debug
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
# Create file handler and set level to info
file_handler = logging.FileHandler('app.log')
file_handler.setLevel(logging.INFO)
# Create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# Add formatter to handlers
console_handler.setFormatter(formatter)
file_handler.setFormatter(formatter)
# Add handlers to logger
logger.addHandler(console_handler)
logger.addHandler(file_handler)
# Log messages
logger.debug('Debug message')
logger.info('Info message')
logger.warning('Warning message')
logger.error('Error message')
logger.critical('Critical message')
|
Exception Logging
1
2
3
4
| try:
x = 1 / 0
except Exception as e:
logging.error(f'An error occurred: {e}', exc_info=True)
|
Conditional Logging
1
2
3
| x = 5
if x < 10:
logging.warning(f'x is less than 10: x={x}')
|
Operators
Arithmetic Operators
1
2
3
4
5
6
7
| print(3 + 2) # Addition: 5
print(3 - 2) # Subtraction: 1
print(3 * 2) # Multiplication: 6
print(3 / 2) # Division: 1.5
print(3 % 2) # Modulus: 1
print(3 ** 2) # Exponentiation: 9
print(3 // 2) # Floor Division: 1
|
Comparison Operators
1
2
3
4
5
6
| print(3 == 2) # Equal: False
print(3 != 2) # Not equal: True
print(3 > 2) # Greater than: True
print(3 < 2) # Less than: False
print(3 >= 2) # Greater than or equal to: True
print(3 <= 2) # Less than or equal to: False
|
Logical Operators
1
2
3
| print(True and False) # and: False
print(True or False) # or: True
print(not True) # not: False
|
Assignment Operators
1
2
3
4
5
| a = 3
a += 2 # Add and assign: a = 5
a -= 1 # Subtract and assign: a = 4
a *= 2 # Multiply and assign: a = 8
a /= 4 # Divide and assign: a = 2.0
|
Bitwise Operators
1
2
3
4
5
6
| print(3 & 2) # Bitwise AND: 2 (0b11 & 0b10 = 0b10)
print(3 | 2) # Bitwise OR: 3 (0b11 | 0b10 = 0b11)
print(3 ^ 2) # Bitwise XOR: 1 (0b11 ^ 0b10 = 0b01)
print(~3) # Bitwise NOT: -4 (two's complement of 0b11 is -0b100)
print(3 << 1) # Bitwise left shift: 6 (0b11 << 1 = 0b110)
print(3 >> 1) # Bitwise right shift: 1 (0b11 >> 1 = 0b1)
|
Membership Operators
1
2
3
| numbers = [1, 2, 3, 4, 5]
print(3 in numbers) # in: True
print(6 not in numbers) # not in: True
|
Identity Operators
1
2
3
4
5
6
| a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b) # is: True (a and b refer to the same list)
print(a is c) # is: False (a and c are equal but refer to different lists)
print(a is not c) # is not: True
|
Integrated Code Example
Below is an example Python script that integrates various elements: variables, data types, functions, control structures (if, elif, else, while), error handling (try and except), and logging. This example aims to show how these elements can work together in a single Python script.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
| import logging
# Initialize logging
logging.basicConfig(level=logging.INFO)
# Function Definitions
def greet(name):
return f"Hello, {name}!"
def is_even(number):
return number % 2 == 0
def add(a, b):
return a + b
# Logging example
logging.info("Starting the program")
# Variables
name = "Ivan"
age = 30
# List
numbers = [1, 2, 3, 4]
# Dictionary
person = {'name': 'Ivan', 'age': 30}
# Basic if-elif-else
if age >= 18:
logging.info("You are an adult.")
elif age >= 13:
logging.info("You are a teenager.")
else:
logging.info("You are a child.")
# Using functions
greeting = greet(name)
logging.info(greeting)
# Error handling with try-except
try:
result = add("10", 20)
except TypeError as e:
logging.error(f"An error occurred: {e}")
# Loop with while
counter = 0
while counter < 3:
logging.info(f"Counter is at {counter}")
counter += 1
# Check if a number is even
if is_even(10):
logging.info("The number is even.")
else:
logging.info("The number is odd.")
# Logging example
logging.info("Ending the program")
|
Conclusion
This guide covered the basic operations in Python, including string manipulations, list operations, dictionary operations, and control structures. With this knowledge, you’re ready to start programming in Python and explore its more advanced features.