You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

16 KiB

Python cheatsheet

(non-complete, please use, modify, (re)publish!)

In [ ]:
 

string, integer, float

In [ ]:
x = '3'
y = 3
z = 3.5
In [ ]:
type(x)
In [ ]:
type(y)
In [ ]:
type(z)
In [ ]:
print(x * y) # Works
In [ ]:
print(x + y) # Does not work: TypeError
In [ ]:
# From int to str
str(y)
In [ ]:
# From str to int
int(x)
In [ ]:
# From float to int
int(z)
In [ ]:
 
In [ ]:
 
In [ ]:
 

string operations

In [11]:
s = 'hello!'
In [12]:
s.upper()
Out[12]:
'HELLO!'
In [13]:
s.lower()
Out[13]:
'hello!'
In [ ]:
s.capitalize()
In [ ]:
s.title()
In [15]:
s.replace('e', 'a')
Out[15]:
'hallo!'
In [ ]:
s.strip('!')
In [14]:
s.count('l')
Out[14]:
2
In [16]:
s.endswith('o')
Out[16]:
False
In [17]:
s.startswith('h')
Out[17]:
True
In [ ]:
# format a string
name = 'you'
t = 'hello {}'.format(name)
print(t)
In [ ]:
# format a string (different way of writing the same!)
name = 'you'
t = f'hello {name}'
print(t)
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 

loops

In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 

if/elif/else

In [18]:
# check if a word is in a list
words = ['hello', 'language', 'weaving']
word = 'quilting'
if word in words:
    print(f'{word} is in the list!')
else:
    print(f'{word} is NOT in the list!')
quilting is NOT in the list!
In [19]:
# check if a letter is in a word
words = ['hello', 'language', 'weaving']
letter = 'a'
for word in words:
    if letter in word:
        print(f'the letter "{letter}" is in the word "{word}"!')
    else:
        print(f'the letter "{letter}" is NOT in the word "{word}"!')
the letter "a" is NOT in the word "hello"!
the letter "a" is in the word "language"!
the letter "a" is in the word "weaving"!
In [22]:
# check if a word is in a sentence
sentences = [
    'Software and language are intrinsically related, since software may process language, and is constructed in language.', 
    'Yet language means different things in the context of computing: formal languages in which algorithms are expressed and software is implemented, and in so-called “natural” spoken languages.', 
    'There are at least two layers of formal language in software: programming language in which the software is written, and the language implemented within the software as its symbolic controls.'
]
word = 'programming'
for sentence in sentences:
    print('---')
    if word in sentence:
        print(f'YES, the word "{word}" is in the sentence "{sentence}"!')
    else:
        print(f'NO, the word "{word}" is NOT in the sentence "{sentence}"!')
---
NO, the word "programming" is NOT in the sentence "Software and language are intrinsically related, since software may process language, and is constructed in language."!
---
NO, the word "programming" is NOT in the sentence "Yet language means different things in the context of computing: formal languages in which algorithms are expressed and software is implemented, and in so-called “natural” spoken languages."!
---
YES, the word "programming" is in the sentence "There are at least two layers of formal language in software: programming language in which the software is written, and the language implemented within the software as its symbolic controls."!
In [23]:
# check if a word ends with "ing"
words = ['hello', 'language', 'weaving']
for word in words:
    if word.endswith('ing'):
        print(f'YES, the word "{word}" ends with "-ing"!')
    else:
        print(f'NO, the word "{word}" DOES NOT end with "-ing"!')
NO, the word "hello" DOES NOT end with "-ing"!
NO, the word "language" DOES NOT end with "-ing"!
YES, the word "weaving" ends with "-ing"!
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 

lists

In [ ]:
# Make an empty list
bag = []
In [ ]:
type(bag)
In [ ]:
# Add items to the list
word = 'hello'
bag.append(word)
print(bag)
In [ ]:
# From list to string
' --- '.join(bag)
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 

dictionaries

In [ ]:
# Make an empty dictionary
dict = {}
In [ ]:
dict['word'] = 10  
print(dict)
In [ ]:
dict.keys()
In [ ]:
 
In [ ]:
 
In [ ]:
 

open(), read(), write(), close()

mode can be:

  • r when the file will only be read
  • w for only writing (an existing file with the same name will be erased)
  • a opens the file for appending, any data written to the file is automatically added to the end
  • r+ opens the file for both reading and writing

(The mode argument is optional: r will be assumed if its omitted.)

In [ ]:
# open(), read()
txt = open('txt/language.txt', 'r').read()
print(txt)
In [ ]:
# readlines()
lines = open('txt/language.txt', 'r').readlines()
print(lines)
In [ ]:
# listdir() (open multiple files in a folder)
import os
folder = 'txt/words-for-the-future/'
for file in os.listdir(folder):
    print(folder+file)
    # txt = open(folder+file).read()
    # print(txt)
In [ ]:
# write() (returns a number, this is how many characters have been written to the file)
out = open('out.txt', 'w')
out.write('Hello!')
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]: