May 10, 2022
I love the Python programming language. It is the most intuitive of all the languages, I feel. After you use it awhile, you can pretty much guess the proper syntax for an operation, and you'd probably be right.
Still I need a handy reference guide. So here is a collection of basic Python operations, presented not so much as a form of instruction, but as a guide for quick consultation. I also cover the creation of lists and dictionaries, functions and file input and output.
I cribbed the material from the documentation, as well as from the Codecademy site.
For many of these examples, I'm using the Python Shell. The “>>>” is the shell prompt, the unannotated lines below that are the response from the shell. These samples used Python 3.9 and 3.10, both from the Anaconda distribution for Windows.
SIMPLE OPERATIONS:
Mathematical operations:
An equal sign assigns value to a variable:
Variables (including text strings) can be updated with "+=":
The modulo operator ("%") provides the remainder of a division:
You can do complex numbers:
Variable names can be part of a formula:
Text strings can be concatenated ("+") :
Strings are indexed:
Length of a string can be determined thusly:
Strings can be mathematically manipulated:
Numbers need to be converted into a text string to be read as text:
Multi-line text can be printed with triple quotes:
LISTS:
Now covered on its own page
DICTIONARIES:
Create a Dictionary:
Dictionaries are sets of key/value pairs, with the item ("key") on the left and the "value" on the right.
A value can be a number, but also can be a string or a Boolean ("true").
Print a Dictionary:
The entire set will be printed in no specific order.
Print just the keys:
Print just the values:
LOOPS/CONDITIONALS:
If/Then:
If/Else:
If/Elif:
For Loop:
While loop:
Functions:
The "print_grades" function is defined in the first block, and is called in the bottom line,
just after the dataset is entered. The function cycles through each data point, printing each grade:
The variables passed into functions are called parameters. When the function is called,
they are passed in as variables. You can also define default values within the parameters themselves.
They can be over-written by an externally-defined variable:
You can get multiple return variables from a function by declaring multiple variables and then set them to the return call:
READING/WRITING FILES:
Reading the Files in a Directory, With Filter:
['03-Succulent-DirtyBandits-Blah.jpg', '03-Succulent-Ezo-SinOfEnvy.jpg']print glob.glob('*.jpg')
Creates a File:
f= open(FileNameVariable,"w+")Opens a File
f2= open("/File/Location/", "r")Reads data in the file previously opened:
Content =f2.read()Write data to the file created:
f.write(Content)Closes both files:
f.close() f2.close()