python
This is an old revision of the document!
Table of Contents
Python
Testing for odd
num = 7
if num % 2 != 0:
print(f"{num} is odd.")
Importing code
from machine import PIN means get the PIN class from the file machine from ir_rx.nex import nec_8 means get the NEC_8 class from the file nec in the directory ir_rx
Passing Variables
- Use classes!
- Python will not change what I think are global variables in functions.
- If, for example, you have a variable xyzzy, and you reference it in a function, python creates a new one.
- So you have to pass in xyzzy if you want to modify it.
- You then have to return it explicitly, because Python returns the value of the last expression.
def incrementXyzzy():
xyzzy = xyzzy + 1
#does not work because xyzzy is a local created on the fly
def incrementXyzzy(xyzzy):
xyzzy = xyzzy + 1
#xyzzy is passed in and can be incremented. it will be returned
def incrementXyzzy(xyzzy):
xyzzy = xyzzy + 1
return xyzzy #explict return is better
#xyzzy is passed in and can be incremented. it will be returned
xyzzy = incrementXyzzy(xyzzy):
#the calling function MUST assign the returned value
Read Csv
- import csv
- file = open('Emp_Info.csv', 'r')
- try:
- reader = csv.reader(file)
- for each_row in reader:
- print(each_row)
- finally:
- file.close()
Lists
- create list - stock = []
- append to list - stock.append(“fred”)
Pip
- python -m pip install somePackage
- sudo python -m pip install email_to ←—————— does not work
error: externally-managed-environment
This environment is externally managed To install Python packages system-wide, try apt install python3-xyz, where xyz is the package you are trying to install.
If you wish to install a non-Debian-packaged Python package, create a virtual environment using python3 -m venv path/to/venv.
Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make sure you have python3-full installed.
For more information visit http://rptl.io/venv
Files
- open file - input = (“someFileLocation”, “r”)
- read a line - line = input.readline()
file_path = 'randomfile.txt'
file_text = open(file_path, "r")
a = True
while a:
file_line = file_text.readline()
if not file_line:
print("End Of File")
a = False
file_text.close()
file = open("randomfile.txt", "r")
while (f := file.read()):
process(f)
file.close()
Packages
- packages live in C:\Users\Donald\AppData\Local\Programs\Python\Python313\Lib\site-packages
- a pip install of exifread appeared to work but did not create this package in the above directory
- found it on Git, downloaded a zip, and copied the package to the site-packages directory
python.1773280256.txt.gz · Last modified: 2026/03/12 01:50 by donald
