""" Multiline strings can be written using three "s, and are often used as documentation. """
3
1 + 1 8 - 1 10 * 2 35 / 5
5 // 3 -5 // 3 5.0 // 3.0 -5.0 // 3.0
10.0 / 3
7 % 3
-7 % 3
2**3
1 + 3 * 2 (1 + 3) * 2
True False
not True not False
True and False False or True
True + True True * 8 False - 5
0 == False 1 == True 2 == True -5 != False
bool(0) bool(4) bool(-6) 0 and 2 -5 or 0
1 == 1 2 == 1
1 != 1 2 != 1
1 < 10 1 > 10 2 <= 2 2 >= 2
1 < 2 and 2 < 3 2 < 3 and 3 < 2
1 < 2 < 3 2 < 3 < 2
a = [1, 2, 3, 4] b = a b is a b == a b = [1, 2, 3, 4] b is a b == a
"This is a string." 'This is also a string.'
"Hello " + "world!"
"Hello " "world!"
"Hello world!"[0]
len("This is a string")
name = "Reiko" f"She said her name is {name}."
f"{name} is {len(name)} characters long."
None
"etc" is None None is None
bool(0) bool("") bool([]) bool({}) bool(())
print("I'm Python. Nice to meet you!")
print("Hello, World", end="!")
input_string_var = input("Enter some data: ")
some_var = 5 some_var
some_unknown_var
"yay!" if 0 > 1 else "nay!"
li = []
other_li = [4, 5, 6]
li.append(1) li.append(2) li.append(4) li.append(3)
li.pop()
li.append(3)
li[0]
li[-1]
li[4]
li[1:3] li[2:] li[:3] li[::2] li[::-1]
li2 = li[:]
del li[2]
li.remove(2) li.remove(2)
li.insert(1, 2)
li.index(2) li.index(4)
li + other_li
li.extend(other_li)
1 in li
len(li)
tup = (1, 2, 3) tup[0] tup[0] = 3
type((1)) type((1,)) type(())
len(tup) tup + (4, 5, 6) tup[:2] 2 in tup
a, b, c = (1, 2, 3)
a, *b, c = (1, 2, 3, 4)
d, e, f = 4, 5, 6
e, d = d, e
empty_dict = {}
filled_dict = {"one": 1, "two": 2, "three": 3}
invalid_dict = {[1,2,3]: "123"} valid_dict = {(1,2,3):[1,2,3]}
filled_dict["one"]
list(filled_dict.keys()) list(filled_dict.keys())
list(filled_dict.values()) list(filled_dict.values())
"one" in filled_dict 1 in filled_dict
filled_dict["four"]
filled_dict.get("one") filled_dict.get("four")
filled_dict.get("one", 4) filled_dict.get("four", 4)
filled_dict.setdefault("five", 5) filled_dict.setdefault("five", 6)
filled_dict.update({"four":4}) filled_dict["four"] = 4
del filled_dict["one"]
{'a': 1, **{'b': 2}} {'a': 1, **{'a': 2}}
empty_set = set()
some_set = {1, 1, 2, 2, 3, 4}
invalid_set = {[1], 1} valid_set = {(1,), 1}
filled_set = some_set filled_set.add(5)
filled_set.add(5)
other_set = {3, 4, 5, 6} filled_set & other_set
filled_set | other_set
{1, 2, 3, 4} - {2, 3, 5}
{1, 2, 3, 4} ^ {2, 3, 5}
{1, 2} >= {1, 2, 3}
{1, 2} <= {1, 2, 3}
2 in filled_set 10 in filled_set
filled_set = some_set.copy() filled_set is some_set
some_var = 5
if some_var > 10: print("some_var is totally bigger than 10.") elif some_var < 10: print("some_var is smaller than 10.") else: print("some_var is indeed 10.")
""" For loops iterate over lists prints: dog is a mammal cat is a mammal mouse is a mammal """ for animal in ["dog", "cat", "mouse"]: print("{} is a mammal".format(animal))
""" "range(number)" returns an iterable of numbers from zero to the given number prints: 0 1 2 3 """ for i in range(4): print(i)
""" "range(lower, upper)" returns an iterable of numbers from the lower number to the upper number prints: 4 5 6 7 """ for i in range(4, 8): print(i)
""" "range(lower, upper, step)" returns an iterable of numbers from the lower number to the upper number, while incrementing by step. If step is not indicated, the default value is 1. prints: 4 6 """ for i in range(4, 8, 2): print(i)
""" To loop over a list, and retrieve both the index and the value of each item in the list prints: 0 dog 1 cat 2 mouse """ animals = ["dog", "cat", "mouse"] for i, value in enumerate(animals): print(i, value)
""" While loops go until a condition is no longer met. prints: 0 1 2 3 """ x = 0 while x < 4: print(x) x += 1
try: raise IndexError("This is an index error") except IndexError as e: pass except (TypeError, NameError): pass else: print("All good!") finally: print("We can clean up resources here")
with open("myfile.txt") as f: for line in f: print(line)
contents = {"aa": 12, "bb": 21} with open("myfile1.txt", "w+") as file: file.write(str(contents))
with open("myfile2.txt", "w+") as file: file.write(json.dumps(contents))
with open('myfile1.txt', "r+") as file: contents = file.read() print(contents)
with open('myfile2.txt', "r+") as file: contents = json.load(file) print(contents)
filled_dict = {"one": 1, "two": 2, "three": 3} our_iterable = filled_dict.keys() print(our_iterable)
for i in our_iterable: print(i)
our_iterable[1]
our_iterator = iter(our_iterable)
next(our_iterator)
next(our_iterator) next(our_iterator)
next(our_iterator)
our_iterator = iter(our_iterable) for i in our_iterator: print(i)
list(our_iterable) list(our_iterator)
def add(x, y): print("x is {} and y is {}".format(x, y)) return x + y
add(5, 6)
add(y=6, x=5)
def varargs(*args): return args
varargs(1, 2, 3)
def keyword_args(**kwargs): return kwargs
keyword_args(big="foot", loch="ness")
def all_the_args(*args, **kwargs): print(args) print(kwargs) """ all_the_args(1, 2, a=3, b=4) prints: (1, 2) {"a": 3, "b": 4} """
args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} all_the_args(*args) all_the_args(**kwargs) all_the_args(*args, **kwargs)
def swap(x, y): return y, x
x = 1 y = 2 x, y = swap(x, y)
x = 5
def set_x(num): x = num print(x)
def set_global_x(num): global x print(x) x = num print(x)
set_x(43) set_global_x(6)
def create_adder(x): def adder(y): return x + y return adder
add_10 = create_adder(10) add_10(3)
(lambda x: x > 2)(3) (lambda x, y: x ** 2 + y ** 2)(2, 1)
list(map(add_10, [1, 2, 3])) list(map(max, [1, 2, 3], [4, 2, 1]))
list(filter(lambda x: x > 5, [3, 4, 5, 6, 7]))
[add_10(i) for i in [1, 2, 3]] [x for x in [3, 4, 5, 6, 7] if x > 5]
{x for x in 'abcddeef' if x not in 'abc'} {x: x**2 for x in range(5)}
import math print(math.sqrt(16))
from math import ceil, floor print(ceil(3.7)) print(floor(3.7))
from math import *
import math as m math.sqrt(16) == m.sqrt(16)
import math dir(math)
class Human:
species = "H. sapiens"
def __init__(self, name): self.name = name
self._age = 0
def say(self, msg): print("{name}: {message}".format(name=self.name, message=msg))
def sing(self): return 'yo... yo... microphone check... one two... one two...'
@classmethod def get_species(cls): return cls.species
@staticmethod def grunt(): return "*grunt*"
@property def age(self): return self._age
@age.setter def age(self, age): self._age = age
@age.deleter def age(self): del self._age
if __name__ == '__main__': i = Human(name="Ian") i.say("hi") j = Human("Joel") j.say("hello")
i.say(i.get_species()) Human.species = "H. neanderthalensis" i.say(i.get_species()) j.say(j.get_species())
print(Human.grunt())
print(i.grunt())
i.age = 42 i.say(i.age) j.say(j.age) del i.age
from human import Human
class Superhero(Human):
species = 'Superhuman'
def __init__(self, name, movie=False, superpowers=["super strength", "bulletproofing"]):
self.fictional = True self.movie = movie self.superpowers = superpowers
super().__init__(name)
def sing(self): return 'Dun, dun, DUN!'
def boast(self): for power in self.superpowers: print("I wield the power of {pow}!".format(pow=power))
if __name__ == '__main__': sup = Superhero(name="Tick")
if isinstance(sup, Human): print('I am human') if type(sup) is Superhero: print('I am a superhero')
print(Superhero.__mro__)
print(sup.get_species())
print(sup.sing())
sup.say('Spoon')
sup.boast()
sup.age = 31 print(sup.age)
print('Am I Oscar eligible? ' + str(sup.movie))
class Bat:
species = 'Baty'
def __init__(self, can_fly=True): self.fly = can_fly
def say(self, msg): msg = '... ... ...' return msg
def sonar(self): return '))) ... ((('
if __name__ == '__main__': b = Bat() print(b.say('hello')) print(b.fly)
from superhero import Superhero from bat import Bat
class Batman(Superhero, Bat):
def __init__(self, *args, **kwargs): Superhero.__init__(self, 'anonymous', movie=True, superpowers=['Wealthy'], *args, **kwargs) Bat.__init__(self, *args, can_fly=False, **kwargs) self.name = 'Sad Affleck'
def sing(self): return 'nan nan nan nan nan batman!'
if __name__ == '__main__': sup = Batman()
print(Batman.__mro__)
print(sup.get_species())
print(sup.sing())
sup.say('I agree')
print(sup.sonar())
sup.age = 100 print(sup.age)
print('Can I fly? ' + str(sup.fly))
def double_numbers(iterable): for i in iterable: yield i + i
for i in double_numbers(range(1, 900000000)): print(i) if i >= 30: break
values = (-x for x in [1,2,3,4,5]) for x in values: print(x)
values = (-x for x in [1,2,3,4,5]) gen_to_list = list(values) print(gen_to_list)
from functools import wraps
def beg(target_function): @wraps(target_function) def wrapper(*args, **kwargs): msg, say_please = target_function(*args, **kwargs) if say_please: return "{} {}".format(msg, "Please! I am poor :(") return msg
return wrapper
@beg def say(say_please=False): msg = "Can you buy me a beer?" return msg, say_please
print(say()) print(say(say_please=True))
|