jupyter | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
To focus on the language itself this guide not includes any built-in modules like math, random, datetime, json, re, random, etc
The Zen of Python is a collection of 19 guiding principles for writing computer programs that influence the design of the Python programming language.
import this
Make a simple hello world
print('Hello, World!')
Help
help(print)
Comments
#This is a comment
#Variables
name = 'John'
age = 42
x, y, z = 1, 2, 3
print('Name: ' + name)
# User input
# favorite_comedy_series = input('Enter your favorite comedy series: \n')
# print(favorite_comedy_series)
# output: Monty Python's Flying Circus
Python has the following data types built-in by default
my_number = 42
print(type(my_number))
# Text
my_string = 'Hello World'
# Numeric
my_integer_number = 20
my_float_number = 20.5
my_complex_number = 1j
# Sequence
my_list = ['apple', 'banana', 'cherry']
my_tuple = ('apple', 'banana', 'cherry') # immutable sequence
my_other_tuple = tuple(('apple', 'banana', 'cherry')) # immutable sequence
my_range = range(4) # range(0, 4)
# Mapping
my_dictionary = {'name' : 'John', 'age' : 36}
my_other_dictionary = dict(name='John', age=36)
# Set - No duplicate members
my_set_value = {"apple", "banana", "cherry"}
my_other_set_value = set({"apple", "banana", "cherry"})
my_frozenset_value = frozenset({"apple", "banana", "cherry"})
# Boolean
my_boolean = True # Can be True of False
bool(0) # Return a Boolean value
# Binary
my_bytes = b"Hello"
my_bytearray = bytearray(5) # bytearray(b'\x00\x00\x00\x00\x00')
my_memoryview = memoryview(bytes(5)) # <memory at 0x01368FA0>
# Convert an integer number to a binary
print(bin(2))
# Convert an integer number to an octal
print(oct(8))
print(type(string))
print(int('1'))
print(float(1))
# Convert an integer number to a lowercase hexadecimal string prefixed with '0x'
print(hex(255))
# Represents a null value
x = None
print(x) # None
A string is a sequence of Unicode characters
hello = 'Hello, World! '
print(hello[0])
print(hello[-2])
print(hello[2:5])
print(len(hello)) # returns the size of hello
print(hello.strip()) # removes whitespaces
print(hello.lower())
print(hello.upper())
print(hello.replace("H", "A"))
print(hello.split(","))
# Membership Operators
print("Hello" in hello)
print("Hello" not in hello)
print('Hello, ' + 'World!')
print('Hello, ' 'World!')
print("{0}, World!".format('Hello'))
print('Hello, \n World!')
print(chr(97)) # Return the string representing a character
print(ord('a')) # Return an integer representing the Unicode
# print('Number is: ' + 1)
# TypeError: must be str, not int
# 'str()' return a string version of object
print('Number is: ' + str(1))
The arithmetic operators are used to perform math operations, such as addition, subtraction, multiplication, and division.
x, y = 1, 2
print(x + y) # Addition
print(x - y) # Subtraction
print(x * y) # Multiplication
print(x / y) # Division
print((50 - 5*6) / 4) # 5.0
print(x % y) # Modulus
print(x ** y) # Exponentiation
print(x // y) # Floor division
x += 3 # Same as x = x + 3
These operators compare the values on either sides of them and decide the relation among them
x, y = 1, 2
print(x == y) # Equal
print(x != y) # Not equal
print(x > y) # Greater than
print(x < y) # Less than
print(x >= y) # Greater than or equal to
print(x <= y) # Less than or equal to
if x > y:
print("x is greater than y")
else:
print("x is not greater than y")
# Assert is used when debugging code
assert x == 1 # AssertionError is not raised
x = 2
print(x == 2 and x > 42)
print(x == 2 or x > 42)
print(not(True))
print(not(False))
Python has a set of built-in math functions
min_value = min(5, 10, 25) # lowest value
max_value = max(5, 10, 25) # highest value
print(min_value)
print(max_value)
print(abs(-7.25)) # returns the absolute (positive) value
print(pow(4, 3)) # returns the '4' to the power of '3'
# Takes two numbers and returns a pair of numbers (a tuple)
# consisting of their quotient and remainder
divmod(2, 2) # same as (2 // b, x % y)
# Return number rounded to ndigits precision after the decimal point
print(round(0.5))
print(round(1.5))
Identity operators are used to compare the objects
x = 'Hello'
z = x
print(x is z)
print(x is not z)
y = 'World'
print(x is y)
print(x == y)
List is used to group together other values.
Built-in methods for lists
mylist = ['hello', 'world']
print(mylist)
print(f'{mylist[0]} - {mylist[-1]} - {mylist[0:1]} - {mylist[:1]} - {mylist[0:]}')
print(mylist[-1])
print(mylist[0:1])
print(mylist[:1])
print(mylist[0:])
mylist[1] = "!"
print(mylist)
for item in mylist:
print(item)
if "hello" in mylist:
print("Yes, 'hello' is in the mylist")
print(len(mylist))
mylist.append("world") # Add an item to the end of the list
print(mylist)
mylist.clear() # Removes all the elements
print(mylist)
mylist = ['hello', 'world']
my_other_list = mylist.copy() # Returns a copy of the list
my_other_list.count('hello') # Return the number of times the value "hello" appears
mylist.extend(['apple']) # Extend the list by appending all the items from the iterable
print(mylist)
mylist.index('world')
mylist.insert(1, "cucumber") # Adds an element at the specified position
print(mylist)
mylist.pop() # Removes the last item from the list
print(mylist)
mylist.remove("cucumber") # Remove the item at the given position in the list, and return it
print(mylist)
my_number_list = [ 1, 2, 3]
my_number_list.reverse()
print(my_number_list)
print(reversed(my_number_list))
my_number_list.sort()
print(my_number_list)
del my_number_list[0]
print(my_number_list)
all(my_number_list) # Return True if all elements of the iterable are true
print(any(my_number_list)) # If the iterable is empty, return False
my_number_list.clear()
print(any(my_number_list))
letters = [ 'a', 'b', 'c' ]
numbers = [ 1, 2, 3 ]
print(letters + numbers)
mylist = list(("apple", "banana", "cherry"))
print(mylist)
my_other_list = [ 'a', 'b', 'c', 'd', 'e' ]
start = 0 # position to start the slicing
end = 5 # position to end the slicing
spet = 2 # step of the slicing
slice_obj = slice(start, end, spet)
my_other_list[slice_obj]
# Return a new sorted list from the items in iterable
my_sorted_list = sorted([5, 4, 3, 2, 1])
print(my_sorted_list)
my_reversed_list = reversed(my_sorted_list)
print(list(my_reversed_list))
map and filter functions
# The filter function tests every element in an iterable object
# with a function that returns either True or False, only keeping
# those which evaluates to True
my_iterable = [ 1, 2, 3, 4, 5 ]
def bigger_than_three(number):
return number > 3
output_list = filter(bigger_than_three, my_iterable)
print(list(output_list))
# The map function allows us to apply a function to every element
# in an iterable object
my_iterable = [ 1, 2, 3, 4, 5 ]
def add_one(number):
return number + 1
output_list = map(add_one, my_iterable)
print(list(output_list))
List comprehensions are a way of making lists
numbers = [number for number in range(5)]
print(numbers)
squares = [number * number for number in range(5)]
print(squares)
def square(number):
return number * number
squares = [square(number) for number in range(5)]
print(squares)
numbers = list(range(10))
even_numbers = [number for number in numbers if number % 2 == 0]
print(numbers)
print(even_numbers)
Unordered collections of unique elements
my_set = {'python', 'is', 'awesome'}
print(my_set)
len(my_set) # Return the number of elements in set
for item in my_set:
print(item)
print('python' in my_set) # Check if 'python' is present in the set
print('python' not in my_set) # Check if 'python' is not present in the set
my_set.add('🐍')
print(my_set)
my_set.update(['and', 'very', 'nice'])
print(my_set)
my_set.remove('🐍')
# If the item to remove does not exists, discart will not raise an error
my_set.discard('python')
print(my_set)
my_set.pop() # Remove and return an arbitrary element from the set
my_set.clear() # Remove all elements from the set
A dictionary is a collection which is unordered, changeable and indexed.
my_dict = {
'name': 'Python',
'designed_by': 'Guido van Rossum',
'first_released': 1991
}
print(my_dict)
print(my_dict['name'])
my_dict['first_released'] = 2077
print(my_dict)
for value in my_dict.values():
print(value)
for key, value in my_dict.items():
print(key, value)
if 'name' in my_dict:
print('The key "name" exists in my_dict')
my_dict['website'] = 'www.python.org' # Add a new item
print(my_dict)
my_dict.pop('website')
print(my_dict)
my_dict.popitem()
print(my_dict)
x, y = 1, 2
if x > y:
print('x is greater than y')
elif x == y:
print('x and y are equal')
else:
print('x is greater than y')
# Short Hand
if x > y: print('x is greater than y')
print('x') if x > y else print('y')
'for' is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object
quote = ['Python', 'is', 'awesome']
for word in quote:
print(word)
for number in range(4):
print(number, end=' ')
for index, value in enumerate(quote):
print(index, value)
# Function continues execution immediately
# after the last yield run
def number_generator():
yield 1
yield 2
for number in number_generator():
print(number)
'while' is used for repeated execution as long as an expression is true
counter = 0
while counter < 4:
print(counter, end=' ')
counter += 1
A function is a block of code which only runs when it is called.
def my_function():
print("Hello, World from a function")
my_function() # Call a function
# A function to add two numbers
def sum(number):
return number + number
print(sum(2))
def my_function(programming_language):
print(programming_language + ' is awesome!')
my_function('Python') # Pass parameters
def my_function(*parameters):
print("The third parameter is: " + parameters[2])
my_function('Python', 'is', 'easy', 'to', 'learn')
def my_function(name, surname):
print(name, surname)
my_function(surname='van Rossum', name='Guido')
def my_function(programming_language="Python"): # Default parameter value
print(programming_language + ' is awesome!')
my_function("Ruby")
my_function()
# True if the object argument appears callable
callable(my_function) # True
Is a small anonymous function
# lambda arguments : expression
my_function = lambda x : x
print(my_function(2))
# is equivalent to
def my_function(x):
return x
sum = lambda x, y : x + y # Two parameters
print(sum(2, 2))
def call_any_function(func):
print(func(2, 2))
call_any_function(sum) # Pass the 'sum' lambda function as parameter
A class is a blueprint for an object, and an object is simply a collection of variables and functions that act on those variables.
class Person:
def __init__(self, name, age):
# Instance attribute’s
self.name = name
self.age = age
def show_name(self):
print("My name is " + self.name)
king_arthur = Person('Arthur', 26)
print(king_arthur)
# King Arthur is a Person object at the memory address 0x7fb265f652b0
king_arthur.show_name()
king_arthur.age = 27 # Modify object properties
# Use inheritance to create child classes from a parent class
class Knight(Person):
def speak(self):
print('Ni!')
# Now the Knight class has the same properties
# and methods as the Person class plus the 'speak()' method
lancelot = Knight('Lancelot', 25)
lancelot.show_name()
lancelot.speak()
vars(lancelot)
# Return the 'identity' of an object
id(lancelot)
# Determine which class a given object belongs to
type(lancelot)
print(isinstance(lancelot, Knight))
print(isinstance(king_arthur, Knight))
print(issubclass(Knight, Person))
Inheritance allows us to define a class that inherits all the methods and properties from another class.
# Base class: Person
# Derived class: Peasant
class Peasant(Person):
# Class attributes are attributes that have the
# same value for all class instances.
political_position = "We're an anarcho-syndicalist commune."
# Friendlier output for print()
def __str__(self):
return f"{self.name} is {self.age} years old"
# You can access the parent class from
# inside a method of a child class by using super()
def show_name_using_super_method(self):
super().show_name()
# Static method it's not bound to instance or class and you
# can simply call that using class name
@staticmethod
def talk_about_politics():
print(Peasant.political_position)
# A class method receives the class as implicit first argument
@classmethod
def show_class(cls):
print(cls)
dennis = Peasant('Dennis', 37)
print(dennis)
dennis.show_name_using_super_method()
dennis.talk_about_politics() # Static method
Peasant.show_class() # class method
getattr(dennis, 'name')
print(dennis.name)
# The function assigns the value to the attribute
setattr(dennis, 'name', 'Other Name') # same as dennis.name = 'Other Name'
print(dennis.name)
print(hasattr(dennis, 'name'))
print(hasattr(dennis, 'email'))
# Return the hash value of the object (if it has one)
print(hash(dennis))
# They are used to quickly compare dictionary keys during a dictionary lookup
print(hash(dennis) == hash(dennis))
# Return a string containing a printable representation of an object
print(repr(dennis))
# The function deletes the named attribute
delattr(dennis, 'name')
# 'property()' Return a property attribute
# class property(fget=None, fset=None, fdel=None, doc=None)
# - doc creates a docstring for the attribute
class C:
def __init__(self):
self._x = None
# function for getting an attribute value
def getx(self):
return self._x
# function for setting an attribute value
def setx(self, value):
self._x = value
# function for deleting an attribute value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
c = C()
c.x # invoke the getter
c.x = 2 # invoke the setter
del c.x # invoke the deleter
# This code is exactly equivalent to the first example
class C:
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
# The object() function returns a featureless
# object which is a base for all classes
my_object = object()
# Get all the attributes
print(dir(my_object))
An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
# Lists, tuples, dictionaries, and sets are all iterable objects
my_list = [ 1, 2, 3 ]
# The 'for' takes the list iterator
# and then moves through it using
# the built-in 'next' iterator method
for number in my_list:
print(number)
# Let's repeat what the 'for' does, but now manually
my_list = [ 1, 2, 3 ] # The same list
list_iterator = iter(my_list) # Returns the iterator
print(next(list_iterator)) # Returns the next value of iterator
print(next(list_iterator))
print(next(list_iterator))
# It is possible to do the same but with a 'while' loop
my_list = [ 1, 2, 3 ]
list_iterator = iter(my_list)
while True:
try:
current_value = next(list_iterator)
print(current_value)
# The 'next' method returns an exception when the list ends
except StopIteration:
break # Stops the while loop
# It is possible to create an iterator,
# is a class that has to have two methods, the 'iter' and the 'next'
class MyNumbers:
# Return the iterator
def __iter__(self):
self.end = 3
self.value = 1 # Start value
return self # Return himself
# It says how to get the next value
def __next__(self):
if self.value > self.end:
# Stops the execution of the 'for' loop
raise StopIteration
current = self.value
self.value += 1
return current
my_numbers = MyNumbers()
for number in my_numbers:
print(number)
Scope refers to the coding region from which particular object is accessible.
LEGB rule (Local, Enclosing, Global, and Built-in):
- Built-in Python scope (Predefined names: open, range, len, etc)
- Global or module scope (Names assigned at top-level of a module or declared global in function)
- Enclosing or nonlocal scope (Only exists for nested functions)
- Local or function scope (Names assigned inside a function def)
len('len() is a built-in function') # built-in scope
number = 0 # global scope
def my_function_one():
number = 1 # enclosed scope
def my_function_two():
number = 2 # local scope
def my_function():
number = 2
my_function()
# print(number) NameError: name 'number' is not defined
# The variable number cannot be accessed from outside the function
def myfunction():
global number # global variable
number = 2
myfunction()
print(number) # can be accessed outside the function
number = 2 # can be used inside the function
def my_function():
print(number)
print(number)
def my_function_one():
name = "King Arthur"
def my_function_two():
# Update and return a dictionary representing the current local symbol table
print(f'Local: {locals()}')
nonlocal name # non local variable
# sets the value of 'name' variable of the 'my_function_one()'
name = "Black Knight"
my_function_two()
return name
print(my_function_one())
Simply, a module is a file consisting of Python code. A module can define functions, classes and variables.
# Save this code in a file named 'my_module.py'
def greeting(name):
print('Hello, ' + name)
# This code is commented out because it doesn't run on the jupyter notebook
# import my_module
# my_module.greeting('Rabbit of Caerbannog')
# output: Hello, Rabbit of Caerbannog
# Create an alias for my_module called my
# import my_module as my
# my.greeting('Rabbit of Caerbannog')
# output: Hello, Rabbit of Caerbannog
# Return a dictionary representing the current global symbol table
print(len(globals()))
globals()['my_iterable']
try:
raise Exception("Sorry, no numbers below zero")
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
# This code is commented out because it doesn't run on the jupyter notebook
# file = open("hello.txt", "r")
# r - Read
# a - Append
# w - Write
# x - Create
# print(file.read())
# print(file.readline())
# file.close()
# Using with statement
# with open('hello.txt', 'w') as file:
# file.write('hello world !')
# no need to call file.close() when using with
# Returns a readable version of any object
# (Strings, Tuples, Lists, etc)
ascii([ 1, 2, 3 ]) # 1, 2, 3
# Compile the source into a code or AST object
ast = compile('print("Hello, World!")',
'test', 'eval')
# Code objects can be executed by:
exec(ast) # Hello, World!
eval(ast) # Hello, World!
# Convert the number 4 and imaginary
# number 2 into a complex number
print(complex(4, 2)) # (4+2j)
# The 'zip()' function takes in iterables as arguments and returns an iterator.
numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
zipped = zip(numbers, letters)
print(type(zipped))
print(list(zipped))
for number, letter in zip(numbers, letters):
print(number, letter)
# In interactive mode, the last printed expression
# is assigned to the variable _
2 + 2
print(_)
# This function drops you into the debugger at the call site
breakpoint()
# '__main__' is the name of the scope in which top-level code executes
# A module’s __name__ is set equal to '__main__' when read from standard
# input, a script, or from an interactive prompt
print(__name__)
if __name__ == "__main__":
# execute only if run as a script
print('Your Module Is the Main Program')
import keyword
print(keyword.kwlist, sep='')