Python Basics
Introduction
Python, pronounced PY-thon (in Russian the name Piton is also common), is a high-level general-purpose programming language focused on
increasing developer productivity and code readability.
The syntax of the Python core is minimalist. At the same time the standard library
includes a large set of useful functions.
Python supports structural, object-oriented, functional,
imperative and aspect-oriented programming.
Its main architectural features are dynamic typing, automatic memory
management, full introspection, an exception handling mechanism, support for multithreaded
computations and high-level data structures.
Programs can be split into modules, which in turn can be combined into packages.
The reference implementation of Python is the CPython interpreter, which supports
most actively used platforms.
It is distributed under the free Python Software Foundation License,
which allows it to be used without restrictions in any applications, including proprietary ones.
There is an interpreter implementation for the JVM with compilation support, for CLR and LLVM,
and other independent implementations. The PyPy project uses JIT compilation, which
significantly increases the execution speed of Python programs.
Python is an actively developing programming language; new versions with
added/changed language features are released about every two and a half
years.
The language has not been officially standardized; the role of the
de facto standard is played by CPython, developed under the control of the language's author.
At the moment (April 2021)
Python ranks third in the TIOBE index with a rating of 11.03%.
Analysts note that this is the highest score Python has ever had during its presence in the
index.
You can view the current rating
here
Hello World!
Instructions for running your first Python program
Make sure Python is installed and the command
python -V
Shows the Python version, for example
Python 3.9.1
If you work in Linux, UNIX or Bash on Windows go to your home directory
In Linux
cd ~
In Windows
cd /mnt/c/Users/username
Create the python directory
mkdir python
Go into it, create the file hello_world.py and open it with any text editor
cd python
touch hello_world.py
vi hello_world.py
Insert the following code there
print("Hello World!")
Run
python hello_world.py
The message should appear in the terminal
Hello World!
You can find more details about running scripts in the next paragraph - «Running a Python script» and then in if __name__ == "__main__":
Running a script
To run a .py script, enter
python file_name.py
The result of such a run depends on what is specified after if __name__ == "__main__": if that condition is present at all
print("Hello!")
python sample.py
Hello!
Now the same thing, but in a function
def say_hello(): print("Hello!")
python sample.py
Nothing happened because nobody called the function
You can add a function call as follows
def say_hello(): print("Hello!") say_hello()
python sample.py
Hello!
In this case the function will always be called - both when the script is run from the terminal and when it is imported into another module you can configure this behavior using the variable __name__ or, more precisely, using the condition if __name__ == "__main__":
Indentation
Python is not a free-format language. Code blocks are not
separated with { }
Instead, blocks are separated by indentation according to the so-called off-side rule
Demonstration
Consider the file for_loop.py
for i in range(1,4):print(i)
python for_loop.py
1
2
3
Everything works fine. Note that only i from 1 to 3 was printed. Python did not print 4.
If you write the code not on one line, but as follows
for i in range(1,4):
print(i)
then the code will not work. You will get an error
File "/home/andrei/python/for_loop.py", line 2 print(i) ^ IndentationError: expected an indented block
So you need to put a space before print
for i in range(1,3):
print(i)
python for_loop.py
1
2
3
Instead of one space you can use a tab, but it is better to use two or four spaces in a row.
PEP8 - the document that collects recommendations for writing Python code says:
Use 4 spaces per indentation level
MOST IMPORTANT: You must not mix tab indentation and space indentation in one file. Choose one style and stick to it.
You can read about how to properly wrap overly long lines here
Arithmetic
/ - division. The result is a floating-point number
>>> 5 / 2
2.5
// - integer division. The result is the quotient rounded down to an integer.
>>> 5 // 2
2
% - the remainder of division. The result is the remainder of //
>>> 5 % 2
1
Greater than or equal to >=
Printing HTML special characters
A script with which you can print a certain number of HTML special characters
for i in range(100001,125000):
print "<tr><td>&#",i,";</td><td>&#",i,";</td></tr>"
Links
Psyco
Shedskin
PyPy
Cython
Jython
IronPython
IDLE
Syntax
A set in curly braces. An element is added with .add()
if __name__ == '__main__'
To understand the meaning of this line, let's create two files.
first_module.py
and
second_module.py
In the first one we write
print(f"Name of the first module: {__name__}")
# If you do not like f-string, write:
print("Name of the first module: {}".format(__name__))
Let's run it
python3 first_module.py
Name of the first module: __main__
In the second one we write
import first_module
Let's run it
python3 second_module.py
Name of the first module: __first_module__
Conclusion: when a module is run directly, its __name__ is __main__
When a module is imported into another module, its __name__ is __py_file_name__
Now that everything is clear, we can add the condition to our code if __name__ == "__main__"
def say_hello(): print("Hello!") def display_name(): print(f"Name of the first module: {__name__}") if __name__ == "__main__": say_hello()
Hello!
Or
def say_hello(): print("Hello!") def display_name(): print(f"Name of the first module: {__name__}") if __name__ == "__main__": display_name()
Name of the first module: __main__
The point is that now we define what will be executed when this script is called and what will not.
Python packages in Linux
Find out how many python3 packages there are in the repository of Ubuntu
apt-cache search python3 | wc -l
3472
You can browse their names with less
apt-cache search python3 | less
alembic - lightweight database migration tool for SQLAlchemy
brltty - Access software for a blind person using a braille display
debian-goodies - Small toolbox-style utilities for Debian systems
devscripts - scripts to make the life of a Debian Package maintainer easier
libcrack2-dev - pro-active password checker library - development files
…
Check whether the file exists hosts
#!/usr/bin/python3
import os.path
if os.path.exists("/etc/hosts"):
print("hosts file exists")
else:
print("no hosts file")
or
#!/usr/bin/python3
try:
f = open('/etc/hosts')
print("hosts file exists")
except FileNotFoundError:
print("no hosts file")
python3 check_hosts.py
hosts file exists
Shebang
Points to the required interpreter. Examples:
#!/usr/bin/env python
#!/home/andrei/.pyenv/shims/python
After writing the shebang, you need to make the script an executable file
chmod + x script_name.py
And now it can be run directly from the terminal
./script_name.py
Or
.\script_name.py
If you use
PowerShell
In
Windows
running Python scripts is helped by Pylauncher
(see
PEP 397
)
Scopes
Local - inside a function
Enclosing - inside the function that called the function
Global - throughout the module
Built-in - built into Python
LEGB
References to Local are destroyed after the function finishes
Consider the function fetch_words()
from the article about
docstring
url, story, story_words, line, line_words, word are local variables
def fetch_words(url): """Fetch a list of words from a URL. Args: url: The URL of a UTF-8 text document. Returns: A list of strings containing the words from the document """ # PEP 257 # story = urlopen("http://sixty-north.com/c/t.txt") story = urlopen(url) story_words = [] for line in story: line_words = line.decode("utf8").split() for word in line_words: story_words.append(word) story.close() return story_words def print_items(story_words): """Print items one per line. Args: An iterable series of printable items. """ for word in story_words: print(word) def main(url): words = fetch_words(url) print_items(words) if __name__ == "__main__": main(sys.argv[1])
Let's examine the behavior of global variables
count = 0 def show_count(): print(count) def set_count(c): count = c show_count() # 0 set_count(5) show_count() # 0
0 0
You can change the behavior of the function with global
count = 0 def show_count(): print(count) def set_count(c): global count count = c show_count() # 0 set_count(5) # Now affects global variable show_count() # 5
0 5
Useful links
codingbat.com
projecteuler.net
codeabbey
reddit
pythonchallenge
Encoding declaration
uuid
An example of creating a string from a uuid
import uuid def str_uuid(): return str(uuid.uuid4()) print("name" + str_uuid()) print("name" + str_uuid()) print("name" + str_uuid()) print("name" + str_uuid()) print("name" + str_uuid())
name8873e1d2-b3c2-497a-952d-89bd3a658edc name4168f752-c676-4740-a12a-b7f7cd07fd2d namebf2e4954-644d-4c6e-be41-de9c3c2809b8 named53dbef3-b798-4af4-a3be-61ad349eac30 name79765d36-cb5c-4514-b6c7-3f9c5779e44a
About uuidgen you can read here
Article author: Andrei Olegovich