Skip to content

Commit

Permalink
added code
Browse files Browse the repository at this point in the history
  • Loading branch information
jesusBernalBermudez committed Mar 3, 2021
1 parent 09c1e3e commit cfbc971
Show file tree
Hide file tree
Showing 30 changed files with 333 additions and 205 deletions.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
## [Máster en Ingeniería Web por la Universidad Politécnica de Madrid (miw-upm)](http://miw.etsisi.upm.es)
## Back-end con Tecnologías de Código Abierto (BETCA).
> Este proyecto es un apoyo docente de la asignatura y contiene ejemplos prácticos sobre Python
### Tecnologías necesarias
`Python` `GitHub`

### :gear: Instalación del proyecto
1. Clonar el repositorio en tu equipo, **mediante consola**:
```sh
> cd <folder path>
> git clone https://github.com/miw-upm/betca-python
```
2. Importar el proyecto mediante **PyCharm**
1. **Open**, y seleccionar la carpeta del proyecto.
1. Instalar las dependencias
7 changes: 7 additions & 0 deletions config.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
ENVIRONMENT=prod

DEV_VAR=value-on-dev
DEV_JWT_SECRET=secret-to-test

PROD_VAR=value-on-production
PROD_JWT_SECRET=secret-${USERNAME}
5 changes: 5 additions & 0 deletions language/1_hello_world.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Hello World
"""
Hello World!!!
"""
print('Hello world!')
32 changes: 21 additions & 11 deletions language/variables.py → language/2_variables.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
import datetime
from datetime import date

# types: str, int, float, complex, bool, list, tuple, range, dict, set, frozenset, bytes, bytearray, memoryview
str_var: str # STATIC var is not defined, it is not possible to use until creating with =
str_var = 'string' # DYNAMIC. str_var is created. It's possible "string", esc==\
var = 5 # var is created
str_var: str # STATIC var is not defined, it is not possible to use until creating with '='
# print(str_var) ERROR!!!
str_var = 'string' # DYNAMIC. str_var is created. It is possible use '...' or "...", esc==\

var = 5 # var is created, it is var = int(5)
null_var = None # None is null and var is created
casting_var = str(var) # casting: str(), float()...
i = 3 + 2j # complex: i.real, i.imag ...
var = 'other' # dynamic type
var = 'other' # dynamic type: from int to str

# One line: one sentence. With \ the line continue
large_str = '''line one\
line one & end of line
other line''' # '\' without end of line
print(large_str[-10:-5]) # Use negative indexes to start from the end of the string
print(large_str[0:5])
print(large_str[5:])
print('1- ', large_str[-10:-5]) # Use negative indexes to start from the end of the string
print('2- ', large_str[0:5])
print('3- ', large_str[5:])
print('4- ', large_str[:]) # it is copy
age = 36
anniversary = datetime.date(1991, 10, 12)
txt = f"My name is \"John\", and I am {age}, my anniversary is {anniversary:%A, %B %d, %Y}"
print('text {}'.format(age))
anniversary = date(1991, 10, 12)
txt = f"My name is \"John\", and I am {age}, my anniversary is {anniversary:%A, %B %d, %Y}" # \ is esc
print('5- ', 'text {}'.format(age))
print('6- ', f'text {age}')

my_list = ["apple", "banana", "cherry"] # list .append .extend .remove .pop .popleft .clear .reverse ...
my_tuple = "apple", "banana", "cherry" # tuple immutable
Expand All @@ -29,3 +34,8 @@
my_set_immutable = frozenset({"apple", "banana", "cherry"}) # set immutable

bytes_var = b'byte'

print('7- type of str_var: ', type(str_var))
print('8- type of age: ', type(age))
print('9- type of anniversary: ', type(anniversary))
print('10- type of bytes_var: ', type(bytes_var))
15 changes: 15 additions & 0 deletions language/3_operators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Arithmetic operators: +, -, *, /, //, %, **
var = 5
print('1- ', '5/2 = ', var / 2)
print('2- ', '5//2 = ', var // 2)
print('3- ', '5%2 = ', var % 2)
print('4- ', '5**2 = ', var ** 2)

# Assignment operators: =, +=, -=, *=, /=, %=, //=, **=, &=, |=, ^=, >>=, <<=
var *= 3
print('5- ', 'var *=3 ', var)

# Logical operators: and, or, not, ==, !=, >, <, >=, <=, is is not
print('6- ', '17>15>12 = ', 17 > var > 12)

# Bitwise Operators: &, |, ^, ~, <<, >>
12 changes: 6 additions & 6 deletions language/flows.py → language/4_flows.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
# Flows
g = 1
if g < 0:
g = 0
print('Negative changed to zero')
print('1- ', 'Negative changed to zero')
elif g == 0:
print('Zero')
print('1- ', 'Zero')
else:
print('More')
print('1- ', 'More')

# Loop: break & continue & else
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w)
print('2- ', w)

