python3

last edited Sat, 10 Feb 2024 15:04:05 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'

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

Flow Control direct link to this section

blocks are denoted by indentation **if-else **

if name == 'Alice': 
	print('Hi, Alice.') 
else: 
	print('Hello, stranger.')

else if

if name == 'Alice': 
	print('Hi, Alice.')
elif age < 12: 
	print('You are not Alice, kiddo.')
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

global statement

def spam():
	global eggs
	eggs = 'spam'
eggs = 'global' 
spam() 
print(eggs)

exception handling

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

>>> spam = ['cat', 'dog', 'bat'] 
>>> spam.append('moose') 
>>> spam 
['cat', 'dog', 'bat', 'moose']
>>> 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]
>>> spam.sort(reverse=True)
>>> spam 
['elephants', 'dogs', 'cats', 'badgers', 'ants']

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

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

>>> import re
>>> phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')

matching regex objects

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:

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.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