0% found this document useful (0 votes)
43 views

Crib Sheet Python: Continue

This document provides an overview of various Python concepts including data types, operators, strings, loops, functions, exceptions and standard library modules. It includes code snippets and examples demonstrating concepts like slicing strings, iterating over characters, converting between types, defining and calling functions, and using built-in functions from modules like math.

Uploaded by

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

Crib Sheet Python: Continue

This document provides an overview of various Python concepts including data types, operators, strings, loops, functions, exceptions and standard library modules. It includes code snippets and examples demonstrating concepts like slicing strings, iterating over characters, converting between types, defining and calling functions, and using built-in functions from modules like math.

Uploaded by

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

Crib Sheet Python

Boolean operators are [not, and, or] range(start,


In string concatenation, + does not add space; stop, step) returns a sequence of
and only
You can only compare two things of works on string to string integers from start(included; default is 0) to
the same type. stop(excluded) in increments by step (default is 1).
Parentheses -> Arithmetic-> The comma does add space by default and works for all.
Comparison-> Boolean for i in range(1,11):
Use parentheses to make things IndexError, ZeroDivisonError, TypeError, NameError,
clear SyntaxError if(i==5):

break continue
len(s) returns how many characters in a string s
if __name__ == "__main__":
doctest.testmod() print(I, end = “ “)
you can access a character in a string s with s[i] where i is the index of the
character (starts from 0 and the range is (-len(s) to len(s)-1)
Output: 1 2 3 4
-len(i) is the index len(s)-i
1 2 3 4 6 7 8 9 10
To select a slice we do s[first:second:step] first(inc) second(exc) with a step of 1

If no first, slice starts at beginning Escape sequences

If no second, slice ends at end of string >>>print(“\”Hello\””)

If no step, default is 1 “Hello”


s[::2] contains every other character
>>>print(“\tHello”)
we get the reverse of a string with s[::-1]
Hello
s.lower(); s.upper() ; s.replace(old,new); s.count(c) returns nonoverlap of c in s;
s.find(c, start,end) returns index of first c in s >>>print(“Yo whats\nup”)

s = 'bananas' Yo whats
for char in s:
up
if char == 'a':

continue int(x) converts value of x to integer (just cuts


the decimal parts off)
print(char, end = ' ')
>>> s = print("INDENT!")
Output: b n n s float(x) converts to float
INDENT!
for index, char in enumerate(s): str(x) converts to string
>>> print("value is", s)
print(char, "has index", index, end = ' ') int(s, base) converts string to int (which is base
value is None 10) and the base specifies what base the string
import doctest is in
>>> print("type is", type(s))
# a function that takes two integers as input round(x, n) rounds x to n digits
# x and y and returns the sum of the numbers type is <class 'NoneType'>
# included between x and y (both included) >>>type(4)
def get_sum(x, y):
<class ‘int’>
sum = 0

# iterate through all the numbers between x and y


# and add them to the sum
for n in range(x, y + 1):
sum += n

return sum

def is_a_vowel(c):
vowels = 'aeiou'
return len(c) == 1 and c in vowels

def only_vowels(s):

# iterate through the characters of s and check if


# there is one that is not a vowel
for c in s:
if not is_a_vowel(c):
return False

return len(s) > 0


Void functions -> return no value

def greetings():

type(greetings) is <class ‘function’>

import math
def get_substring(s, i, j):
if i < 0 or j < 0 or i >= len(s) or j >= len(s): def greatest_common_divisor(x, y):
then you need to use math.sin(90)
return '' while x != y:
from math import * if x > y:
# A possible solution is to use slicing: x=x-y
# return s[i
then: j +you
1] can use sin(90) else:
y=y-x
# otheriwise
importusemath
a loopas m
substring = '' return x
for indexthen
in range(i, j+1):to use m.sin(90)
you need
substring += s[index] def least_common_multiple(x, y):

return substring
product = abs(x * y)

input() is always returned as a string lcm = product // greatest_common_divisor(x, y)


return lcm
import random
Mathematical operators (need import math)
random.random() will return random float from
0(inclusive) to 1(exclusive). ** is exponent

random.randint(a, b) will return integer from a to / is divison


b (both inclusive).
// finds the quotient

% finds the remainder (mod)

math.fabs(-2) gives the absolute value (float)

pow(x,y) is built in and gives x**y; abs(x) is built


in

def chocolate_bag(small, big, goal_in_kg): def count_occurrences(s, c):


""" if len(c) != 1:
(int, int, int) -> int return
# if we don't specify a value, None is returned
small: the number of chocolate bars of 1kg s = s.lower()
big: the number of chocolate bars of 5 kg c = c.lower()
wanted_kgs: how many kgs of chocolate we want count = 0
if car == c:
Returns the number of 1kg bars needed to reach goal_in_kg count += 1
To convert 5710 in binary kgs of chocolate. return count
Assuming
57/2 = 28R1 ; 28/2 = 14R0; 14/2 = 7R0; 7/2 = 3R1; we use
3/2 = 1R1; 1/2as= many
0R1 big bars as possible to reach the
goal. def remove_duplicates(s):
Go backwards so -> 111001 Returns -1 if the goal cannot be achieve.
no_duplicates = ""
To convert a number into hex do the same but divide by 16, 5 for base 5
>>> chocolate_bag(4, 1, 9)
To convert from 111001 2 to decimal 4 # iterate through the characters in s and decide whether to add them
>>> chocolate_bag(4, 1, 10) # or not to the string no_duplicates
1.25+1.24+1.23+0.22+0.21+1.20 = 57 -1 for c in s:
import turtle
import math

def polygon(t, length, n):


"""
(Turtle) -> None

draws a n-sided polygon with sides


of size length. t is a Turtle
"""
# interior angle = 180 - 360/n
# this is the angle the turtle needs to turn at each iteration
# to draw a polygon
angle = 360/n

# iterate for a number of times equal to the number of sides


the turtle
# needs to draw
for i in range(n):
t.fd(length)
t.left(angle)

def print_mult_table(rows, cols):


def circle(t, r): # iterate through all the rows
""" for r in range(1, rows + 1):
(Turtle, float) -> None # display row r by iterating through the columns
for c in range(1, cols + 1):
the Turtle t draws a circle of radius r # display all multiples of r on the same line
""" print(r * c, end = "\t")
# we want to use polygon() from this
function. We need to figure out # go on a new line to be ready for the next row
# how many sides we want based on a print()
length we fix.
# We need: length * n = circumference
def print_squared_table(n):
circ = 2 * math.pi * r
length = 10
n = int(circ / length) # iterate through all the rows
for row in range(1, n + 1):
# call polygon # display row by iterating through the columns
polygon(t, length, n) # the number of columns changes depending on
# which row we want to display
for col in range(1, row + 1):
print(row * col, end = "\t")

# go on a new line to be ready for the next row


print()

You might also like