0% found this document useful (0 votes)
16 views2 pages

Cheat Sheet

Uploaded by

yuchenpan10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views2 pages

Cheat Sheet

Uploaded by

yuchenpan10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Variables must start with _ or a letter

Exponent: ** Floor Division (division that rounds down): // Modulus (Remainder): %


Division returns a float x.split(char) takes x and breaks it up into a list on the char (optional)
import math
- math.ceil(x) rounds x up to the nearest integer
- math.floor(x) rounds x down to the nearest integer
- math.sqrt(x) returns square root of x
- math.exp(x) returns 2^x
- math.pow(x,y) returns x^y
for x in dict.keys(): go through keys
for x in dict: go through keys
for y in dict.values(): go through values
for x,y in dict.items(): go through keys are their values at the same time
with open(“hello.txt”, ‘w’) as f:
opens the file in write mode (overwrites previous data) and stores it in variable f
- ‘a’ - append does not overwrite previous data
- ‘r’ - read mode, default
CSV Files - import csv at the top of the file
with open(‘file.csv’, ‘r’) as f: the header to open the file and store it in a variable like text files
csv_reader = csv.reader(f) → required to properly read a csv file
csv_writer = csv.writer(f)

list.sort(key = sortFunction) while sortFunction tells us what to sort by


If no input, sort() sorts left to right in ascending order
To sort in reverse: list.sort(key = sortFunction, reverse = True)
dict.get(“c”, 4) → if key “c” is in dict, it will return the value of key “c”, else, it will return 4
- If dict.get(“c”) and “c” is not in dict, it will return a KeyError
ord() get you the character code while chr() is the reverse
with open('filename.txt', 'r') as file:
# Read the entire file content
content = file.read()
for line in file:
print(line)

# Open a file for writing (overwrites


existing content)
with open('filename.txt', 'w') as file:
file.write('Hello, world!\n')
# Append to an existing file
with open('filename.txt', 'a') as file:
file.write('This is appended text.\n')

import csv
with open('data.csv', 'r') as file:
csv_reader = csv.reader(file)
# Read header row (if exists)
header = next(csv_reader, None)
for row in csv_reader:
print(row)

import csv
# Open a CSV file for writing
with open('data.csv', 'w', newline='') as
file:
csv_writer = csv.writer(file)
csv_writer.writerow(['Name', 'Age'])
csv_writer.writerow(['Alice', 25])
csv_writer.writerow(['Bob', 30])

You might also like