Python is a fun, relatively easy to learn, and powerful programming language. Python is cool, too. Don’t you believe me? Let me show you some examples.
user@pc:~$ python Python 3.9.5 (default, May 11 2021, 08:20:37) [GCC 10.3.0] on linux Type "help", "copyright", "credits" or "license" for more information.
>>> import this
# It is displayed by typing **import this**. The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one‐‐ and preferably only one ‐‐obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea ‐‐ let’s do more of those!
>>> import __hello__ # Other Easter egg. Hello world!
>>> from __future__ import braces
Don't you like using whitespaces in Python to denote scopes? Maybe, just maybe you could use the C-style braces {} from the future...
File "", line 1 SyntaxError: not a chance
user@pc:~$ python Python 3.9.5 (default, May 11 2021, 08:20:37) [GCC 10.3.0] on linux Type "help", "copyright", "credits" or "license" for more information.
>>> from faker import Faker
>>> fake = Faker() # We create and initialize a fake generator.
>>> fake.name() # We call its methods to generate fake names, addresses, emails, etc.
'Lindsey Williams'
>>> fake.address()
'3346 Jeffrey Bypass\nNorth Michael, MT 79279'
>>> fake.sentence()
'Show summer now stuff total ready.'
>>> fake.email()
'laurie47@example.org'
>>> fake.country()
'Albania'
>>> fake.profile()
{'job': 'Financial adviser', 'company': 'Nichols-Romero', 'ssn': '366-02-9979', 'residence': '280 Sean Pine\nChenberg, PA 42513', 'current_location': (Decimal('-12.6499745'), Decimal('-174.891558')), 'blood_group': 'AB+', 'website': ['http://www.harmon.org/', 'https://www.chandler-pacheco.com/', 'http://www.haley-brooks.biz/'], 'username': 'garyvillanueva', 'name': 'John Jones', 'sex': 'M', 'address': '7284 Robin Parkway\nMichaelstad, FL 28169', 'mail': 'osbornejeremiah@hotmail.com', 'birthdate': datetime.date(1983, 2, 5)}
>>> fake.text()
'Plant live science mind. Sign case kind while accept floor. Note identify series. Day score reveal arrive form when good. Range mind president two parent evidence.'
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
def myWordCloud(file, mask, fileCloud):
# It reads the whole text (file).
text = open(file, 'r').read()
stopwords = set(STOPWORDS)
# It reads the mask image and creates an array from the image we want to use as a mask.
custom_mask = np.array(Image.open(mask))
# It instantiates a wordcloud object.
wc = WordCloud(background_color = 'white', # It defines the background color.
scale=3,
stopwords = stopwords,
mask = custom_mask,
collocations=True,
colormap='RdYlGn', # It changes the ‘colormap’ to ‘RdYlGn’.
contour_width = 0.1,
contour_color = '#5d0f24')
# We use the generate method to feed the wordcloud object (wc) with our corpus and generate a word cloud image.
wc.generate(text)
# We store the cloud object to a file.
wc.to_file(fileCloud)
return wc
# It plots our word cloud.
def plotting(title):
plt.figure(figsize=(10,8))
# It displays the word cloud object.
plt.imshow(wc, interpolation = 'bilinear')
# We only want to display the word cloud, not axes and their values.
plt.axis('off')
plt.title(title)
plt.show()
if __name__ == "__main__":
wc = myWordCloud("thailand.txt", "elephant.png", "elephantCloud.png")
plotting("Thailand")
import asyncio
from typing import Dict, Union
from countdoom import CountdoomClient
def get_doomsday_clock() -> Dict[str, Union[str, float, None]]:
"""
Get current Doomsday Clock value.
:return: Dictionary of Doomsday Clock representation styles
"""
client = CountdoomClient()
loop = asyncio.get_event_loop() # The event loop is the core of every asyncio application. asyncio.get_running_loop() returns the running event loop in the current OS thread.
task = loop.create_task(client.fetch_data()) # It schedules the execution of a coroutine and returns a Task object.
data = loop.run_until_complete(task) # It is used to run a future (an eventual result of an asynchronous operation) until it's finished. In other words, it will block the execution of code following it.
return data
def printCountDown(data): # Data is a dictionary of doomsday clock
for keys, values in data.items():
print(keys, ": ", values)
if __name__ == "__main__":
data = get_doomsday_clock()
printCountDown(data)
sentence : IT IS 100 SECONDS TO MIDNIGHT clock : 11:58:20 time : 23:58:20 minutes : 1.67 countdown : 100.0
user@pc:~$ python Python 3.9.5 (default, May 11 2021, 08:20:37) [GCC 10.3.0] on linux Type "help", "copyright", "credits" or "license" for more information.
>>> import antigravity
import speedtest, datetime
from rich import print
def checkSpeed():
mySpeedTest = speedtest.Speedtest() # It creates an instance of Speedtest.
print("Loading server list...")
myBestServer = mySpeedTest.get_best_server() # We need a server to send ping requests for a health check, and we obviously choose the best one.
mytime = datetime.datetime.now().strftime("%H:%M:%S")
print(f"Using server: {myBestServer['host']} located in {myBestServer['host']}")
print("Performing donwload test...")
download_results = mySpeedTest.download() # It uses the download method to fetch the download speed.
print("Performing upload test...")
upload_results = mySpeedTest.upload() # It uses the upload method to fetch the upload speed.
ping_results = mySpeedTest.results.ping
print(f"time: {mytime}")
A formatted string literal is a string literal that is prefixed with ‘f’. It could contain replacement fields, which are expressions delimited by curly braces {} evaluated at run time.
print(f"Download speed: [red]{download_results/(1e+6):.2f}[/red] Mbps")
Download_results are in bits/s. How many bps are in 1 Mbps? The answer is 1000000, that’s why we calculate download_results/(1e+6).
>>> value = 12.34567
>>> print(f"My value: {value:.2f}") My value: 12.35
This is our checkspeed() method’s last lines:
print(f"Upload speed: [red]{upload_results/(1024**2):.2f}[/red] Mbps")
print(f"Ping: [red]{ping_results:.2f}[/red] ms")
if __name__ == '__main__':
checkSpeed()
user@pc:~$ python Python 3.9.5 (default, May 11 2021, 08:20:37) [GCC 10.3.0] on linux Type "help", "copyright", "credits" or "license" for more information.
>>> import pywhatkit
>>> pywhatkit.text_to_handwriting("""You have to have a big vision and take very small steps to get there. You have to be humble as you execute but visionary and gigantic in terms of your aspiration. In the Internet industry, it's not about grand innovation, it's about a lot of little innovations: every day, every week, every month, making something a little bit better. Jason Calacanis""")
# **It converts text to handwritten characters**. The output is saved as an image file (pywhatkit.png) where the Python source file is located.
CODE = {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '‐‐.', 'H': '....', 'I': '..', 'J': '.‐‐-', 'K': '-.-', 'L': '.-..', 'M': '‐‐', 'N': '-.', 'O': '‐‐-', 'P': '.‐‐.', 'Q': '‐‐.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.‐‐', 'X': '-..-', 'Y': '-.‐‐', 'Z': '‐‐..', '0': '‐‐‐‐-', '1': '.‐‐‐‐', '2': '..‐‐-', '3': '...‐‐', '4': '....-', '5': '.....', '6': '-....', '7': '‐‐...', '8': '‐‐-..', '9': '‐‐‐‐.', ' ':'/ ', '.':'.-.-.-', ',':'‐‐..‐‐', ':':'‐‐-...', '?':'..‐‐..', "'":'.‐‐‐‐.', '-':'-....-', '/':'-..-.', '@': '.‐‐.-.', '=':'-...-', '(':'-.‐‐.', ')':'-.‐‐.-', '+':'.-.-.'}
""" Morse code translator. It encrypts the string "codigo" according to the morse code chart"""
def morse(codigo):
codigoMorse = ""
for char in codigo:
codigoMorse += " " + CODE[char.upper()]
return codigoMorse
if __name__ == "__main__":
print(morse("sos"))
print(morse("rats"))
… ‐‐- … # SOS (… ‐‐- …) is the worldwide distress call.
.-. .- - … # rats (.-. .- - …) is considered the first wireless hack.
import subprocess, platform
"""is hostname up or down?"""
def check_ping(hostname, n):
# We use platform.system() to check the OS of the machine and then run the command accordingly.
param = '-n' if platform.system().lower()=='windows' else '-c'
command = ['ping', param, n, hostname]
The command to ping a server is ping -c count hostname for Unix and ping -n count hostname for Windows, where count is the number of packets and hostname is the server address we want to check.
The subprocess.call(args) method runs the command described by args. It returns 0 if the command executes successfully.
if subprocess.call(command) == 0:
print("Network Active. " + hostname + " is available!")
else:
print("Network Error. " + hostname + " is down!")
if __name__ == "__main__":
check_ping("www.justtothepoint.com", '3')
Pinging justtothepoint.com [91.146.103.142] with 32 bytes of data:
Reply from 91.146.103.142: bytes=32 time=188ms TTL=48
Reply from 91.146.103.142: bytes=32 time=188ms TTL=48
Reply from 91.146.103.142: bytes=32 time=189ms TTL=48
Ping statistics for 91.146.103.142: Packets: Sent = 3, Received = 3, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds: Minimum = 188ms, Maximum = 189ms, Average = 188ms
Network Active. www.justtothepoint.com is available!