Spam Spam: Python Basics Math Operators Highest Lowest Data Types Data Type Examples
Spam Spam: Python Basics Math Operators Highest Lowest Data Types Data Type Examples
>>> spam
Integers -2, -1, 0, 1, 2, 3, 4, 5
'Hello'
Inline comment:
# This is a comment
String Concatenation and Replication
3 Variables """
>>> 23 % 7 You can name a variable anything as long as it obeys This is a function docstring
the following three rules:
2 You can also use:
1. It can be only one word.
>>> (5 - 1) * ((7 + 1) / (3 - 1))
2. It can use only letters, numbers, and the ''' Function Docstring '''
underscore (_) character.
""" >>> if a:
Operator Meaning
>>> print("the list is not empty!")
The print() Function
>>> print('Hello world!') The str(), int(), and float() Functions
Hello world! Integer to String or Float:
> Greater Than
>>> a = 1 >>> str(29)
5 == Equal to True
>>> pass
Boolean evaluation Expression Evaluates to
Never use == or != operator to evaluate boolean >>> if not a:
operation. Use the is or is not operators, or use
>>> pass not True False
implicit boolean evaluation.
True The and Operator’s Truth Table:
Mixing Boolean and Comparison Operators
>>> True != False
Expression Evaluates to >>> (4 < 5) and (5 < 6)
True True
True and True True
YES (even if they are valid Python): >>> (4 < 5) and (9 < 6)
>>> print('World') There are four rules to tell whether a variable is in a 42.0
local scope or global scope:
HelloWorld
Final code in exception handling
1. If a variable is being used in the global scope
>>> print('cats', 'dogs', 'mice') Code inside the finally section is always executed,
(that is, outside of all functions), then it is always
a global variable. no matter if an exception has been raised or not, and
cats dogs mice
2. If there is a global statement for that variable even if an exception is not caught.
>>> print('cats', 'dogs', 'mice', in a function, it is a global variable.
3. Otherwise, if the variable is used in an >>> def spam(divideBy):
sep=',')
assignment statement in the function, it is a
>>> try:
cats,dogs,mice local variable.
4. But if the variable is not used in an
>>> return 42 / divideBy
Local and Global Scope assignment statement, it is a global variable.
>>> except ZeroDivisionError as e:
Code in the global scope cannot use any Exception Handling
local variables. >>> print('Error: Invalid
However, a local scope can access global argument: {}'.format(e))
Basic exception handling
variables.
Code in a function’s local scope cannot use >>> def spam(divideBy): >>> finally:
variables in any other local scope.
You can use the same name for different >>> try: >>> print("-- division finished
--")
variables if they are in different scopes. That is,
there can be a local variable named spam and a >>> return 42 / divideBy
>>> print(spam(12))
global variable also named spam.
>>> except ZeroDivisionError as e:
>>> print(spam(0))
The global Statement >>> print('Error: Invalid
argument: {}'.format(e)) 21.0
If you need to modify a global variable from within a
function, use the global statement: >>> -- division finished --
['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', Index 2 in supplies is: flame-throwers >>> cat = ['fat', 'orange', 'loud']
'Z']
Index 3 in supplies is: binders
spam -= 1 spam = spam - 1 >>> spam = ['cat', 'dog', 'bat'] >>> spam.sort()
>>> spam
spam *= 1 spam = spam * 1
>>> spam.append('moose') [-7, 1, 2, 3.14, 5]
>>> spam += ' world!' You can also pass True for the reverse keyword
argument to have sort() sort the values in reverse
>>> spam >>> spam.insert(1, 'chicken') order:
>>> bacon = ['Zophie'] ['cat', 'chicken', 'dog', 'bat'] ['elephants', 'dogs', 'cats', 'badgers',
'ants']
>>> bacon *= 3
Removing Values from Lists with remove()
If you need to sort the values in regular alphabetical
>>> bacon
>>> spam = ['cat', 'bat', 'rat', order, pass str. lower for the key keyword argument in
'elephant'] the sort() method call:
['Zophie', 'Zophie', 'Zophie']
>>> spam = ['a', 'z', 'A', 'Z']
Finding a Value in a List with the index() Method
>>> spam.remove('bat') >>> spam.sort(key=str.lower)
>>> spam = ['Zophie', 'Pooka', 'Fat-
tail', 'Pooka']
>>> spam
Tuple Data Type >>> for v in spam.values(): Checking Whether a Key or Value Exists in a
Dictionary
>>> eggs = ('hello', 42, 0.5) >>> print(v)
>>> spam = {'name': 'Zophie', 'age': 7}
>>> eggs[0] red
>>> 'name' in spam.keys()
'hello' 42
True
>>> eggs[1:3] keys():
>>> 'Zophie' in spam.values()
(42, 0.5) >>> for k in spam.keys():
True
>>> len(eggs) >>> print(k)
>>> # You can omit the call to keys()
3 when checking for a key
color
The main way that tuples are different from lists is >>> 'color' in spam
age
that tuples, like strings, are immutable.
False
items():
Converting Types with the list() and tuple() >>> 'color' not in spam
>>> for i in spam.items():
Functions
True
>>> tuple(['cat', 'dog', 5]) >>> print(i)
Dictionaries and Structuring Data >>> spam = {'color': 'red', 'age': 42} 'I am bringing 2 cups.'
>>> 'I am bringing {} >>> message = 'It was a bright cold day 'l': 3,
eggs.'.format(str(picnic_items.get('eggs in April, and the clocks were striking
', 0))) 'n': 4,
>>> thirteen.'
'I am bringing 0 eggs.' 'o': 2,
>>> count = {}
The setdefault() Method 'p': 1,
>>>
Let's consider this code: 'r': 5,
>>> for character in message:
spam = {'name': 'Pooka', 'age': 5} 's': 3,
>>> count.setdefault(character, 0)
't': 6,
>>> count[character] =
if 'color' not in spam: count[character] + 1 'w': 2,
>>> pprint.pprint(count)
Using setdefault we could write the same code Merge two dictionaries
more succinctly: {' ': 13, # in Python 3.5+:
>>> spam = {'name': 'Pooka', 'age': 5} ',': 1, >>> x = {'a': 1, 'b': 2}
>>> spam.setdefault('color', 'black') '.': 1, >>> y = {'b': 3, 'c': 4}
'black' 'A': 1, >>> z = {**x, **y}
>>> spam 'I': 1, >>> z
{'color': 'black', 'age': 5, 'name': 'a': 4, {'c': 4, 'a': 1, 'b': 3}
'Pooka'}
'b': 1,
>>> spam.setdefault('color', 'white')
'c': 3, # in Python 2.7
'black'
'd': 3, >>> z = dict(x, **y)
>>> spam
'e': 5, >>> z
{'color': 'black', 'age': 5, 'name':
'Pooka'}
'g': 2, {'c': 4, 'a': 1, 'b': 3}
And as an unordered data type, they can't be indexed. >>> s >>> s3 = {3, 4, 5}
File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <module> set difference
2 17 + 5 = 22
From the official Python 3.x documentation:
operator.mul(2, 3) 22 + 9 = 31
The module standardizes a core set of fast, memory
efficient tools that are useful by themselves or in 6 31 + 1 = 32
combination. Together, they form an “iterator
algebra” making it possible to construct specialized operator.mul(6, 4) combinations()
tools succinctly and efficiently in pure Python.
24 Takes an iterable and a integer. This will create all the
The itertools module comes in the standard library
unique combination that have r members.
and must be imported. operator.mul(24, 5)
itertools.combinations(iterable, r)
The operator module will also be used. This module is 120
not necessary when using itertools, but needed for
Example:
some of the examples below. Passing a function is optional:
>>> shapes = ['circle', 'triangle',
>>> data = [5, 2, 6, 4, 5, 9, 1] 'square',]
accumulate()
Makes an iterator that returns the results of a >>> result = itertools.accumulate(data) >>> result =
function. itertools.combinations(shapes, 2)
>>> for each in result:
itertools.accumulate(iterable[, func]) >>> for each in result:
>>> print(each) Example: red
('circle', 'square') >>> print(i) When reached the end of the iterable it start over
again from the beginning.
('triangle', 'square') >>> if i > 20:
Example: 19
>>> colors = ['red', 'orange', 'yellow',
'green', 'blue']
>>> shapes = ['circle', 'triangle', 22
'square'] >>> shapes = ['circle', 'triangle',
cycle() 'square', 'pentagon']
>>> result =
itertools.combinations_with_replacement( This function cycles through an iterator endlessly. >>> result = itertools.chain(colors,
shapes, 2) shapes)
itertools.cycle(iterable)
>>> for each in result: >>> for each in result:
Example:
>>> print(each) >>> print(each)
>>> colors = ['red', 'orange', 'yellow',
('circle', 'circle') 'green', 'blue', 'violet'] red
A List comprehension can be generated from a A raw string completely ignores all escape characters >>> def my_function():
dictionary: and prints any backslash that appears in the string.
>>> print('''
>>> c = {'name': 'Pooka', 'first_name': >>> print(r'That is Carol\'s cat.')
'Oooka'} >>> Dear Alice,
That is Carol\'s cat.
>>> ["{}:{}".format(k.upper(), >>>
v.upper()) for k, v in c.items()]
Note: mostly used for regular expression definition
(see re package) >>> Eve's cat has been arrested
['NAME:POOKA', 'FIRST_NAME:OOOKA'] for catnapping, cat burglary, and
extortion.
Manipulating Strings Multiline Strings with Triple Quotes
>>>
>>> print('''Dear Alice,
Escape Characters
>>> Sincerely,
>>>
Escape Prints as >>> Bob
character >>> Eve's cat has been arrested for
catnapping, cat burglary, and extortion.
>>> ''').strip()
>>>
\' Single quote This generates the same string than before.
>>> Sincerely,
Indexing and Slicing Strings
\" Double quote >>> Bob''')
H e l l o w o r l
Dear Alice, d !
\t Tab 0 1 2 3 4 5 6 7 8 9
10 11
Eve's cat has been arrested for
\n Newline (line break) catnapping, cat burglary, and extortion. >>> spam = 'Hello world!'
\\ Backslash
Sincerely, >>> spam[0]
'Hello world'
The upper(), lower(), isupper(), and islower() The isX String Methods
>>> spam[::-1] String Methods
isalpha() returns True if the string consists
upper() and lower(): only of letters and is not blank.
'!dlrow olleH'
isalnum() returns True if the string consists
>>> spam = 'Hello world!'
>>> spam = 'Hello world!' only of lettersand numbers and is not blank.
>>> spam = spam.upper() isdecimal() returns True if the string consists
>>> fizz = spam[0:5] only ofnumeric characters and is not blank.
>>> fizz
>>> spam isspace() returns True if the string consists
only of spaces,tabs, and new-lines and is not
'HELLO WORLD!' blank.
'Hello'
>>> spam = spam.lower() istitle() returns True if the string consists
The in and not in Operators with Strings only of wordsthat begin with an uppercase
>>> spam letter followed by onlylowercase letters.
>>> 'Hello' in 'Hello World'
'hello world!' The startswith() and endswith() String Methods
True
>>> 'Hello world!'.startswith('Hello')
True >>> '=======Hello========'
'MyABCnameABCisABCSimon'.split('ABC')
>>> 'Hello world!'.endswith('world!')
['My', 'name', 'is', 'Simon'] Removing Whitespace with strip(), rstrip(), and
True lstrip()
>>> 'My name is Simon'.split('m') >>> spam = ' Hello World '
>>> 'abc123'.startswith('abcdef')
['My na', 'e is Si', 'on'] >>> spam.strip()
False
Justifying Text with rjust(), ljust(), and center() 'Hello World'
>>> 'abc123'.endswith('12')
rjust() and ljust(): >>> spam.lstrip()
False
>>> 'Hello'.rjust(10) 'Hello World '
>>> 'Hello world!'.startswith('Hello
world!') ' Hello' >>> spam.rstrip()
An optional second argument to rjust() and ljust() will >>> import pyperclip
'cats, rats, bats' specify a fill character other than a space character.
Enter the following into the interactive shell:
>>> ' '.join(['My', 'name', 'is',
'Simon']) >>> pyperclip.copy('Hello world!')
>>> 'Hello'.rjust(20, '*')
'My name is Simon'
'***************Hello'
>>> 'ABC'.join(['My', 'name', 'is', >>> pyperclip.paste()
>>> 'Hello'.ljust(20, '-')
'Simon'])
'Hello---------------' 'Hello world!'
'MyABCnameABCisABCSimon'
>>> num = 5 Lazy string formatting >>> from string import Template
>>> print(main_number)
>>> hero_regex = re.compile (r'Batman| Optional Matching with the Question Mark
>>> mo.group(2)
Tina Fey')
The ? character flags the group that precedes it as an
'555-4242' optional part of the pattern.
'415-555-4242'
>>> mo2 = hero_regex.search('Tina Fey
To retrieve all the groups at once: use the groups() and Batman.') >>> mo2 = bat_regex.search('The
method—note the plural form for the name. Adventures of Batwoman')
>>> mo1.group() Greedy and Nongreedy Matching To summarize what the findall() method returns,
remember the following:
'Batwoman' Python’s regular expressions are greedy by default,
which means that in ambiguous situations they will
When called on a regex with no groups, such >>> consonant_regex.findall('Robocop
as \d-\d\d\d-\d\d\d\d, the method findall() eats baby food. BABY FOOD.')
returns a list of ng matches, such as ['415-555- >>>
['R', 'b', 'c', 'p', ' ', 't', 's', ' ', whole_string_is_num.search('1234567890')
9999', '212-555-0000']. 'b', 'b', 'y', ' ', 'f', 'd', '.', '
When called on a regex that has groups,
<_sre.SRE_Match object; span=(0, 10),
such as (\d\d\d)-d\d)-(\d\ d\d\d), the method ', 'B', 'B', 'Y', ' ', 'F', 'D', '.'] match='1234567890'>
findall() returns a list of es of strings (one string
for each group), such as [('415', ', '9999'), ('212',
The Caret and Dollar Sign Characters
'555', '0000')].
You can also use the caret symbol (^) at the >>>
whole_string_is_num.search('12345xyz6789
Making Your Own Character Classes start of a regex to indicate that a match must 0') is None
occur at the beginning of the searched text.
There are times when you want to match a set of Likewise, you can put a dollar sign ($) at the True
characters but the shorthand character classes (\d, end of the regex to indicate the string must end
\w, \s, and so on) are too broad. You can define your with this regex pattern.
own character class using square brackets. For And you can use the ^ and $ together to
example, the character class [aeiouAEIOU] will match indicate that the entire string must match the >>> whole_string_is_num.search('12
any vowel, both lowercase and uppercase. regex—that is, it’s not enough for a match to be 34567890') is None
made on some subset of the string.
>>> vowel_regex = True
The r'^Hello' regular expression string matches strings
re.compile(r'[aeiouAEIOU]')
that begin with 'Hello':
The Wildcard Character
>>> begins_with_hello =
re.compile(r'^Hello') The . (or dot) character in a regular expression is
>>> vowel_regex.findall('Robocop eats
baby food. BABY FOOD.') called a wildcard and will match any character except
for a newline:
['o', 'o', 'o', 'e', 'a', 'a', 'o', 'o',
'A', 'O', 'O'] >>> begins_with_hello.search('Hello >>> at_regex = re.compile(r'.at')
world!')
You can also include ranges of letters or numbers by
<_sre.SRE_Match object; span=(0, 5),
using a hyphen. For example, the character class [a- match='Hello'> >>> at_regex.findall('The cat in the hat
zA-Z0-9] will match all lowercase letters, uppercase sat on the flat mat.')
letters, and numbers.
['cat', 'hat', 'sat', 'lat', 'mat']
By placing a caret character (^) just after the character >>> begins_with_hello.search('He said
class’s opening bracket, you can make a negative hello.') is None
Matching Everything with Dot-Star
character class. A negative character class will match
all the characters that are not in the character class. True
>>> name_regex = re.compile(r'First
For example, enter the following into the interactive Name: (.*) Last Name: (.*)')
shell: The r'\d$' regular expression string matches strings
that end with a numeric character from 0 to 9:
>>> consonant_regex =
re.compile(r'[^aeiouAEIOU]') >>> whole_string_is_num = >>> mo = name_regex.search('First Name:
re.compile(r'^\d+$') Al Last Name: Sweigart')
'Serve the public trust.'
Symbol Matches
>>> mo.group(1) >>> newline_regex = re.compile('.*',
re.DOTALL)
'Al' {n,m}? or *? or +? performs a nongreedy match
>>> newline_regex.search('Serve the of the preceding p.
>>> mo.group(2) public trust.\nProtect the
innocent.\nUphold the law.').group()
'Sweigart'
'Serve the public trust.\nProtect the
^spam means the string must begin
innocent.\nUphold the law.' with spam.
The dot-star uses greedy mode: It will always try to
match as much text as possible. To match any and all
text in a nongreedy fashion, use the dot, star, and Review of Regex Symbols spam$ means the string must end
question mark (.*?). The question mark tells Python to
with spam.
match in a nongreedy way: Symbol Matches
Substituting Strings with the sub() Method phone_regex = re.compile(r'((\d{3}|\ Fortunately, Python provides easy ways to handle this.
The sub() method for Regex objects is passed two
(\d{3}\))?(\s|-|\.)?\d{3}(\s|-|\.)\d{4} We will showcase how to deal with this with
(\s*(ext|x|ext.)\s*\d{2,5})?)') both os.path.join and pathlib.Path.joinpat
arguments:
h
you can spread the regular expression over multiple
1. The first argument is a string to replace any
lines with comments like this: Using os.path.join on Windows:
matches.
2. The second is the string for the regular phone_regex = re.compile(r'''( >>> import os
expression.
The sub() method returns a string with the (\d{3}|\(\d{3}\))? # area
substitutions applied: code
>>> os.path.join('usr', 'bin', 'spam')
>>> names_regex = re.compile(r'Agent (\s|-|\.)? #
\w+') separator 'usr\\bin\\spam'
\d{3} #
first 3 digits And using pathlib on *nix:
/home/asweigart/invite.docx >>>
os.makedirs('C:\\delicious\\walnut\\waff
>>> print(Path('usr') / 'bin' / 'spam') les')
The Current Working Directory
usr/bin/spam Using os on Windows: Using pathlib on *nix:
Notice the path separator is different between >>> import os >>> from pathlib import Path
Windows and Unix based operating system, that's why
you want to use one of the above methods instead of >>> cwd = Path.cwd()
adding strings together to join paths together.
>>> os.getcwd() >>> (cwd / 'delicious' / 'walnut' /
'waffles').mkdir()
Joining paths is helpful if you need to create different
file paths under the same directory. 'C:\\Python34'
Traceback (most recent call last):
>>> os.chdir('C:\\Windows\\System32')
Using os.path.join on Windows: File "<stdin>", line 1, in <module>
There are two ways to specify a file path. >>> os.getcwd() import os
>>> from pathlib import Path Finding File Sizes and Folder Contents --snip--
>>> for folder_name, subfolders, The current folder is [When, in disgrace with fortune and
filenames in os.walk('C:\\delicious'): C:\delicious\walnut\waffles men's eyes,\n', ' I all alone beweep my
>>> print('The current folder is FILE INSIDE C:\delicious\walnut\waffles: outcast state,\n', And trouble deaf
{}'.format(folder_name)) butter.txt heaven with my bootless cries,\n', And
>>> pathlib provides a lot more functionality than the look upon myself and curse my fate,']
ones listed above, like getting file name, getting file
>>> for subfolder in subfolders: extension, reading/writing a file without manually
opening it, etc. Check out the official documentation if
>>> print('SUBFOLDER OF {}: >>> # You can also iterate through the
you want to know more! file line by line:
{}'.format(folder_name, subfolder))
>>> for filename in filenames: Reading and Writing Files >>> with open('sonnet29.txt') as
sonnet_file:
>>> print('FILE INSIDE {}: The File Reading/Writing Process
{}'.format(folder_name, filename)) ... for line in sonnet_file: # note
the new line character will be included
To read/write to a file in Python, you will want to use
in the line
>>> the with statement, which will close the file for you
after you are done. ... print(line, end='')
>>> print('')
The current folder is C:\delicious Opening and reading files with the open() function
>>> with When, in disgrace with fortune and men's
SUBFOLDER OF C:\delicious: cats open('C:\\Users\\your_home_folder\\hello eyes,
.txt') as hello_file:
SUBFOLDER OF C:\delicious: walnut
I all alone beweep my outcast state,
... hello_content =
FILE INSIDE C:\delicious: spam.txt hello_file.read() And trouble deaf heaven with my bootless
cries,
>>> hello_content
And look upon myself and curse my fate,
The current folder is C:\delicious\cats 'Hello World!'
Ternary operators can be chained: def forward(f, *args, **kwargs): name: apple
Inside forward, args is a tuple (of all positional >>> def show(arg1, arg2, *args,
arguments except the first one, because we specified kwarg1=None, kwarg2=None, **kwargs):
>>> print('kid' if age < 13 else it - the f), kwargs is a dict. Then we call f and unpack
>>> print(arg1)
'teenager' if age < 18 else 'adult') them so they become normal arguments to f.
else:
>>> fruits("apples", "bananas", >>> data1 = [1,2,3]
print('teenager') "grapes")
>>> data2 = [4,5,6]
else:
>>> data3 = {'a':7,'b':8,'c':9}
print('adult') "apples"
It is easy to add default values to the fields of your ... name: Any
Features data class.
... value: Any = 42
1. They store data and represent a certain data >>> @dataclass
type. Ex: A number. For people familiar with ...
ORMs, a model instance is a data object. It ... class Product:
represents a specific kind of entity. It holds
Virtual Environment
attributes that define or represent the entity. ... name: str
2. They can be compared to other objects of The use of a Virtual Environment is to test python
the same type. Ex: A number can be greater ... count: int = 0 code in encapsulated environments and to also avoid
than, less than, or equal to another number. filling the base Python installation with libraries we
Python 3.7 provides a decorator dataclass that is used ... price: float = 0.0 might use for only one project.
to convert a class into a dataclass.
...
virtualenv
python 2.7
>>> obj = Product("Python")
1. Install virtualenv
>>> class Number:
>>> obj.name
2. pip install virtualenv
... def __init__(self, val):
Python 3. Install virtualenvwrapper-win (Windows)
conda deactivate