This is a repository that contains all the resources that I have used to learn Python. Down below, you will find a table of contents that will help you navigate through the resources.
- Lessons
- Exercises
- ✅ Semantic versioning:
- ✅ Install pipenv
- ✅ To create requirements.txt file
- ✅ Modules
🎯 Here are some resources to help you get started with Python and exercise 💪👇️
- Practice Python (https://www.practicepython.org/)
- HackerRank (https://www.hackerrank.com/domains/python)
- Project Euler (https://projecteuler.net/archives)
- Codewars (https://www.codewars.com/kata/search/python)
- ex: 3.11.0
- "3" - Major version
- "11" - Minor version
- "0" - Patch version
To install pipenv
, run the following commands:
pip install pipenv
pipenv --version
If it did not work, try the following steps:
- Uninstall
virtualenv
andpipenv
:python -m pip uninstall virtualenv pipenv -y py -m pip uninstall virtualenv pipenv -y python3 -m pip uninstall virtualenv pipenv -y
- Upgrade
setuptools
andwheel
:python -m pip install --upgrade setuptools wheel
- Reinstall
pipenv
:python -m pip install --user pipenv
If you encounter the error:
'pipenv' is not recognized as an internal or external command, operable program or batch file
Follow these steps to resolve it:
- Get the path to the base directory for the user site-packages by running:
Example output:
python -m site --user-site
C:\Users\YourUsername\AppData\Roaming\Python\Python37\site-packages
- Replace
site-packages
in the path withScripts
and add it to your system PATH:- On Windows: Edit environment variables for your account > in the User variables select
Path
> Edit > New >C:\Users\YourUsername\AppData\Roaming\Python\Python37\Scripts
- On Windows: Edit environment variables for your account > in the User variables select
- The outdated command:
pipenv lock -r > requirements.txt
- The new version:
pipenv run pip freeze > requirements.txt
- Codete - 10 Built-in Modules in Python You Should Know
- Levelup - 11 Most Useful Built-in Python Modules You Might Not Know Yet
-
random.random()
:- Return the next random floating point number in the range [0.0, 1.0).
import random print(random.random())
-
random.randint(a, b)
:- Return a random integer N such that a <= N <= b.
import random print(random.randint(0, 10))
-
random.choice(seq)
:- Return a random element from the non-empty sequence
seq
. Ifseq
is empty, raisesIndexError
.
import random x = [i for i in range(10)] print(random.choice(x))
- Return a random element from the non-empty sequence
-
random.shuffle(x[, random])
:- Shuffle the sequence
x
in place.
import random x = [[i] for i in range(10)] random.shuffle(x) print(x)
- Shuffle the sequence
-
math.ceil(x)
:- Return the ceiling of
x
as a float, the smallest integer value greater than or equal tox
.
import math print(math.ceil(4.2))
- Return the ceiling of
-
math.floor(x)
:- Return the floor of
x
as a float, the largest integer value less than or equal tox
.
import math print(math.floor(4.8))
- Return the floor of
-
math.trunc(x)
:- Return the Real value
x
truncated to an Integral (usually an integer).
import math print(math.trunc(4.8))
- Return the Real value
-
math.factorial(x)
:- Return
x
factorial as an integer. RaisesValueError
ifx
is not integral or is negative.
import math print(math.factorial(5))
- Return
-
math.gcd(a, b)
:- Return the greatest common divisor of the specified integer arguments.
import math print(math.gcd(10, 20))
-
math.pow(x, y)
:- Return
x
raised to the powery
.
import math print(math.pow(2, 3))
- Return
-
math.sqrt(x)
:- Return the square root of
x
.
import math print(math.sqrt(16))
- Return the square root of
-
math.pi
:- The mathematical constant π = 3.141592…, to available precision.
import math print(math.pi)
-
time.time()
:- Return the time in seconds since the epoch as a floating point number.
import time print(time.time()) print("tm_wday =>", time_z.tm_wday) print("tm_min =>", time_z.tm_min) print("tm_isdst =>", time_z.tm_isdst) print("tm_mday =>", time_z.tm_mday) print("tm_year =>", time_z.tm_year) print("tm_zone =>", time_z.tm_zone)
-
time.sleep(secs)
:- Suspend execution of the calling thread for the given number of seconds.
import time time.sleep(1)
-
time.localtime([secs])
:- Convert a time expressed in seconds since the epoch to a
struct_time
in local time.
import time print(time.localtime())
- Convert a time expressed in seconds since the epoch to a
-
time.strftime(format[, t])
:- Convert a tuple or
struct_time
representing a time to a string as specified by the format argument.
import time print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 1. %y => is year in short version => Годы в краткой версии # 2. %Y => is year in full version => Годы в полной версии # 3. %m => is month in number => Месяцы в числовом формате # 4. %M => is minute in number => Минуты в числовом формате # 5. %d => is day in number => Дни в числовом формате # 6. %D => is Date (full date) => Дата (полная дата) # 7. %h => is month in short version => Месяцы в краткой версии # 8. %H => is hour in number => Часы в числовом формате # 9. %s => DOES NOT EXIST => НЕ СУЩЕСТВУЕТ # 10. %S => is second in number => Секунды в числовом формате
- Convert a tuple or
-
datetime.datetime.now()
:- Return the current local date and time.
import datetime print(datetime.datetime.now())
-
datetime.datetime(year, month, day, ...)
:- The year, month, and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass.
import datetime print(datetime.datetime(2020, 5, 17, 12, 30, 0, 0))
-
timedelta
:
- EN: The timedelta class is used to represent the difference between two dates or times.
import datetime
print(datetime.timedelta(days=365, hours=5, minutes=1))
- timedelta can add days, seconds and microseconds to a datetime object
import datetime
now = datetime.now()
print(now)
>>> datetime.datetime(2023, 7, 31, 12, 30, 10, 999999)
print(now + datetime.timedelta(days=365))
>>> datetime.datetime(*2024*, 7, 30, 12, 30, 10, 999999)
-
json.dumps(obj)
:- Serialize
obj
to a JSON formattedstr
.
import json print(json.dumps({}))
- Serialize
-
json.loads(s)
:- Deserialize
s
(astr
,bytes
orbytearray
instance containing a JSON document) to a Python object.
import json print(json.loads("{}"))
- Deserialize
Logging is a means of tracking events that happen when some software runs. It has an ordered list of levels that indicate the severity of events:
DEBUG
: Detailed information, typically of interest only when diagnosing problems.INFO
: Confirmation that things are working as expected.WARNING
: An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’).ERROR
: Due to a more serious problem, the software has not been able to perform some function.CRITICAL
: A serious error, indicating that the program itself may be unable to continue running.
To configure the logging module, you must use the basicConfig()
function:
import logging
logging.basicConfig(
level=logging.DEBUG,
filename='app.log',
filemode='a+',
format='%(levelname)s - %(message)s - %(asctime)s'
)
logging.debug('This is a debug message')
This library is similar to axios
in JavaScript.
import requests
# HTTP METHODs
# axios.get() # get data from server => Получить данные с сервера
# axios.post() # send data to server => Отправить данные на сервер
# axios.put() # update data on server => Обновить данные на сервере
# axios.delete() # delete data from server => Удалить данные с сервера
# axios.patch() # partially update data on server => Частично обновить данные на сервере
URL = "https://reqres.in/api/users?page=2"
response = requests.get(URL)
print("Status:", response)
users = response.json().get("data", "No data found")
for user in users:
str = f"""
Name: {user["first_name"]} {user["last_name"]}
Email: {user["email"]}
------------------------------------------------
"""
print(str)
# {}[key] # raise error if key not found
# {}.get(key) # return None if key not found
# ===================================================================
# In js we would do:
# axios.get('https://...')
# In python we do:
# response = requests.get('https://...')
# # To get the status code:
# print(response.status_code)
# # To get the content:
# print(response.content)
# # To get the json:
# print(response.json())
This library generates fake data.
from faker import Faker
fake = Faker()
print(fake.name())
print(fake.address())
print(fake.text())
print(fake.email())
print(fake.phone_number())
print(fake.country())
print(fake.url())
import translators as ts
original_text = "Hello, what a beautiful weather it is today!"
arabic_translation = ts.translate_text(original_text, to_language='ar')
print("ARABIC translation:", arabic_translation)
uzbek_translation = ts.translate_text(original_text, to_language='uz')
print("UZBEK translation:", uzbek_translation)
russian_translation = ts.translate_text(original_text, to_language='ru')
print("RUSSIAN translation:", russian_translation)
japanese_translation = ts.translate_text(original_text, to_language='ja')
print("JAPANESE translation:", japanese_translation)
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
# OUTPUT:
# ARABIC translation: مرحبا ، يا له من طقس جميل اليوم!
# UZBEK translation: Assalomu alaykum bugungi kun qanday go'zal ob-havo!
# RUSSIAN translation: Здравствуйте, какая сегодня прекрасная погода!
# JAPANESE translation: こんにちは、今日はなんと美しい天気でしょう!
# Source: https://regexr.com/
import re
# string = "The rain in Spain"
# pattern = "ai"
# r_pattern = r'[A-Z]'
# --------------------------------------
# re.findall(pattern, string) # => It returns a list of all matching patterns.
# result = re.findall(pattern, string)
# print(result)
# --------------------------------------
# re.search(pattern, string) # => It returns first match's position
# result = re.search(r_pattern, string)
# print(result)
# --------------------------------------
# re.split(pattern, string)
# => Works like split() method of strings but can take RE as separator.
# r_pattern = r'[A-Z]'
# string = "The rain in Spain"
# result = re.split(r_pattern, string)
# print(result)
# --------------------------------------
# re.sub(pattern, repl, string, count=0, flags=re...)
# # => It returns a new string with all matches of the pattern replaced by repl.
# ________________
# r_pattern = r'[A-Z]'
# string = "The rain in Spain"
# result = re.sub(r_pattern, '*', string)
# print(result)
# ________________
# 1. pattern => The regular expression pattern string.
# 2. repl => The replacement string.
# 3. string => The source string.
# 4. count => Maximum number of occurrences that will be replaced.
# If not specified or is 0, all occurrences will be replaced.
# 5. flags => A combination of re flags.
# --------------------------------------
# re.compile(pattern, flags=0)
# => It returns a regular expression object.
# r_pattern = r'[A-Z]'
# string = "The rain in Spain"
# pattern = re.compile(r_pattern)
# result = pattern.findall(string)
# print(result)
# f''
# ''.format()
# ======= Username pattern =======
# re.compile(r'@([A-Za-z0-9_]+)')
# @ -> indicates the start of the username
# () -> indicates the start and end of the username
# [] -> indicates the range of characters that can be used in the username
# + -> indicates that the username must contain at least one character
# A-Za-z0-9_ -> indicates the range of characters that can be used in the username
# Ex: @username
# Ex: @user_name
# To test if it works, use the following code:
# username = '@user_name'
# print(re.search(r'@([A-Za-z0-9_]+)', username) != None)
# ============================================================
# ^ (Caret) => It matches the start of the string.
# string = "Hello World!"
# x = re.findall("^Hello", string)
# print(x)
# ============================================================
# # $ (Dollar) => It matches the end of the string.
# string = "Hello World!"
# x = re.findall("World!$", string)
# print(x)
# # ============================================================
# . (Dot) => It matches any character except a newline.
# string = "Hello World!"
# x = re.findall("H.ll.", string)
# print(x)
-
collections.deque
from collections import deque queue = deque() queue.append(5) queue.append("Mine") queue.append(True) queue.appendleft(10) print(queue) queue.rotate(2) print(queue)
-
collections.Counter
from collections import Counter arr = [1, 1, 1, 2, 2, 3, 3, 3, 3, 3] word = "Hello World" lc = Counter(arr) wc = Counter(word) print(lc) print(wc) print(lc.most_common(2)) print(wc.total())
-
collections.defaultdict
from collections import defaultdict d = defaultdict(int) d['a'] = 1 d['b'] = 2 print(d['c'])