for i in range(0, 10, 2):
print(i)
print('3- ', i)

while g < 10:
print('4- ', g)
g += 1
14 changes: 14 additions & 0 deletions language/5_dicts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# dict: len(my_dict), my_dict['name'] or my_dict.get("name"), .keys(), .values(), .clear(), .copy()
my_dict = {"name": "John", "age": 36, "dni": 12345678, "role": None}
print('1- ', my_dict.keys())
print('1- ', my_dict.values())

for key in my_dict.keys():
print('2- ', key, ':', my_dict[key])
print('2- ', key, ':', my_dict.get(key))

print('3- ', my_dict['age'])

my_dict.setdefault('name', 'only-if-not-exist')
my_dict.setdefault('new', 'new-value')
print('4- ', my_dict.keys(), '::', my_dict.values())
55 changes: 55 additions & 0 deletions language/6_functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
def cheese_shop(kind, *arguments, **keywords) -> int: # position, *: optional, **: dict
print('1- ', "-- Do you have any", kind, "?")
for arg in arguments:
print('1- ', arg)
for key in keywords: # .keys() is optional,
print('1- ', key, ":", keywords[key])
return 10


print('0- type of def: ', type(cheese_shop))

g = cheese_shop("-Position-",
"Optional-1", "Optional-2",
key1="Michael Palin", key2="John Cleese", key3="Cheese Shop Sketch")
print("1- ", 'cheese-shop return: ', g)


def model(index, **keywords): # keywords: Dict[str,Any]
print(index, 'keywords: ', keywords)
for key in keywords: # keywords.keys() is optional,
print(index, key, ":", keywords[key])


my_dict = {"name": "John", "age": 36, "dni": 12345678}
model('2- ', **my_dict) # convert key-value pairs into arguments
# model(my_dict) ERROR!!!
model('3- ', one=my_dict)


def make_increment(n):
return lambda param: param + n


f = make_increment(665)
print('4- ', 'lambda: ', f(1))

# variable scope
global_var = 'global'


def fun0():
non_local_var = 'nonlocal'

def fun1():
global global_var # for updating
nonlocal non_local_var # for updating
local_var = 'local'
non_local_var = 'from f1'
global_var = 'from f1'
print('6- ', 'fun1 >> global_var:', global_var, ', non_local_var:', non_local_var, ', local_var:', local_var)

fun1()


fun0()
98 changes: 98 additions & 0 deletions language/7_classes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# __***__ are especial functions and attributes


def dynamic_function():
print('dynamic_function')


class MyClass:
"""A simple example class""" # default: __doc__=...
i: int # it is a instance attribute
att = 'static' # it is a static attribute

def __init__(self, name): # constructor: __init__
print('Init MyClass:', name)
self.i = len(name)
self.name = name # 'other' is a instance attribute
self.dynamic = dynamic_function

def public(self): # public
return 'hello world (' + str(self.i) + ')'

def __private(self): # private
pass


print('0- type of class: ', type(MyClass))

print('1 ---------------- ')
my_class = MyClass('me')
my_class.dynamic()
my_class.new_attribute = "New!!!"
my_class.new_function = dynamic_function
print(my_class.new_attribute)


# Inheritance
class ChildClass(MyClass):
def __init__(self):
super().__init__('child')


print('2 ---------------- ')
ChildClass()


class Two:
two: str

def __init__(self):
print('Init Two')


# Multiple inheritance
class Multiple(MyClass, Two):
value: str


print('3 ---------------- ')
multiple = Multiple('multiple')
multiple.i = 3
multiple.name = "name"
multiple.two = "2"
multiple.value = "value"


class WithDecorator:

def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name

@classmethod
def from_string(cls, name_str):
first_name, last_name = map(str, name_str.split(' '))
return cls(first_name, last_name)

@staticmethod
def is_full_name(name_str):
names = name_str.split(' ')
return len(names) > 1


# __doc__ __init__ __name__ __module__ __call__ ...

print('4 ---------------- ')
print('__doc__ ', MyClass.__doc__)
print('__name__ ', MyClass.__name__)
print('__module__ ', MyClass.__module__)


class Callable:
def __call__(self, value): # class default function
print('__call__ >> value: ', value)


my_callable = Callable()
my_callable("!!!") # class is callable
# my_class() ERROR!!!
76 changes: 0 additions & 76 deletions language/classes.py

This file was deleted.

13 changes: 0 additions & 13 deletions language/dicts.py

This file was deleted.

Loading

0 comments on commit cfbc971

Please sign in to comment.