Python Language Notes
- Lexical Analysis Keywords
- Operators and Builtin Functions
- All Types
- All Numeric Types
- abs(-1) # 1
- chr(65) #'A'
- ord('A')#65
- complex(1) #(1+0j)
- divmod(25,7) #(3,4) => (25//7, 25%7)
- pow(2,8) #256
- round(2.75,1) #2.8, rounds up
- Objects
- Classification
- Primative, Numeric, Sequence, Container: Can contain other types, Collection
- Common use cases
- Dictionaries for lookups
- Tuples for data that is invariant at runtime
- Lists for dynamic runtime data
- Primative Types
- bool -> True, False
- bool(float("NaN")) --> True
- bool(0.0) --> False
- bool(0) --> False
- bool([]) --> False
- int
- 2**31 - 1
- binary: 0b10 , bin(20) #'0b10100'
- octal: 0o77 , oct(20) #'0o24"
- hex: 0xFF , hex(20) #'0x14'
- int(3.5); int("3.5"); int("1111", 2) --> 15
- abs(-1)
- 1//3 #0, integer division
- float
- 1.41
- 3e-5
- float(3), float("3.14")
- float("nan"), float("inf"), float("-inf")
- round(1.234, 2)
- Complex
- Sequence (Builtin Functions) len(obj)
- character (char): ord(char) --> int
- strings In contrast to many other programming languages, there is no separate character type distinct from the string type.
- raw strings r'this is t raw'
- implicit concatantion "hello" "world"
- bytes b'this is a byte string' an immutable sequence of bytes
- bytearray
- tuple
- Lists
- Sorting Lists
- Numerical Lists use range() to generate a series of numberss.
- List Comprehensions A compact way of defining lists
- Generator Expressions use like list comprensions except use parenthesis instead
- dictionary {key:value} check whether a key is available 'key' in dict
- Set {1,2,3} each element is unique
- Frozenset
- Complex
- Modules and Packages
- Modules A module is a python file.
- Packages lets say you have a package called maps for map functionality. The folders structure may look like:
- Standard Library / Types
- math
- Fraction
- Decimal
- Date
- Array
- range
- Converstion Functions
- int, float, bool, str, tuple, list, dict, set
- chr(int) --> char
- Operators
- Function application function(args...)
- Indexing seq[index | range]
- Lookup (dictionaries) d[key]
- Expressions
- Rules for Well-formedness
- R1
- R2 (E)
- R3 <uop> E
- R4 E1 <bop> E2
- R5 E1[E2]
- R6 F(A, ...)
- R7 if O.f(E)
- Printing
- Functions A function is a named block of code. Lambda's produce anonymous functions.
- lambda
- def
- keyword
- Destructuring with Tuples Used for passing any number of positional arguments.
- Destructuring with Dictionaries
- destructuring with both
- Methods
- Magic Methods
- Some Builtins
- Testing
- Conditionals
- Sequence Operations
- Slicing start at first index, stop at item before last index
- Strings
- split
- for loops learn.txt
- Classes
- Creating Classes A class organises data and actions into one object. You can create instances of the class. An attribute is a variable associated with a class. A method is a function in the class.
- Inheritance
- User Input
name = input("what is your name? ")
name ::= lc_letter (lc_letter | "_")* lc_letter ::= "a"..."z"
type(obj) --> type object
isinstance(obj, typ) --> bool
repr(obj) #evaluatable representation
str(obj) #printable representation
is, is not # are two objects the same
int, float, bool, dict, set, tuple, str, bytes Nonefunctions without return, return None
complex(2,3) #(2+3j)
help(str) >>> m = """This is ... a multiline ... string""" 'This isna multilinenstring' print(m) str(666) "Vi er så glad for å høre og lære om Python!" # 'Vi er så glad for å høre og lære om Python!' "Vi er su00e5 glad for u00e5 hxf8re og lu00e6re om Python!" ' #Vi er så glad for å høre og lære om Python!'Similarly, you can use the x escape sequence followed by a 2-character hexadecimal string to include one-byte Unicode code points in a string literal:
'\xe5' 'å'You can even use an escaped octal string using a single backlash followed by three digits in the range zero to seven, although we confess we’ve never seen this used in practice, except inadvertently as a bug:
'\345' 'å'some common methods and patterns
str.title(), str.upper(), str.lower, str.lstrip(), .rstrip, .strip var = 'in' print(f"I am {var} trouble!")f is short for format
b'this is a byte string'.split() [b'this', b'is', b'a', b'byte', b'string'] "Vi er så glad for ".encode('utf-8') b'Vi er sa\xcc\x8a glad for '.decode('utf-8')
(1,2) (False, 1, 'c') (2,) + (9,) => (2,9)
[1,2,3] [True, False, '7']
append(x), count(x), extend(L), index(x), insert(x), insert(i,x), pop(x), remove(x), reverse(), sort()
alist = [0, 1, 2, 3] del alist[2] #[0, 1, 3]copy a list by generating a new list using slice operations
mylist[:]
sorted() #generate a copy sort sorted(x, reverse=True) reverse()
list(range(5)) list(range(5,11)) nums = [] for exp in range(5): nums.append(2**exp)
[2**exp for exp in range(5)][i**3 for i in range(10) if True]
f = open("test.txt", 'r') data = [line.strip for line in f] f.close() # now process data
f = open("test.txt", 'r') data = (line.strip for line in f) #now process data before closing the file! f.close()
dict() => {} dict(one=1, two=2) => {'one': 1, 'two': 2}
states = { 'ca': 'California', 'il': 'Illinois', 'fl': 'florida', } states['ca'] states.get('xx', 'default value') # equivalant to: states['xx'] if 'xx' in states else 'default value' states.setdefault('xx', 'default value') #in not there set and return the key. states['ny'] = 'New York' del states['il'] states.values() #dict_values([...]), <class 'dict_values'> states.items() states.keys()
has_key(), keys(), values(), dict.items(), clear(), copy(), update(x), get(x,[y])key should be unique
s = set() s.add(1) s.add('foo') t = set() s | t #union of t & sSet Comprehensions are similar to list comps. just use curly brackets.
odd = {i for i in range(10) if i % 2}
import module import module as mod from module import specific_function
maps/ __init__.py cities.py navigation.py gpsdata.py__init__.py can be empty but is required. One imports it simply by:
import mapsyou can use a function inside navigation, for example, turn_right() like:
maps.navigation.turn_right()
import math math.sqrt(16) PI = math.pi math.sin(PI) math.log(1000, 10)
range(5)
-
Numeric
+ 1 * ** / // %
Bitwise
~ >> << & ^ |
Comparison1
< > <= >= <> != ==
Boolean
and, or, not
Sequence
<string | list> + <string | list> 'five' + 'four' <int> * <string | list> <obj> in <seq>
Operator Precedence | no. | operators | description | | 1 | f(...) | function application | | 2 | o[l] | index lookups | | 3 | o.f(...) | method call | | 4 | ** | exponentiation | | 5 | -N | sign change | | 6 | *,/,//,% | numeric | | 7 | +,- | numeric | | 8 | <, <=, ... | comparisons | | 9 | in, not in | membership | | 10 | not o | logical | | 11 | and 0 | logical | | 12 | or | logical |
Every Value is well formed
if E is well formed then (E) is well formed
<uop> is a unary operation if E, then <uop> E is well formed
<bop> is a binary operation if E1, E2, then E1 <bop> E2
if E1, E2, the E1[E2]
if F is a function with A, A1, A2, ... expressions then F(), F(A), F(A, A1), F(A, A1, A2), ...
if O, f, E, E1, ... then O.f(), O.f(E), O.f(E, E1), ...
print("hello", 'how') print("hello", end='') from pprint import * pprint(expressions)
lambda x: x
def f(x,y): return x + y
def h(): "hello" #This function returns None h() #None
def f(x=0, y=0): print("x = ", x, "y = ", y) return (x, y) f(x=1, 2) f() f(1)
def ff(*a): print("first = ", a[0], "Second = ", a[1]) return (len(a), a)
def fff(**a): print(a["first"]) return a
def g(*a,**b): return (a,b)
x+1 [is actually] x.__add__(1)Similarly we have the following:
__add__(self, y) # x + y __sub__(self, y) # x - y __mul__(self, y) # x * y __mod__(self, y) # x % y __neg__(self) # -x __eq__(self, y) # x == y __ge__(self, y) # x >= y __gt__(self, y) # x > y __lt__(self, y) # x < y __le__(self, y) # x <= y __ne__(self, y) # x != y __contains__(self,y) # y in x __getitem__(self, y) # x[y] __setitem__(self, i, y) # x[i] = y __hash__(self) # hash(x) __int__(self) # int(x) __iter__(self) # for y in x __len__(self) # len(x) __repr__(self) # repr(x) __str__(self) # str(x)
abs, min, max type len dir gives internal dictionary of names
Doctests test_sqrt.py """ >>> sqrt(4) 2.0 >>> sqrt(2) 1.4142135623730951 >>> sqrt(-1) 0+1j """ from sqrt import * if __name__ == "__main__": import doctest doctest.testmod() sqrt.py def sqrt(x): x**0.5
if expr: expr elif expr: expr else: True
while x: expr break;break - takes you out of the loop permanently. continues - takes you to the beginning of the loop again.
'0123456789'[1:5] [0,1,2,3,4,5,6,7,8,9][1:5]optional 3rd index gives step value. sequence[i;j;k]
s = "Python" s[::-1] #'nohtyP' s[::2] #'Pto'
'this.is.a.string'.split('.') ''.split(':')
cities = ["London", "New York", "Paris", "Oslo", "Helsinki"] for city in cities: print(city) colors = {'crimson': 0xdc143c, 'coral': 0xff7f50, 'teal': 0x008080} for color in colors: print(color, colors[color]) from urllib.request import urlopen def get_words(): with urlopen('http://thevikidtruth.com/5000/!download?-A1624') as story: story_words = [] for line in story: line_words = line.decode('utf-8').split() for word in line_words: story_words.append(word) for word in story_words: print(word) if __name__ == '__main__': get_words()
class Microphone(): """ A Documentation String """ def __init__(self, type, volume=50): #init method is self.type = type #called automatically self.volume = volume #self=current instance def record(self, input): """blah blah""" print(f"using {self.type} on {input}.")create an instance and use:
mic1 = Microphone('laffler') mic1.record(5)
class Condenser(Microphone): """documentation""" def __init__(self, type, volume=30): super().__init__(type, volume) self.power = True def record(self, input): if self.power == True: super().record(input) print(" And I have power") else: print("Please put on Power.")use it:
mic2 = Condenser('heavy') mic2.record(4) mic2.power
http://thevikidtruth.com/wiki/?python
06dec23 | admin |