Basic Python for Everyone
Python is a versatile language that supports web development, data science, AI, and scripting. Its readable and simple, English-like syntax, makes it ideal for fast development. Created by Guido van Rossum in 1991, it reduces maintenance costs and allows developers to write programs with fewer lines.
Language Introduction
Python is a high level, dynamic, interpreted (bytecode-compiled) language. Unlike Java or C++ which are compiled languages, there is no lengthy compilation or build step in Python. Therefore, developers can write and run code immediately and therefore the development cycle is fast. Interpreters typically execute code line-by-line and can report errors the moment they are encountered.
There are no type declarations of variables, parameters, functions, or methods in source code. This makes the code short and flexible, and you lose the compile-time type checking of the source code. Python tracks the types of all values at runtime and flags code that does not make sense as it runs.
Also, programs written in interpreted languages are generally more portable. The source code can run on any system that has a compatible interpreter installed, regardless of the underlying hardware or operating system architecture.
Python source code
Python source files use the ".py" extension and are called "modules."
With a Python module hello.py, the easiest way to run it is with the shell command "python hello.py Alice" which calls the Python interpreter to execute the code in hello.py, passing it the command line argument "Alice".
Here's a very simple hello.py program:
#!/usr/bin/python3
# import modules used here -- sys is a very standard one
import sys
# Gather our code in a main() function
def main():
print('Hello there', sys.argv[1])
# Command line args are in sys.argv[1], sys.argv[2] ...
# sys.argv[0] is the script name itself and can be ignored
# Standard boilerplate to call the main() function to begin
# the program.
if __name__ == '__main__':
main()
Running this program from the command line looks like:
$ python3 hello.py Guido
Hello there Guido
$ ./hello.py Alice ## without needing 'python3' first (Unix)
Hello there Alice
Key Concepts/ Parts of Python Program
Module: A single Python file (e.g., mymodule.py) that can include functions, classes, and variables. When you execute a python module like python3 hello.py Bob, hello.py is the module. A module is a file containing Python definitions and statements (typically ending in .py) that allows you to organize and reuse code across different programs.
When a Python file is run directly, the special variable "__name__" is set to "__main__". Therefore, it's common to have the boilerplate if __name__ ==... shown above to call a main() function when the module is run directly, but not when the module is imported by some other module.
Imports - In a python program, you generally import some other modules and then it itself becomes a module. An obvious module import is that of sys. A Python module can be run directly — as above hello.py — or it can be imported as import hello and used by some other module.
Arguments - When you execute a python program like, python3 hello.py Bob, Bob is an argument. You are passing user variables into the program. A program may accept zero, one or more arguments as per its design.
Recommended by LinkedIn
In a standard Python program, the list sys.argv contains the command-line arguments in the standard way with sys.argv[0] being the program itself, sys.argv[1] the first argument, and so on. If you know about argv, or the number of arguments, you can simply request this value from Python with len(sys.argv).
An excellent way to see how Python code works is to run the Python interpreter and type code right into it.
$ python3 ## Run the Python interpreter
Python 3.X.X (XXX, XXX XX XXXX, XX:XX:XX) [XXX] on XXX
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 6 ## set a variable in this interpreter session
>>> a ## entering an expression prints its value
6
>>> a + 2
8
>>> a = 'hi' ## 'a' can hold a string just as well
>>> a
'hi'
>>> len(a) ## call the len() function on a string
2
>>> a + len(a) ## try something that doesn't work
Traceback (most recent call last):
File "", line 1, in
TypeError: can only concatenate str (not "int") to str
>>> a + str(len(a)) ## probably what you really wanted
'hi2'
>>> foo ## try something else that doesn't work
Traceback (most recent call last):
File "", line 1, in
NameError: name 'foo' is not defined
>>> ^D ## type CTRL-d to exit (CTRL-z in Windows/DOS terminal)
len(): In general, len() can tell you how long a string is, the number of elements in lists and tuples (another array-like data structure), and the number of key-value pairs in a dictionary.
Standard Library: A collection of over 200 built-in modules (like math, os, and random) that come pre-installed with Python
User Defined Function
A function is a reusable block of code that performs a specific task and runs only when called. You define them using the def keyword
# Defines a "repeat" function that takes 2 arguments.
def repeat(s, exclaim):
"""
Returns the string 's' repeated 3 times.
If exclaim is true, add exclamation marks.
"""
result = s + s + s # can also use "s * 3" which is faster (Why?)
if exclaim:
result = result + '!!!'
return result
Variables
In Python, variables are symbolic names that act as references to objects stored in memory
# GLOBAL VARIABLE: Declared outside any function
message = "I am global"
def my_function():
# LOCAL VARIABLE: Declared inside a function
local_msg = "I am local"
print(f"Inside function: {message}") # Accesses global variable
print(f"Inside function: {local_msg}") # Accesses local variable
my_function()
print(f"Outside function: {message}") # Works
# print(local_msg) # This would cause a NameError because local_msg is not defined here
Class
A class acts as a "blueprint" or template for creating objects. It bundles data (variables) and behaviors (functions) together. In a class, variables are often called "attributes," and functions are called "methods"
class Dog:
# Class variable (shared by all instances)
species = "Canine"
def __init__(self, name, age):
# Instance variables (unique to each object)
self.name = name
self.age = age
# Method (function inside a class)
def bark(self):
return f"{self.name} says Woof!"
# Creating an instance (object) of the class
my_dog = Dog("Buddy", 3)
print(my_dog.bark())