img.png

Python is a high-level, general-purpose programming language.

What i’m using.

Intellij (Idea) + Python 3

versus

A terminal or command line:

$ python
Python 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("hello")
hello
>>>

Virtual env (environment)

$ python -m venv ./venv
$ ls -la
drwxrwxr-x  5 4096 Apr 25 18:27 venv
source ./venv/bin/activate
(venv) $
print("Hello World!")
print("Hello Again")
print("I like typing this.")
print("This is fun.")
print('Yay! Printing.')
print("I'd much rather you 'not'.")
print('I "said" do not touch this.')

Operators

+ plus
- minus
/ slash
* asterisk
% percent
< less-than
> greater-than
<= less-than-equal
>= greater-than-equal

print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)

print(“Is it greater?”, 5 > -2)

>>> print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
6.75
>>> print("Is it greater?", 5 > -2)
Is it greater? True
>>>

Comments

Variables

Python uses underscores _ (space) for “making_sense_from_variables”

>>> cars = 100
>>> people_in_each_car = 4
>>>
>>> print("There are", cars, "cars available.")
There are 100 cars available.
>>>
>>> my_eyes = 'Blue'
>>> print(f"{my_eyes}")

Command line arguments

from sys import argv

script, first, second, third = argv

print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)

Files

filename = "test.txt"
target = open(filename, 'w')
line1 = input("line 1: ")
target.write(line1)
target.close()

Loops

fruits = ["apple", "banana", "cherry"]
for x in fruits:
    if x == "banana":
      print("it's a banana")

    print(x)

A simple class

class SimpleClass:
    def __init__(self, x=5, y=10):
        self.x = x
        self.y = y

    def __str__(self):
        return f"{self.x} {self.y}"

    def add_x_and_y(self):
        return self.x + self.y


default_class = SimpleClass()
simple_class = SimpleClass(1, 2)

print(default_class)
print(simple_class)
print(simple_class.add_x_and_y())

Python web server

# Python 3 server example
from http.server import BaseHTTPRequestHandler, HTTPServer
import time

hostName = "localhost"
serverPort = 8080

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(bytes("<html><head><title>Stone Code and Infrastructure</title></head>", "utf-8"))
        self.wfile.write(bytes("<p>Request: %s</p>" % self.path, "utf-8"))
        self.wfile.write(bytes("<body>", "utf-8"))
        self.wfile.write(bytes("<p>This is an example web server.</p>", "utf-8"))
        self.wfile.write(bytes("</body></html>", "utf-8"))

if __name__ == "__main__":
    webServer = HTTPServer((hostName, serverPort), MyServer)
    print("Server started http://%s:%s" % (hostName, serverPort))

    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        pass

    webServer.server_close()
    print("Server stopped.")

What is the “top-level code environment”?

__main__ is the name of the environment where top-level code is run.

“Top-level code” is the first user-specified Python module that starts running. It’s “top-level” because it imports all other modules that the program needs.

Sometimes “top-level code” is called an entry point to the application. It’s not the same as Java main() - as this is Class specific.

An example:

class SimpleClass:
    def __init__(self, x=5, y=10):
        self.x = x
        self.y = y

    def __str__(self):
        return f"{self.x} {self.y}"

    def add_x_and_y(self):
        return self.x + self.y
# end of class

def __main__():
    print("main")


if __name__ == '__main__':
    __main__()

simple_class = SimpleClass(1, 2)

print(simple_class)

When you run this (main is the first thing printed - name == ‘main’):

$ python hello-world.py
main
1 2

When you run python from the command line. The top level Python name is main:

$ python
Python 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print(__name__)
__main__
>>>

More detail on __main__

pep8 - style guide for Python

https://peps.python.org/pep-0008/