PYTHON BASICS



Skip to a subsection :

  1. IDE, REPL
  2. PRINT
  3. GETTING HELP
  4. OPERATORS
  5. FUNCTIONS
  6. RANGE
  7. ENUMERATE
  8. BACKSLASH CHARACTER
  9. UNPACKING
  10. ZIP
  11. MATCH
  12. ANY
  13. CLONING AND ALIASING
  14. OBJECT ORIENTED PROGRAMMING


IDE, REPL

IDE : Integrated Development Environment . IDEs are programs that provide a convenient interface for writing and testing code. Some popular IDEs for Python include PyCharm, IDLE, and Spyder.

REPL : Read Eval Print Loop. It is a simple environment for executing commands one at a time. They are often used for testing code snippets, debugging, and prototyping. It's a way to interact with the programming language on the command line or in a terminal window, without the need to create a separate file. When you use a REPL, you type in individual lines of code one at a time, and the computer reads, evaluates, and prints the results of each line as you enter it.

In IDLE, the Python REPL is called the "Python Shell". In Spyder, the Python REPL is called the "IPython Console"

On the other hand, a script is a file containing a series of commands or instructions. It's saved as a file with a specific file extension (e.g. .py for Python), and it can be executed by the computer's operating system. When you run a script, the computer reads and executes the instructions in the file. A script is a file containing a series of commands that can be executed all at once


PRINT

print is used to display output to the console or terminal. It is commonly used to display text, variables, and other data types.

x=10
print(x) # prints 10    
x=10
y=1
print(x+y) # prints 11
x='hello world'
print(x) # prints hello world
x='world'
print('hello',x) # prints hello world

The sep parameter in the print() function is used to specify the separator between the arguments passed to the function.

"\n" is not specific to the print() function , it's a special character used to represent a newline

print('a','b','c') # prints a b c
print('a', 'b', 'c', sep='') # prints abc
print('a', 'b', 'c', sep='-') # prints a-b-c
print('a', 'b', 'c', sep="\n") # prints : a b and c on separate lines
print('a', '\n', 'b') # prints a and b on separate lines, with a space before b
print('a', '\nb') # prints a and b on separate lines, without a space before b
print('a', end=''), print('b') # prints ab on the same line
print('\n') # prints a blank line
print('a','\t','b') # prints a        b
print() # new line

Print a mutliplication table in the terminal :

def table():
    for i in range(1,10):
        for j in range(1,10):
           print(i * j,'\t',end='')
        print()
table()

GETTING HELP

There are methods to obtain assistance or information when working in the Python console

print(dir(mylist))
print(help(mylist))
print(myfunction.__doc__)
import numpy as np
print(dir(np))
print(np.__doc__)

OPERATORS

Operators are special symbols that are used to perform specific operations on one or more values or variables. Here are the main types of operators in Python: In Python, operators are special symbols that are used to perform specific operations on one or more values or variables. Here are the main types of operators in Python:

Arithmetic Operators

These operators are used to perform arithmetic operations like addition, subtraction, multiplication, division, and modulus.

Comparison Operators:

These operators are used to compare two values and return a Boolean (True or False) value based on the comparison.

Logical Operators:

These operators are used to perform logical operations like AND, OR, and NOT.

Assignment Operators:

These operators are used to assign values to variables.

Membership Operators:

These operators are used to test if a value or variable is a member of a sequence.

Identity Operators:

These operators are used to test if two objects are the same object.

* asterisk operator:

When used as an asterisk operator, it is used to unpack the values of an iterable, such as a list or tuple, and assign them to separate variables. Please read 'unpacking' section to know more.


FUNCTIONS

Definitions

A function is a block of reusable code that performs a specific task. Functions are defined using the def keyword, followed by the function name, and a set of parentheses. The parentheses may include one or more parameters (or arguments) that the function can accept. The function body is indented and contains the statements that make up the function

User-defined Functions

