-
Notifications
You must be signed in to change notification settings - Fork 0
/
python.py
1526 lines (1097 loc) · 44 KB
/
python.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 1. Setting Up Python
# Before you start coding in Python, make sure you have Python installed on your computer.
# Download Python from the official website: https://www.python.org/downloads/
# After installing Python, you can test it in the command line or terminal:
# - Type `python` or `python3` to ensure it is installed correctly.
# 2. Hello World Program
# A basic Python program to print a message:
print("Hello, World!")
# 3. Variables and Data Types
# Variables store data that you can use in your program.
# Python is dynamically typed, meaning you don’t need to declare variable types explicitly.
my_variable = 10 # Integer
my_string = "Hello, Python!" # String
my_float = 10.5 # Float
my_boolean = True # Boolean
# Printing variables
print(my_variable)
print(my_string)
print(my_float)
print(my_boolean)
# 4. Basic Math Operations
# You can perform mathematical operations like addition, subtraction, multiplication, and division in Python.
addition = 5 + 3
subtraction = 10 - 4
multiplication = 7 * 3
division = 12 / 4
# Print the results
print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)
# 5. Lists (Arrays in Python)
# A list is a collection of items that can be of different types.
my_list = [1, 2, 3, "Python", 5.5]
# Accessing list items
print(my_list[0]) # First item
print(my_list[-1]) # Last item
# Modifying a list
my_list.append(100)
print(my_list)
# 6. If-Else Statements
# Conditional statements allow you to execute different code depending on conditions.
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
# 7. Loops
# Python has two types of loops: `for` and `while`.
# For loop example
for i in range(5):
print("Iteration:", i)
# While loop example
counter = 0
while counter < 5:
print("Counter:", counter)
counter += 1
# 8. Functions
# Functions in Python allow you to group reusable code together.
def greet(name):
print("Hello, " + name)
# Calling a function
greet("Alice")
greet("Bob")
# 9. Dictionaries (Key-Value Pairs)
# A dictionary in Python is a collection of key-value pairs.
my_dict = {
"name": "John",
"age": 25,
"location": "New York"
}
# Accessing values in a dictionary
print(my_dict["name"])
print(my_dict["age"])
# Adding or updating items
my_dict["age"] = 26
my_dict["job"] = "Engineer"
print(my_dict)
# 10. Classes and Objects (Object-Oriented Programming)
# Python supports Object-Oriented Programming (OOP). You can create classes and objects.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is " + self.name + " and I am " + str(self.age) + " years old.")
# Creating an object of the Person class
person1 = Person("Alice", 30)
person1.greet()
# 11. Exception Handling
# Exception handling in Python helps you deal with errors gracefully using try-except blocks.
try:
result = 10 / 0 # This will cause a ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero!")
# 12. File Handling
# Python can handle file reading and writing operations.
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, this is a test file.")
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content)
# 13. Lambda Functions
# Lambda functions are small anonymous functions defined using the `lambda` keyword.
# Example of a lambda function:
multiply = lambda x, y: x * y
print(multiply(3, 4)) # Output: 12
# 14. List Comprehensions
# List comprehensions provide a concise way to create lists by applying expressions to each element of an iterable.
# Example of list comprehension:
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
# 15. Modules and Packages
# Modules are Python files that contain code and can be imported into other Python scripts.
# Example of using the math module:
import math
print(math.sqrt(16)) # Output: 4.0
print(math.pi) # Output: 3.141592653589793
# You can also create your own modules by saving Python code into a `.py` file and importing it in other scripts.
# 16. Working with Dates and Times
# The `datetime` module allows working with dates and times.
from datetime import datetime
# Get the current date and time
now = datetime.now()
print(now) # Output: Current date and time
# Formatting date and time
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date) # Output: Formatted current date and time
# 17. Regular Expressions (Regex)
# The `re` module in Python allows you to use regular expressions to search and manipulate strings.
import re
# Searching for a pattern in a string
pattern = r"\d+" # Pattern to find digits
text = "There are 100 apples."
match = re.search(pattern, text)
if match:
print("Match found:", match.group()) # Output: Match found: 100
# 18. Iterators and Generators
# Iterators allow you to traverse through all the elements of a collection. Generators provide a more efficient way to create iterators.
# Example of an iterator:
my_list = [1, 2, 3, 4]
my_iterator = iter(my_list)
print(next(my_iterator)) # Output: 1
print(next(my_iterator)) # Output: 2
# Example of a generator:
def my_generator():
yield 1
yield 2
yield 3
gen = my_generator()
for value in gen:
print(value) # Output: 1 2 3
# 19. Decorators
# Decorators allow you to modify the behavior of functions or methods without changing their code.
# Example of a simple decorator:
def decorator_function(func):
def wrapper():
print("Before the function is called.")
func()
print("After the function is called.")
return wrapper
@decorator_function
def say_hello():
print("Hello!")
say_hello()
# Output:
# Before the function is called.
# Hello!
# After the function is called.
# 20. Working with APIs
# Python allows you to interact with APIs (Application Programming Interfaces) using libraries like `requests`.
import requests
# Sending a GET request to an API
response = requests.get("https://jsonplaceholder.typicode.com/posts")
print(response.status_code) # Output: 200 (OK)
print(response.json()) # Output: JSON data returned from the API
# 21. Multithreading and Multiprocessing
# Python's `threading` module allows running tasks in parallel (multithreading).
# The `multiprocessing` module allows creating separate processes to take advantage of multiple CPU cores.
import threading
# Example of multithreading:
def print_numbers():
for i in range(5):
print(i)
# Creating two threads
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_numbers)
# Starting the threads
thread1.start()
thread2.start()
# 22. Web Development with Flask
# Flask is a lightweight web framework in Python that allows you to build web applications easily.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run(debug=True)
# To run this Flask app, save it in a `.py` file and run it from the command line with:
# $ python filename.py
# Then open your browser and visit http://127.0.0.1:5000/
# 23. Working with Databases (SQLite)
# Python provides built-in support for interacting with databases like SQLite.
import sqlite3
# Connecting to a SQLite database
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# Creating a table
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)''')
# Inserting data
cursor.execute("INSERT INTO users (name) VALUES ('Alice')")
cursor.execute("INSERT INTO users (name) VALUES ('Bob')")
conn.commit()
# Querying data
cursor.execute("SELECT * FROM users")
print(cursor.fetchall()) # Output: [(1, 'Alice'), (2, 'Bob')]
# Closing the connection
conn.close()
# 24. Unit Testing
# Python's `unittest` module allows you to test your code by writing test cases.
import unittest
# Example of a simple test case
def add(a, b):
return a + b
class TestMathOperations(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5) # Test that 2 + 3 equals 5
if __name__ == '__main__':
unittest.main()
# 25. Virtual Environments
# A virtual environment allows you to create isolated Python environments for your projects.
# Creating a virtual environment:
# $ python -m venv myenv
# Activating the virtual environment (Windows):
# $ myenv\Scripts\activate
# Activating the virtual environment (Mac/Linux):
# $ source myenv/bin/activate
# 26. Python Packages
# You can install and use third-party libraries using `pip`, the Python package manager.
# Installing a package using pip:
# $ pip install requests
# Importing and using the installed package:
import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts")
print(response.status_code)
# 27. Working with JSON
# Python's `json` module helps you work with JSON data (JavaScript Object Notation).
import json
# Convert a Python dictionary to JSON
data = {"name": "Alice", "age": 25}
json_data = json.dumps(data)
print(json_data) # Output: '{"name": "Alice", "age": 25}'
# Convert JSON data back to Python dictionary
python_data = json.loads(json_data)
print(python_data) # Output: {'name': 'Alice', 'age': 25}
# 28. File Handling
# Python provides built-in functions to work with files, including reading, writing, and managing files.
# Writing to a file:
with open("sample.txt", "w") as file:
file.write("Hello, Python!\n")
file.write("This is a sample file.")
# Reading from a file:
with open("sample.txt", "r") as file:
content = file.read()
print(content) # Output: Hello, Python!\nThis is a sample file.
# Appending to a file:
with open("sample.txt", "a") as file:
file.write("\nAppended content.")
# 29. Sorting and Filtering
# Python provides several ways to sort and filter data, such as using the `sorted()` function and `filter()`.
# Sorting a list of numbers:
numbers = [4, 1, 3, 2, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 3, 4, 5]
# Filtering a list of numbers (keep only even numbers):
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers)) # Output: [4, 2]
# 30. Mapping Functions
# The `map()` function allows you to apply a function to every item in an iterable.
# Example of using `map()` to square numbers:
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x**2, numbers)
print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]
# 31. Global and Local Variables
# Variables declared inside a function are local, while variables declared outside a function are global.
# Example:
x = 10 # Global variable
def foo():
global x # Accessing the global variable
x = 20 # Modifying the global variable
print(x)
foo() # Output: 20
print(x) # Output: 20
# 32. Recursion
# Recursion is a technique where a function calls itself to solve a problem.
# Example of a recursive function to calculate factorial:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120 (5 * 4 * 3 * 2 * 1)
# 33. Map, Filter, and Reduce
# The `reduce()` function (from the `functools` module) is used to apply a function cumulatively to the items of an iterable.
from functools import reduce
# Example of `reduce()` to sum a list:
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total) # Output: 15
# 34. Handling Exceptions
# Python uses `try`, `except`, `else`, and `finally` blocks to handle exceptions.
# Example of handling exceptions:
try:
value = int(input("Enter a number: "))
except ValueError:
print("Invalid input! Please enter a valid number.")
else:
print(f"You entered: {value}")
finally:
print("This will always be executed.")
# 35. Working with JSON Files
# Python makes it easy to read and write JSON data, which is commonly used in APIs and data exchange.
import json
# Writing a Python object to a JSON file:
data = {"name": "Alice", "age": 25}
with open("data.json", "w") as json_file:
json.dump(data, json_file)
# Reading data from a JSON file:
with open("data.json", "r") as json_file:
loaded_data = json.load(json_file)
print(loaded_data) # Output: {'name': 'Alice', 'age': 25}
# 36. Decorators with Arguments
# Decorators can also accept arguments to modify their behavior.
# Example of a decorator with arguments:
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def say_hello():
print("Hello!")
say_hello() # Output: Hello! Hello! Hello!
# 37. Python's `os` module
# The `os` module allows you to interact with the operating system, such as file handling, directory manipulation, etc.
import os
# Get the current working directory:
print(os.getcwd())
# List files in a directory:
print(os.listdir("."))
# Create a new directory:
os.mkdir("new_directory")
# 38. Python's `sys` module
# The `sys` module provides access to system-specific parameters and functions, including command-line arguments.
import sys
# Get command-line arguments:
print(sys.argv) # Output: List of arguments passed to the script
# Exit the program:
sys.exit("Exiting the program.")
# 39. Python's `time` module
# The `time` module provides functions for working with time-related tasks, such as measuring performance.
import time
# Example of time delay:
print("Start")
time.sleep(2) # Sleep for 2 seconds
print("End") # This will print after 2 seconds
# Measure execution time:
start_time = time.time()
# Some code to measure time for
end_time = time.time()
print(f"Execution time: {end_time - start_time} seconds")
# 40. Python's `collections` module
# The `collections` module provides specialized container datatypes like `namedtuple`, `deque`, `Counter`, etc.
from collections import Counter
# Example of using `Counter` to count occurrences in a list:
word_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_count = Counter(word_list)
print(word_count) # Output: Counter({'apple': 3, 'banana': 2, 'orange': 1})
# 41. Object-Oriented Programming (OOP)
# Python supports Object-Oriented Programming (OOP), allowing you to define classes and objects.
# Example of creating a class:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display(self):
print(f"Car Brand: {self.brand}, Model: {self.model}")
# Creating an object of the Car class:
my_car = Car("Toyota", "Corolla")
my_car.display() # Output: Car Brand: Toyota, Model: Corolla
# 42. Static Methods and Class Methods
# In addition to regular methods, you can define static methods and class methods in Python classes.
class MyClass:
@staticmethod
def static_method():
print("This is a static method.")
@classmethod
def class_method(cls):
print("This is a class method.")
# Calling the static and class methods:
MyClass.static_method()
MyClass.class_method()
# 43. Context Managers
# Context managers allow you to manage resources (like files) with the `with` statement, ensuring proper cleanup.
# Example of a context manager with file handling:
with open("example.txt", "w") as file:
file.write("Hello, Python with context manager!")
# 44. Python's `shutil` module
# The `shutil` module provides high-level file operations like copying and moving files.
import shutil
# Copying a file:
shutil.copy("source.txt", "destination.txt")
# Moving a file:
shutil.move("source.txt", "new_directory/source.txt")
# 45. Python's `sqlite3` module
# Python's `sqlite3` module allows you to interact with SQLite databases.
import sqlite3
# Connect to SQLite database
connection = sqlite3.connect('my_database.db')
# Create a cursor object
cursor = connection.cursor()
# Create a table in SQLite database
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)''')
# Insert data into the table
cursor.execute("INSERT INTO users (name) VALUES ('Alice')")
connection.commit()
# Query data from the table
cursor.execute("SELECT * FROM users")
print(cursor.fetchall()) # Output: [(1, 'Alice')]
# Close the connection
connection.close()
# 46. Regular Expressions (regex)
# Python's `re` module allows you to work with regular expressions for pattern matching in strings.
import re
# Example: Searching for a pattern in a string
text = "The quick brown fox jumps over the lazy dog."
pattern = r"\b\w{5}\b" # Find words with exactly 5 characters
matches = re.findall(pattern, text)
print(matches) # Output: ['quick', 'brown', 'jumps']
# 47. Lambda Functions
# Lambda functions are small anonymous functions defined with the `lambda` keyword.
# Example of a lambda function:
multiply = lambda x, y: x * y
print(multiply(3, 4)) # Output: 12
# 48. Python's `itertools` module
# The `itertools` module provides functions for creating iterators for efficient looping.
import itertools
# Example of using `itertools.combinations` to generate combinations from a list:
numbers = [1, 2, 3, 4]
combinations = itertools.combinations(numbers, 2)
print(list(combinations)) # Output: [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
# 49. Data Structures - Stacks and Queues
# A stack is a collection where elements are added and removed from one end (LIFO).
# A queue is a collection where elements are added from one end and removed from the other (FIFO).
# Example of a stack:
stack = []
stack.append(1) # Push 1
stack.append(2) # Push 2
print(stack.pop()) # Pop 2 (Output: 2)
# Example of a queue using `collections.deque`:
from collections import deque
queue = deque()
queue.append(1) # Enqueue 1
queue.append(2) # Enqueue 2
print(queue.popleft()) # Dequeue 1 (Output: 1)
# 50. Python's `socket` module
# The `socket` module allows you to implement networking, including client-server communication.
import socket
# Example of creating a simple server:
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("localhost", 12345))
server_socket.listen(1)
print("Server is waiting for a connection...")
client_socket, client_address = server_socket.accept()
print("Client connected:", client_address)
# Example of creating a client:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 12345))
client_socket.sendall(b"Hello, Server!")
# 51. Working with CSV Files
# Python's `csv` module provides tools for reading and writing CSV files.
import csv
# Writing data to a CSV file:
header = ["Name", "Age", "Country"]
rows = [["Alice", 25, "USA"], ["Bob", 30, "Canada"]]
with open("people.csv", mode="w", newline="") as file:
writer = csv.writer(file)
writer.writerow(header)
writer.writerows(rows)
# Reading data from a CSV file:
with open("people.csv", mode="r") as file:
reader = csv.reader(file)
for row in reader:
print(row) # Output: ['Name', 'Age', 'Country'], ['Alice', 25, 'USA'], ['Bob', 30, 'Canada']
# 52. Working with Databases (MySQL, PostgreSQL, etc.)
# Python supports working with databases like MySQL, PostgreSQL, SQLite, etc.
import mysql.connector
# Example of connecting to a MySQL database and executing queries:
connection = mysql.connector.connect(
host="localhost", user="root", password="password", database="test_db"
)
cursor = connection.cursor()
cursor.execute("SELECT * FROM users")
result = cursor.fetchall()
print(result)
cursor.close()
connection.close()
# 53. Python's `pandas` Library
# Pandas is a powerful library for data analysis and manipulation. It provides data structures like `DataFrame` and `Series`.
import pandas as pd
# Example of creating a DataFrame:
data = {"Name": ["Alice", "Bob"], "Age": [25, 30], "Country": ["USA", "Canada"]}
df = pd.DataFrame(data)
print(df)
# Example of reading data from a CSV file using pandas:
df = pd.read_csv("people.csv")
print(df)
# 54. Python's `matplotlib` and `seaborn` Libraries
# `matplotlib` is used for creating static visualizations, and `seaborn` is built on top of matplotlib for statistical graphics.
import matplotlib.pyplot as plt
import seaborn as sns
# Example of plotting a simple line chart with matplotlib:
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y)
plt.title("Simple Line Chart")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
# Example of plotting a bar chart with seaborn:
sns.barplot(x=["A", "B", "C"], y=[10, 20, 30])
plt.title("Bar Chart")
plt.show()
# 55. Python's `numpy` Library
# NumPy is a library for numerical computing. It provides support for large multi-dimensional arrays and matrices, as well as a collection of mathematical functions.
import numpy as np
# Example of creating a NumPy array:
arr = np.array([1, 2, 3, 4])
print(arr) # Output: [1 2 3 4]
# Example of performing mathematical operations with NumPy:
arr2 = np.array([5, 6, 7, 8])
sum_arr = np.add(arr, arr2)
print(sum_arr) # Output: [6 8 10 12]
# 56. Web Development with Flask
# Flask is a micro web framework for Python that allows you to build web applications quickly.
from flask import Flask
# Example of a basic Flask application:
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == "__main__":
app.run()
# 57. Web Development with Django
# Django is a high-level web framework that encourages rapid development and clean, pragmatic design.
# Example of a simple Django view:
from django.http import HttpResponse
def my_view(request):
return HttpResponse("Hello, Django!")
# 58. Python's `asyncio` module
# The `asyncio` module allows you to write asynchronous programs, which can be useful for I/O-bound and high-level structured network code.
import asyncio
# Example of an asynchronous function:
async def say_hello():
print("Hello")
await asyncio.sleep(1) # Asynchronous sleep (non-blocking)
print("World")
# Running an event loop:
asyncio.run(say_hello())
# 59. Python's `pytest` Library
# `pytest` is a testing framework for Python that makes it easy to write simple and scalable test cases.
# Example of a simple test case using pytest:
def test_addition():
assert 1 + 1 == 2
# To run the test, you would run `pytest` in the command line.
# 60. Python's `tkinter` Library
# `tkinter` is the standard Python interface to the Tk GUI toolkit.
import tkinter as tk
# Example of creating a simple window with a button:
root = tk.Tk()
button = tk.Button(root, text="Click me", command=lambda: print("Button clicked"))
button.pack()
root.mainloop()
# 61. Python's `threading` module
# The `threading` module allows you to run multiple threads concurrently, which can be useful for parallel tasks.
import threading
# Example of using threading to run two functions simultaneously:
def task1():
print("Task 1 running")
def task2():
print("Task 2 running")
# Creating and starting threads:
thread1 = threading.Thread(target=task1)
thread2 = threading.Thread(target=task2)
thread1.start()
thread2.start()
# Wait for both threads to complete:
thread1.join()
thread2.join()
# 62. Python's `multiprocessing` module
# The `multiprocessing` module allows you to create multiple processes, making it possible to take full advantage of multi-core systems.
import multiprocessing
# Example of using multiprocessing:
def worker():
print("Worker process started")
# Creating and starting a process:
process = multiprocessing.Process(target=worker)
process.start()
process.join()
# 63. Python's `subprocess` module
# The `subprocess` module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
import subprocess
# Example of running a shell command and capturing its output:
result = subprocess.run(['echo', 'Hello, subprocess!'], capture_output=True, text=True)
print(result.stdout) # Output: Hello, subprocess!
# 64. Python's `os` and `sys` Modules
# The `os` module provides a way of using operating system-dependent functionality, and `sys` allows you to interact with the Python runtime environment.
import os
import sys
# Example of using `os` to get the current working directory:
current_directory = os.getcwd()
print(current_directory)
# Example of using `sys` to interact with command-line arguments:
print(sys.argv) # List of command-line arguments
# 65. Python's `logging` module
# The `logging` module provides a way to log messages from your application, useful for debugging and tracking application behavior.
import logging
# Example of configuring and using the logging module:
logging.basicConfig(level=logging.INFO)
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")
# 66. Python's `json` module
# The `json` module allows you to work with JSON data, both reading and writing.
import json
# Example of converting a Python object to a JSON string:
data = {"name": "Alice", "age": 25}
json_string = json.dumps(data)
print(json_string) # Output: {"name": "Alice", "age": 25}
# Example of converting a JSON string back to a Python object:
json_data = '{"name": "Bob", "age": 30}'
python_data = json.loads(json_data)
print(python_data) # Output: {'name': 'Bob', 'age': 30}
# 67. Python's `hashlib` module
# The `hashlib` module allows you to create secure hash values using different algorithms like SHA-256.
import hashlib
# Example of generating a SHA-256 hash:
text = "Hello, world!"
hashed_text = hashlib.sha256(text.encode()).hexdigest()
print(hashed_text) # Output: A long SHA-256 hash
# 68. Python's `functools` module
# The `functools` module provides higher-order functions that operate on or return other functions.
from functools import lru_cache
# Example of using the Least Recently Used (LRU) cache to optimize a function:
@lru_cache(maxsize=3)
def expensive_function(x):
print(f"Computing {x}...")
return x * x
print(expensive_function(2)) # Output: Computing 2... 4
print(expensive_function(2)) # Output: 4 (cached result)
# 69. Python's `collections` module
# The `collections` module includes useful data structures like `defaultdict`, `deque`, `namedtuple`, and `Counter`.
from collections import defaultdict
# Example of using a defaultdict:
default_dict = defaultdict(int) # Default value is 0
default_dict["apple"] += 1
print(default_dict["apple"]) # Output: 1
# 70. Python's `memoryview` object
# The `memoryview` object allows you to access the internal data of objects like bytes and bytearrays without making copies.
# Example of using memoryview with a bytearray:
data = bytearray(b"Hello, world!")
view = memoryview(data)
print(view[0]) # Output: 72 (ASCII code of 'H')
# 71. Python's `weakref` module
# The `weakref` module allows you to create weak references to objects, which do not prevent garbage collection.
import weakref
# Example of creating a weak reference to an object:
class MyClass:
def __del__(self):
print("MyClass instance deleted")
obj = MyClass()
weak_ref = weakref.ref(obj)
del obj # Output: MyClass instance deleted
# 72. Python's `pickle` module
# The `pickle` module allows you to serialize and deserialize Python objects, enabling saving and loading of objects.
import pickle
# Example of pickling an object:
data = {"name": "Alice", "age": 25}
with open("data.pickle", "wb") as f:
pickle.dump(data, f)
# Example of unpickling an object:
with open("data.pickle", "rb") as f:
loaded_data = pickle.load(f)
print(loaded_data) # Output: {'name': 'Alice', 'age': 25}
# 73. Python's `contextlib` module
# The `contextlib` module provides utilities for working with context managers, which simplify resource management.
from contextlib import contextmanager
# Example of using contextlib to create a custom context manager:
@contextmanager
def my_context_manager():
print("Entering context")
yield
print("Exiting context")
with my_context_manager():
print("Inside context")
# Output:
# Entering context
# Inside context
# Exiting context
# 74. Python's `uuid` module
# The `uuid` module generates universally unique identifiers (UUIDs).
import uuid
# Example of generating a random UUID:
generated_uuid = uuid.uuid4()
print(generated_uuid) # Output: e.g., 2f3c14f8-c3d1-4b7b-91c4-076073dfb320
# 75. Python's `inspect` module
# The `inspect` module allows introspection of live objects, including functions and classes.
import inspect
# Example of getting information about a function:
def my_function(a, b):
return a + b