Python CookBook

Share

            Python CookBook

Sure, here are some fundamental Python “recipes” you might find useful.

  1. Reading a File
python
with open('myfile.txt', 'r') as f:
data = f.read()
  1. Writing to a File
python
with open('myfile.txt', 'w') as f:
f.write("Hello, world!")
  1. Sorting a List of Dictionaries by a Common Key
python
from operator import itemgetter
list_of_dicts = [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 23}, {'name': 'Dave', 'age': 30}]
sorted_list = sorted(list_of_dicts, key=itemgetter('age'))
  1. Creating a Dictionary from Two Lists
python
keys = ['name', 'age', 'job']
values = ['John', 25, 'developer']
dict_from_lists = dict(zip(keys, values))
  1. Catching Exceptions
python
try:
# risky operation
risky_operation()
except Exception as e:
print(f"Caught an exception: {e}")
  1. Creating a Function with Optional Arguments
python
def my_function(a, b, c=None):
if c is None:
c = []
# do something
  1. Iterating Over a List with Indices
python
my_list = ['apple', 'banana', 'cherry']
for i, value in enumerate(my_list):
print(f"Item {i} is {value}")
  1. List Comprehensions
python
squares = [x**2 for x in range(10)]
  1. Lambda Functions
python
f = lambda x: x**2
print(f(5)) # prints 25
  1. Filtering Items in a List
python
my_list = [1, 2, 3, 4, 5]
filtered_list = list(filter(lambda x: x % 2 == 0, my_list)) # [2, 4]
  1. Using map to Apply a Function to All Items in a List
python
my_list = [1, 2, 3, 4, 5]
squared_list = list(map(lambda x: x**2, my_list)) # [1, 4, 9, 16, 25]

Remember that Python is a highly flexible language, and there are often many ways to achieve the same result. These are some idiomatic examples, but other approaches could also be valid.

Python Training Demo Day 1

 
You can find more information about Python in this Python Link

 

Conclusion:

Unogeeks is the No.1 IT Training Institute for Python  Training. Anyone Disagree? Please drop in a comment

You can check out our other latest blogs on Python here – Python Blogs

You can check out our Best In Class Python Training Details here – Python Training

💬 Follow & Connect with us:

———————————-

For Training inquiries:

Call/Whatsapp: +91 73960 33555

Mail us at: info@unogeeks.com

Our Website ➜ https://unogeeks.com

Follow us:

Instagram: https://www.instagram.com/unogeeks

Facebook: https://www.facebook.com/UnogeeksSoftwareTrainingInstitute

Twitter: https://twitter.com/unogeeks


Share

Leave a Reply

Your email address will not be published. Required fields are marked *