python3
last edited Wed, 24 Jul 2024 05:21:40 GMT
backlinks: null
Syntax Basics direct link to this section
operators direct link to this section
Exponent 2 ** 3
= 8
Modulus 22 % 8
= 6
Integer Division 22 // 8
= 2
Division 22 / 8
= 2.75
Multiplication 3 * 5
= 15
Subtraction 5 - 2
Addition 2 + 2
string concatenation direct link to this section
'alice' + 'bob'
= 'alicebob'
- you can't concatenate integer values with string values without converting values
string replication direct link to this section
'alice' * 5*
= 'alicealicealicealicealice'
comments direct link to this section
# this is a comment
essential functions direct link to this section
print('What is your name?') # ask for their name
myName = input()
stored as string according to user input
- may give errors with pytho n 2 as string not defined
print(len(myName))
evaluates the integer value of the number of characters in a string>>> str(29)
='29'
str() converts int to string, useful for concatenation int() convert string value to an integerspam = int(spam)
note: an integer can be equal to a floating point
Flow Control direct link to this section
blocks are denoted by indentation **if-else **
if name == 'Alice':
print('Hi, Alice.')
else:
print('Hello, stranger.')
- An else statement doesn’t have a condition
- ensures one clause is executed
else if
- follows an
if
orelif
statement - provides another condition that is checked only if all of the previous conditions were False
- order matters!
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
- the rest of the elif clauses are automatically skipped once a True condition has been found while loop
spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
break keyword allows to break out of while clause early
continue execution jumps to the start of the loop, re-evaluates condition
for loop
used with the range()
function
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')
range() function
The first argument is where the for
loop's variable starts, the second will be up to the number to stop at.
for i in range(12, 16):
print(i)
In this example the third argument will be the step argument. The amount the variable increases by through each iteration.
for i in range(0, 10, 2):
print(i)
range func accepts negative arguments to count down instead of up importing modules
import random, sys, os, math
Functions direct link to this section
defining a function
def hello(name):
print('Hello, ' + name)
hello('Alice')
hello('Bob')
Functions with Parameters
def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression
None keyword
- only
NoneType
data type - useful since all function calls must evaluate to a return value
- Python adds return None to the end of any function definition with no return statement
global statement
- modify a global variable from within a function
- eggs refers to the global variable
def spam():
global eggs
eggs = 'spam'
eggs = 'global'
spam()
print(eggs)
exception handling
- program execution moves to the start of a following
except
clause if an error happens
def spam(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print('Error: Invalid argument.')
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
Lists direct link to this section
you will get an IndexError error message if you use an index that exceeds the number of values in your list value.
for loops with lists
for i in [0, 1, 2, 3]:
print(i)
in and not in Operators
>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']
True
tuple unpacking
>>> cat = ['fat', 'gray', 'loud']
>>> >>> size, color, disposition = cat
Finding a Value in a List with the index() Method
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> spam.index('hello')
0
>>> spam.index('heyas')
3
Adding Values to Lists with the append() and insert() Methods
append()
adds new value to the end of a list
>>> spam = ['cat', 'dog', 'bat']
>>> spam.append('moose')
>>> spam
['cat', 'dog', 'bat', 'moose']
- the
insert()
method can insert a value at any index in the list - the first argument is the index for the new value, and the second argument is the new value to be inserted
>>> spam = ['cat', 'dog', 'bat']
>>> spam.insert(1, 'chicken')
>>> spam
['cat', 'chicken', 'dog', 'bat']
Removing Values from Lists with the remove() Method
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('bat')
>>> spam
['cat', 'rat', 'elephant']
Sorting the Values in a List with the sort() Method
you cannot sort lists that have both number values and string values in them
>>> spam = [2, 5, 3.14, 1, -7]
>>> spam.sort()
>>> spam
[-7, 1, 2, 3.14, 5]
- can sort values in reverse
>>> spam.sort(reverse=True)
>>> spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']
- “ASCIIbetical order” rather than actual alphabetical order for sorting strings. This means uppercase letters come before lowercase letters
Reversing the Values in a List with the reverse() Method
>>> spam = ['cat', 'dog', 'moose']
>>> spam.reverse()
>>> spam
['moose', 'dog', 'cat']
The copy Module’s copy() and deepcopy() Functions direct link to this section
- If the list you need to copy contains lists, then use the
copy.deepcopy()
function instead ofcopy.copy()
. Thedeepcopy()
function will copy these inner lists as well
Dictionaries and Structuring Data direct link to this section
Manipulating Strings direct link to this section
Automating Tasks direct link to this section
Pattern Matching with Regular Expressions direct link to this section
regexes for short, are descriptions for a pattern of text
- you must import the packages to use regex functions
>>> import re
>>> phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
matching regex objects
- use the
search()
method
Input Validation direct link to this section
Reading and Writing Files direct link to this section
Organizing Files direct link to this section
Debugging direct link to this section
Web Scraping direct link to this section
Essential modules:
webbrowser
comes with base install, opens browser to page(s)requests
downloads files and web pagesbs4
HTML parserselenium
controls browser, can simulate mouse clicks
Working with Excel Spreadsheets direct link to this section
Working with Google Cheets direct link to this section
Working with PDF and Word Documents direct link to this section
Working with CSV Files and JSON Data direct link to this section
Keeping Time, Scheduling Tasks, and Launching Programs direct link to this section
Essential Modules:
- time
- datetime
time.time()
Unix Epoch returns the number of seconds since 12am January 1, 1970 as a float value.
time.ctime()
returns a string description that's human readable
time.sleep()
Useful for having a program pause. Takes the time to stay idle in seconds as an argument.
round()
Rounds a float to the precision specified. Takes the number to be rounded as an argument. There is an optional second argument representing how many digits after the decimal to round to. If no second argument is passed then the number is rounded to the nearest whole integer by default.
Sending Email and Text Messages direct link to this section
Manipulating Images direct link to this section
Controlling the Keyboard and Mouse With GUI Automation direct link to this section
Libraries direct link to this section
References direct link to this section
Automate the Boring Stuff with Python