Thursday, June 30, 2022
Python - Lists
# Displays all the items in the list
print(thislist)
# Displays only index item 0 of the list (apple)
print(thislist[0])
# How many items in the list?
# 3
print(len(thislist))
list1 = ["abc", 34, True, "Pecan"]
print(list1)
# class 'list'
print (type(thislist))
# Negative indexing
# cherry
print(thislist[-1])
# 0 1 2 3 4 5 6
bigList = ["Adam", "Bob", "Charlie", "David", "Ed", "Frank", "Greg" ]
# Charlie, David, Ed
# So confusing. Stops before the upper end
# W3schools says: "Start at index 2 (included) and end at index 5 (not included)
print(bigList[2:5])
# Ends at index 3 (not included)
# Adam Bob Charlie
print(bigList[:3])
# Starts at index 3 and goes to the end
# David Ed Frank Greg
print(bigList[3:])
# Starts with Ed, three from the end
# Ends with the last one, but does not include the last one
# So winds up being:
# Ed Frank
print(bigList[-3:-1])
# This will replace index 1 (Bob) with the value of "Babette"
# Remember that indexes start with 0,
# so "1" would be the SECOND index position (Bob)
bigList[1] = "Babette"
# Adam Babette Charlie...
print (bigList)
# Replace index values #2 and #3
# Remember it stops before #4
bigList[2:4] = ["Camille", "Denise"]
# Adam Babette Camille Denise Ed Frank Greg
print (bigList)
# 7 items
print (len(bigList))
# Replace index position 1 with two list
bigList[1:2] = ["Becca", "Cagney"]
# ['Adam', 'Becca', 'Cagney', 'Camille', 'Denise', 'Ed', 'Frank', 'Greg']
print (bigList)
# Now 8 items
print (len(bigList))
# Insert a list item at index position 4
# It becomes the new index position 4; everything else is moved toward the end
bigList.insert(4, "Daphne")
# ['Adam', 'Becca', 'Cagney', 'Camille', 'Daphne', 'Denise', 'Ed', 'Frank', 'Greg']
print (bigList)
# 9
print (len(bigList))
Wednesday, June 29, 2022
Python - Lists, Tuples, Sets, and Dictionaries
# Lists use a square bracket []
# Tuples are ordered, unchangeable, and allow duplicate values
# Tuples use parentheses ()
# Sets are UNORDERED, unchangeable, and do NOT allow duplicates
# Sets use curly brackets {}
# Dictionaries are ordered, changeable, and do NOT allow duplicates
# Dictionaries use curly brackets {} but specify key:value pairs
mylist = ["apple", "banana", "cherry", "apple"]
mytuple = ("apple", "banana", "cherry", "apple")
myset = {"apple", "banana", "cherry"}
mydictionary = {
"brand": "chiquita",
"model": "banana",
"year": 2022
}
# ['apple', 'banana', 'cherry', 'apple']
print(mylist)
# ('apple', 'banana', 'cherry', 'apple')
print(mytuple)
# {'banana', 'cherry', 'apple'}
print(myset)
# {'brand': 'chiquita', 'model': 'banana', 'year': 2022}
print(mydictionary)
Thursday, June 23, 2022
Python - Booleans
print(10 > 9)
# Returns false
print(10 == 9)
# Returns false
print (10 < 9)
a = 100
b = 9
# Prints "a is greater than b"
if a > b:
print ("a is greater than b")
else:
print ("a is not greater than b")
print ("out of the if/else")
print("---")
# Most values are true
# These all display "True"
print(bool("abc"))
print(bool(True))
print(bool(123))
print(bool(["apple", "cherry", "banana"]))
print("---")
# But some values are false
print(bool(False))
print(bool(None))
print(bool(0))
print(bool(""))
print(bool(()))
print(bool([]))
print(bool({}))
print("---")
# Functions can return True or False
def myFunction():
# Is John awesome?
return True
print(myFunction())
if myFunction():
print ("John is awesome")
else:
print ("You are mistaken")
print("---")
Wednesday, June 22, 2022
Python - String methods
There are a bunch of string methods listed over at W3Schools.
Here are some I particularly like:
count() - Returns the number of times a specified value occurs in a string
find() - Searches the string for a specified value and returns the position of where it was found
index() - Searches the string for a specified value and returns the position of where it was found
isalnum() - Returns True if all characters in the string are alphanumeric
isalpha() - Returns True if all characters in the string are in the alphabet
isdecimal() - Returns True if all characters in the string are decimals
isdigit() - Returns True if all characters in the string are digits
isnumer() - Returns True if all characters in the string are numeric
isprintable() - Returns True if all characters in the string are printable
lstrip() - Returns a left trim version of the string
replace() - Returns a string where a specified value is replaced with a specified value
rfind() - Searches the string for a specified value and returns the last position of where it was found
rindex() - Searches the string for a specified value and returns the last position of where it was found
rstrip() - Returns a right trim version of the string
split() - Splits the string at the specified separator, and returns a list
startswith() - Returns true if the string starts with the specified value
strip() - Returns a trimmed version of the string
zfill() - Fills the string with a specified number of 0 values at the beginning
Python - Escape characters
# Because of the quotes around the word "never"
#txt = "This will "never" work"
# The fix is to escape the quotes
txt = "This will \"never\" work"
print(txt)
"""
\' = Single quote
\\ = Backslash
\n = New line
\r = Carriage return
\t = Tab
\b = Backspace
\f = Form feed
"""
Python - Formatting strings
# A simple approach
myVar = "caveman"
txt = "So easy a " + myVar + " could do it"
print(txt)
# Fancy
age = 36
txt = "My name is John, and I am not {}"
print(txt.format(age))
# Fancier
age = 36
name = "John"
txt = "My name is {}, and I am not {}"
print(txt.format(name, age))
# Fancy-pants
# Notice the order
quantity = 3
itemno = 567
price = 49.95
myOrder = "I want to pay {2} dollars for {0} pieces of item {1}."
# This will print "I want to pay 49.95 dollars for 3 pieces of item 567."
print(myOrder.format(quantity, itemno, price))
print ("---")
# The following line of code will never work
# Because of the quotes around the word "never"
#txt = "This will "never" work"
# The fix is to escape the quotes
txt = "This will \"never\" work"
print(txt)
Python - Concatenate strings
a = "Hello, World!"
# Prints HELLO, WORLD!
print(a.upper())
# Prints hello, world!
print(a.lower())
print("---")
a = " Hello, World! "
# Prints "Hello, World!"
# Notice the space at the beginning and end is removed (stripped)
print(a.strip())
print("---")
print("Destructive?")
# Destructive to original contents?
a.strip()
# No. Not destructive. This will print the original with spacing intact
print (a)
# So we gotta do this?
a = a.strip()
print (a)
print("Split examples:")
# This will return a list
b = a.split(",")
print (b)
# Told you it was a list
print (type(b))
print ("Type: " + str(type(b)))
Python - Left, Right, and Middle string ranges
# Python stops right before the upper bound
# So this will print "llo"
# Character positions 2, 3, and 4
# Remember that strings start at 0
b = "Hello, World!"
print(b[2:5])
# By leaving out the starting parameter,
# we can print the first five characters
# This prints "Hello"
b = "Hello, World!"
print(b[:5])
# Conversely, if we leave out the end parameter
# we print to the end of the string
# Therefore, this prints "llo World!"
b = "Hello, World!"
print(b[2:])
# Use negatives indexes to count from the end
# to print the last character of the string
# This will print the last character (!)
b = "Hello, World!"
print(b[-1])
# This will print the "W"
print(b[-6])
# Getting fancy:
# Print from W to the end of the string
print(b[-6:])
Python - Fun with strings and random numbers
myVar = "hello"
# First character is position 0
# So this will print "h"
print(myVar[0])
print("----")
# This will print 0 through 4
for x in range(5):
print(x)
print("Now out of for loop")
print("----")
# This will loop through the string myVar
# It will print each letter on a different line
# "hello" = 5 characters
# Positions 0 through 4
for x in range(5):
print (myVar[x])
print("Now out of for loop")
print("----")
# Lazier way of looping through the word
print("Lazy:")
for x in myVar:
print(x)
print("----")
# Print a random letter of the string
# Need to import the module
import random
# By default the seed will use the system time if we leave it blank
random.seed()
myRandomNumber = random.randrange(0, len(myVar) )
print(myVar[myRandomNumber])
print("----")
# Do it 30 times, each time printing a different random letter
# This is a good way to force errors if I have my upper/lower bounds wrong
for x in range(30):
myRandomNumber = random.randrange(0, len(myVar) )
print(myVar[myRandomNumber])
Python - Data Types
x = str("Hello World")
print (x)
print (type(x))
# Will display <class 'str'>
x = int(20)
print(type(x))
x = float(20.5)
print(type(x))
x = complex(1j)
print(type(x))
x = list(("apple", "banana", "cherry"))
print(type(x))
x = tuple(("apple", "banana", "cherry"))
print(type(x))
x = range(6)
print(type(x))
x = dict(name="John", age=36)
print(type(x))
x = set(("apple", "banana", "cherry"))
print(type(x))
x = frozenset(("apple", "banana", "cherry"))
print(type(x))
x = bool(5)
print(type(x))
x = bytes(5)
print(type(x))
x = bytearray(5)
print(type(x))
x = memoryview(bytes(5))
print(type(x))
Python - Global variables
x = "awesome"
def myfunc():
x = "cool"
print("Python is " + x) # Output: Python is cool
myfunc()
print("Python is " + x) # Output: Python is awesome
def myfunc2():
# Notice here we turn what would normally have been a local variable 'y' into a global variable
# This means it is accessible outside this function
global y
y = "fantastic"
print ("Python is " + y) # Output: Python is fantastic
myfunc2()
print ("Python is " + y) # Output: Python is fantastic
Python - Start here
# This is a comment
x = 5 # This is another comment
y = 2
"""
This is an interesting way to make
a multi-line comment.
But it is probably convenient to comment out a bunch of code this way.
"""
z = "Hello world"
if x > y:
print("Five is greater than 2")
print("Out of the if branch")
# Here we see the variables were set above
print("x:")
print(x)
print("y:")
print(y)
print("z:")
print(z)
# Now we redefine the variables to different types on the fly
x = "apple"
y = "banana"
z = 400
# Here we see the redefined variables worked
print("x:")
print(x)
print("y:")
print(y)
print("z:")
print(z)
# This tells us the data type
print("z is a")
print(type(z))
# This lets us recast a variables type as a different type
z = str(z)
print("z:")
print(z)
print("z is a")
print(type(z))
# Both single and double quotes work
firstName = "John"
lastName = 'Doe'
myVar = "John"
myVAR = "Doe"
# Case sensitive variable names
print("myVar:")
print(myVar)
print("myVAR:")
print(myVAR)
# Assign 3 variables three different values
x, y, z = "John", "Doe", "Smith"
print(x)
print(y)
print(z)
# Assign 3 variables the same value is evil!
multi = variable = declaration = "evil"
print(multi)
print(variable)
print(declaration)
# Unpacking is cool: This snippet "unpacks" a list into three different variables
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x) # x will be set to apple
print(y) # y will be set to banana
print(z) # z will be set to cherry
# Here is a way of printing all three variables on the same line
print(x, y, z) # Output: apple banana cherry
# Here is another way but no space in between each value
print(x + y + z) # Output: applebananacherry
x = 10
y = 5
print(x + y) # Output: 15
x = "John"
y = 5
z = "years old"
print(x, "is", y, z) # Output: John is 5 years old
exit()
Tuesday, June 21, 2022
Python - Table of contents
I am working my way through the Python tutorial and taking notes.
I keep my notes here for ease of access (home/work/travel).
I find this is the best way for me to remember and then refer back to a language.
I tend to skip stuff that makes sense to me and go into more detail on things I have trouble with.
So this is more for me than you, weary traveler.
The full W3Schools tutorial can be found here:
https://www.w3schools.com/python/default.asp
Table of contents
Start here
Global variables
Data types
Fun with strings and random numbers
Left, Right, and Middle string ranges
Concatenate strings
Formatting strings
Escape characters
String methods
Booleans
Lists, Tuples, Sets, and Dictionaries
Lists
Add or remove items from a list
Loop through lists
List Comprehension
Sort lists
Copy lists
Join lists
Tuples
Unpacking tuples
Add and remove items from a set
Set joins
Dictionaries
If... Else
While loops
For loops
Functions
Classes and Inheritance
Scope
Modules
Dates
Math
Regular Expressions
Error handling (try, except, else, finally)
User input
String formatting
File handling