Functions are a powerful tool for organizing code and making it more modular and reusable. Here are a few exemples of user-defined functions

#1. takes two numbers and returns their sum
def add_numbers(a, b):
    sum = a + b
    return sum

add_numbers(3, 4) # returns 7

#2. takes two numbers as arguments but doens't return any value, perfoms an action : prints their sum
def add_numbers(a, b):
    sum = a + b
    print(sum)

add_numbers(3, 4) # returns 7

#3. doesn't takes any argument, doesn't return any value, prints 'hello' 
def printsomething():
    print('hello')

printsomething() #returns ('hello')

Functions that return a value are used when we need to perform some computation and use the output in other parts of the program. These functions take some input, perform some operations on that input, and return a value as a result. The returned value can be used in calculations, as input to other functions, or in conditional statements

Functions that perform an action without returning a value, like the print() function, are typically used when we want to produce some output or modify some external state, but we don't need to use the output in other parts of the program


Default argument

A default argument is a value that a function uses if the user doesn't provide a value for that argument when calling the function. You can specify default arguments in Python by assigning a value to the argument in the function definition :

def multiply(x, y = 2): # default argument is y = 2
    product = x * y
    print(product)
multiply(5,3) # prints 15, default argument y=2 was not used
multiply(5) # prints 10, default argument y=2 was used

Labels

A function with labels is a function that takes arguments in the form of key-value pairs, where the keys are the labels and the values are the actual arguments. This is also known as keyword arguments.

def difference(number1,number2):
diff = number1 - number2
print(diff)

difference(number1 = 5, number2 = 4) # prints 1
difference(number2 = 5,number1 = 4) # prints -1
difference(5, 4) # prints 1
difference(4, 5) # prints -1

Typed function

A function where the type of argument is defined is called a typed function or a function with type annotations. Type annotations are used to specify the expected type of the arguments and the return value of a function. This can help with readability, maintainability, and catching errors in your code.

def add(a: int, b: int)->int:
    print(a + b)

It's possible to combine labels, argument type and default argument in the same function definition.

def add(a: int=2, b: int=3)->int:
    print(a + b)

add() # prints 5
add(1, 1) # prints 2

Unlimited number of arguments

the * (asterisk) operator is used to indicate that a function should take an arbitrary number of arguments. When used in a function definition, *args (pronounced "star-args") is a special syntax that allows the function to accept any number of positional arguments

def add(*args):
    result = 0
    for arg in args:
        result += arg
    print(result)

add(2, 2) # prints 4 
add(2, 1, 4, 1) # prints 8

Decorators

A decorator is a higher-order function that accepts a function as an input and returns a new function that extends or modifies the behavior of the original function. In mathematics, you can take two functions f(x) and g(x) and compose them into a new function (f ∘ g)(x), where the output of g(x) is used as the input for f(x). This allows you to build complex functions out of simpler ones by chaining them together. Decorators work in a similar way. You can take a function f and a decorator d and compose them into a new function d(f), where the output of f is modified or extended by the functionality provided by d. Just like with function composition, you can chain multiple decorators together to build up more complex functionality.

def timer(func):
import time
def wrapper(n):
    start_time = time.time()
    result = func(n)
    end_time = time.time()
    print(f"Elapsed time: {end_time - start_time} seconds")
    return result
return wrapper

@timer
def fibonacci(p):
    if p in (0,1):       
        return 1
    else:     
        return fibonacci(p - 1) + fibonacci(p - 2)
        
print(fibonacci(15))



RANGE

range() generates a sequence of numbers. It takes 3 arguments, the start, stop and step values. The start value is the first number in the sequence, the stop value is the last number in the sequence (not inclusive), and the step value is the difference between each number in the sequence. The syntax is range(start, stop, step). The start limit is inclusive, which means it is included in the range. The stop limit is exclusive, which means it is not included in the range.

for i in range(2,7,1):
    print(i)
# prints: 
# 2
# 3
# 4

