https://docs.python.org/3/tutorial/classes.html
domingo, 15 de febrero de 2026
class and name space
miércoles, 11 de febrero de 2026
Functions
Defining Functions
We can create a function that writes the Fibonacci series to an arbitrary boundary:
def fib(n): # write Fibonacci series less than n
"""Print a Fibonacci series less than n."""
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
# Now call the function we just defined:
fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 The keyword def introduces a function definition. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, and must be indented.
A function definition associates the function name with the function object in the current symbol table. The interpreter recognizes the object pointed to by that name as a user-defined function. Other names can also point to that same function object and can also be used to access the function:
fib
<function fib at 10042ed0>
f = fib
f(100)
0 1 1 2 3 5 8 13 21 34 55 89Return value.
It is simple to write a function that returns a list of the numbers of the Fibonacci series, instead of printing it:
def fib2(n): # return Fibonacci series up to n
"""Return a list containing the Fibonacci series up to n."""
result = []
a, b = 0, 1
while a < n:
result.append(a) # see below
a, b = b, a+b
return result
f100 = fib2(100) # call it
f100 # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]This example, as usual, demonstrates some new Python features:
The
returnstatement returns with a value from a function.returnwithout an expression argument returnsNone. Falling off the end of a function also returnsNone.
The statement
result.append(a)calls a method of the list objectresult. A method is a function that ‘belongs’ to an object and is namedobj.methodname, whereobjis some object (this may be an expression), andmethodnameis the name of a method that is defined by the object’s type. Different types define different methods. Methods of different types may have the same name without causing ambiguity. (It is possible to define your own object types and methods, using classes, see Classes) The methodappend()shown in the example is defined for list objects; it adds a new element at the end of the list. In this example it is equivalent toresult = result + [a], but more efficient.
4.9.1. Default Argument Values
The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:
def ask_ok(prompt, retries=4, reminder='Please try again!'):
while True:
reply = input(prompt)
if reply in {'y', 'ye', 'yes'}:
return True
if reply in {'n', 'no', 'nop', 'nope'}:
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)
This function can be called in several ways:
giving only the mandatory argument:
ask_ok('Do you really want to quit?')giving one of the optional arguments:
ask_ok('OK to overwrite the file?', 2)or even giving all arguments:
ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')
This example also introduces the in keyword. This tests whether or not a sequence contains a certain value.
The default values are evaluated at the point of function definition in the defining scope, so that
i = 5
def f(arg=i):
print(arg)
i = 6
f()
will print 5.
Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
This will print
[1]
[1, 2]
[1, 2, 3]
If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return LPositional, Tuple, and Dictionary Arguments
Output
def fn(pos, *args, **kwargs): print("Positional argument:", pos) print("Tuple argument:", args) print("Dictionary argument:", kwargs) fn('Placencio', 100, 300, 200, name='Ambiorix', lastname='Rodriguez')
Positional argument: Placencio Tuple argument: (100, 300, 200) Dictionary argument: {'name': 'Ambiorix', 'lastname': 'Rodriguez'}
fn('Placencio', 100, 300, 200, name='Ambiorix', lastname='Rodriguez')
https://docs.python.org/3/tutorial/controlflow.html#defining-functions
viernes, 30 de enero de 2026
Topics
https://docs.python.org/3/reference/lexical_analysis.html
martes, 23 de diciembre de 2025
function parameters
# 1️⃣ *args — Extra positional parameters
def print_numbers(*args):
print("Positional numbers:", args)
print_numbers(1, 2, 3, 4)
# Output:
# Positional numbers: (1, 2, 3, 4)
print()
# 2️⃣ **kwargs — Extra keyword parameters
def print_info(**kwargs):
print("Keyword info:", kwargs)
print_info(name="Alice", age=17, country="FR")
# Output:
# Keyword info: {'name': 'Alice', 'age': 17, 'country': 'FR'}
print()
# 3️⃣ * — Force keyword-only arguments
def connect(host, port, *, timeout=5, ssl=False):
print(host, port, timeout, ssl)
connect("localhost", 5432, timeout=10, ssl=True)
# Output:
# localhost 5432 10 True
print()
# 4️⃣ ** in a call — Unpack dict into keywords
def greet(name, age):
print(f"Hello {name}, you are {age} years old!")
data = {"name": "Bob", "age": 20}
greet(**data)
# Output:
# Hello Bob, you are 20 years old!
print()
# 5️⃣ Combined example with all of them
def full_example(a, b, *args, c=10, **kwargs):
print("a, b:", a, b)
print("args:", args)
print("c:", c)
print("kwargs:", kwargs)
full_example(1, 2, 3, 4, 5, c=99, x=100, y=200)
# Output:
# a, b: 1 2
# args: (3, 4, 5)
# c: 99
# kwargs: {'x': 100, 'y': 200}
martes, 27 de mayo de 2025
iterating
>>> i=0
>>> while i<len(a.keys()):
... print(a[list(a.keys())[i]])
... i=i+1
...
Ambiorix
43
195
domingo, 6 de abril de 2025
Pyhon Exception
try:
result = 10 / a
except Exception as e:
print(f"An unexpected error occurred: {e}")
else:
print("Codigo funciona")
finally:
print("Siempre corre")
domingo, 16 de marzo de 2025
python generators
# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
def test(i):
n=0
while n<i:
if n==3:
yield 'We reached the limit'
else:
yield n
n=n+1
m=test(24)
print(next(m))
print(next(m))
print(next(m))
print(next(m))
///////
0
1
2
We reached the limit
jueves, 13 de febrero de 2025
while and if
i=0
m=True
while m:
print(i)
i+=1
if i==10:
m=False
0
1
2
3
4
5
6
7
8
9
find missing number from a list range
l1=[1,2,5,6]
l2=[7, 1, 3, 5, 6]
def find_missing_number(l1):
max_n=max(l1)+1
min_n=min(l1)
c=[a for a in range(min_n,max_n) ]
missing_n=[a for a in c if a not in l1]
return missing_n
print(find_missing_number(l1))
print(find_missing_number(l2))
[3, 4]
[2, 4]
miércoles, 22 de enero de 2025
using cases with dict
def mycase(v):
d={"A":13,"B":14,"C":22}
if v in d.keys():
return d[v]
else:
return 0
print(mycase("C"))
lunes, 20 de enero de 2025
https://cloud.google.com/video-intelligence/docs/streaming/live-streaming
https://cloud.google.com/video-intelligence/docs/streaming/live-streaming
sábado, 4 de enero de 2025
Python Range
>>>
>>> [a for a in range(2,11,2) ]
[2, 4, 6, 8, 10]
>>> [a for a in range(2,11,2) if a>4]
[6, 8, 10]
>>> [a**2 for a in range(2,11,2) if a>4]
[36, 64, 100]
>>>
filtering a list with other list
>>> l=[a for a in l if a not in ['Casa',0]]
>>> l
['Television', 10, 'Pistola']
>>> l=[a for a in l if a not in ['Casa',0]]
>>> l
['Television', 10, 'Pistola']
miércoles, 25 de diciembre de 2024
Switch Match
>>> def http(e):
... match e:
... case 400:
... print('Error 400')
... case 401:
... print('Auth request')
... case _:
... print('Unknow error')
...
>>> http(12)
Unknow error
>>> http(500)
Unknow error
>>> http(400)
Error 400
martes, 24 de diciembre de 2024
OpenAI API Realtime TTS and Speech to Text
https://platform.openai.com/docs/guides/realtime-websocket?websocket-examples=python
martes, 17 de diciembre de 2024
getting key from a dict based on a value
>>> users
{'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}
>>> [a for a in users.keys() if users.get(a)=='active']
['Hans', '景太郎']
jueves, 12 de diciembre de 2024
getting only str o int values from a dict
>>> r
{'Name': 'Ambiorix', 'age': 34}
>>> {r[a]:a for a in r if type(r[a])==int}
{34: 'age'}
>>> {r[a]:a for a in r if type(r[a])==str}
{'Ambiorix': 'Name'}
martes, 10 de diciembre de 2024
dict practice
>>>
>>>
>>> answer
'Ambiorix Rodriguez Placencio'
>>> chr(max({a:ord(a) for a in answer}.values()))
'z'
>>> chr(max({a:ord(a) for a in answer}.values()))
jueves, 28 de noviembre de 2024
accessing to dict values
Code that modifies a collection while iterating over that same collection can be tricky to get right. Instead, it is usually more straight-forward to loop over a copy of the collection or to create a new collection:
# Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}
# Strategy: Iterate over a copy
for user, status in users.copy().items():
if status == 'inactive':
del users[user]
# Strategy: Create a new collection
active_users = {}
for user, status in users.items():
if status == 'active':
active_users[user] = statusdomingo, 10 de noviembre de 2024
reading a file
import os
import sys
def search_key_value(file_path, search_key):
# Open and read the file safely using a context manager
with open(file_path, 'r') as file:
lines = file.readlines()
# Create a dictionary from the parsed list
parsed_dict = {line.strip().split(',')[0]: line.strip().split(',')[1] for line in lines}
# Return the value associated with the search key if it exists
return parsed_dict.get(search_key)
# Example usage:
file_path = '/var/www/html/fwlist.conf'
sound_folder = '/var/lib/asterisk/sounds/en/custom/'
search_key = sys.argv[1]
file = search_key_value(file_path, search_key)
if file:
print(f"The value for key '{search_key}' is: {file}")
# Check if the corresponding file exists
file_path = sound_folder + file
print(1 if os.path.isfile(file_path) else 0)
else:
print(f"Key '{search_key}' not found.")
print(0)