ENUMERATE

enumerate() allows you to iterate over a sequence (like a list or a string) while also keeping track of the index of each item in the sequence. The first variable represents the index and the second variable represents the value of each item in the list as you loop through it.

mylist=[10, 9, 17, 0]
for index, value in enumerate(mylist):
    print('index:', index,', value:', value)
# prints : 
index: 0 , value: 10
index: 1 , value: 9
index: 2 , value: 17
index: 3 , value: 0

You can replace these variable names with any descriptive names that make sense for your use case.

By default, 'enumerate' begins with an index of 0, but with the 'start' parameter, you have the option to initiate it with a different value.

mylist=[10, 9, 17, 0]
for index,value in enumerate(mylist, start = 1):
    print('index:',index,', value:', value)
# prints : 
index: 1 , value: 10
index: 2 , value: 9
index: 3 , value: 17
index: 4 , value: 0

BACKSLASH CHARACTER

The backslash character is used as an escape character to indicate special characters, such as newline (\n) or tab (\t). For example, the string literal 'hello\nworld' represents the string "hello" followed by a newline character and then "world".

In Windows file paths, backslashes are used as path separators, so using regular string literals with backslashes in file paths can lead to errors or unexpected behavior. The r before the path name is called a "raw string" literal in Python. It's a way to define a string literal in which backslashes (\) are treated as regular characters, rather than as escape characters. Another way to represent path names is to use double backslashes


UNPACKING

The values of an iterable, such as a list or tuple, can be unpacked with the * operator

mylist=[10,9,17,0]
print(mylist) # prints [10, 9, 17, 0]
print(*mylist) # prints 10 9 17 0

ZIP

The zip() function takes two or more iterables (such as lists, tuples, or strings) and returns an iterator that aggregates elements from each of the iterables into tuples. When you try to display the elements of the zipped iterator without using list(), Python will return a reference to the iterator object itself, rather than the contents of the iterator. To actually retrieve the tuples from the zipped iterator, you need to convert it to a list using the list() function.

x=[1,2,3]
y=[4,5,6]
z=[7,8,9]
p=list(zip(x,y,z))
print(p) # prints [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

zip stops pairing elements when it reaches the end of the shorter list :

colors=['blue','red','yellow']
images = ['image1','image3']
for color, image in zip(colors,images):
  print(color, image)
# prints :
blue image1
red image3

MATCH

match is a feature introduced in Python 3.10. It allows you to match a value against multiple patterns and execute corresponding code blocks based on the matched pattern

def check_fruits(fruit):
    match fruit:
        case 'apple':
            print("it's a fruit")
        case 'yellow':
            print("it's a color")
        case '@ù++&':
            print("it's unkown")

check_fruits('yellow') # prints : it's a color

ANY

any() returns `True` if at least one element in a sequence (such as a list) evaluates to `True`context; otherwise, it returns `False`.

my_list = [True, False, False, True, False]
result = any(bool_list)
print(result)  # prints True 

my_list = [0, 0, 0, 1, 0]
result = any(int_list)
print(result)  # prints True

my_list = [2, 4, 6, -3, 8]
result = any(x < 0 for x in num_list) # prints True

CLONING AND ALIASING

In the context of object-oriented programming :

Lists can be easily cloned using slicing [:], which is illustrated in this example

mylist1 = [1,2,4]
# ALIASING : 
mylist2 = mylist1
print(mylist1 == mylist2) # prints True
print(mylist1 is mylist2) # prints True

# CLONING : 
mylist3 = mylist1[:]
print(mylist1 == mylist3) # prints True
print(mylist1 is mylist3) # prints False

OBJECT ORIENTED PROGRAMMING

To explain Object-Oriented Programming (OOP), it's essential to share a substantial amount of information. This doesn't necessarily mean it's complicated. In fact, it often makes code more readable and maintainable. In order to have some examples, please refer to the dedicated page : object oriented programming