An Intro to Python Benefits
- High level language, with a variety of complex data types built in
- Short syntax, readability focused
- Allows programs to be split into re-usable modules
- Is an interpreted language (not needing compilation and executed on the fly by the interpreter)
- Extensible: easy to add new modules, etc.
- Named after Monty Python
Numbers Intro
- Most common types: int, float
- Whole nums typed to ints
- Fractions typed to floats, includes results of int division ending in fractions
- Division, even when resulting in a whole num types to a float
- Any math operations on a float, int combo will return float
Numbers Intro
- Standard math operators: /, +, *, etc.
- Floor division: //
- Assign to variable: varName = value
- Power: **
>>> 10 ** 2
100
- Can reference last output in Python interpreter terminal via _
>>> tax = 10
>>> 10 + tax
20
>>> 20 + _
40
Strings
- Store in str objects
- Enclosed in either single or double quotes, using backslash to escape a “ or ‘
- Use single quotes for string literals
- Can wrap a pair of single quotes in double quotes, or double in single, but if wrapping same types, use backslash to escape inner pair. Same if quotes not in opening/closing pair.
- Concatenate: +
- If want to interpret string with \[reserved] as not reserved, preface string quotes with r
>>> print('C:\some\name') #here \n means newline!
C:\some
ame
>>> print(r'C:\some\name') #note the r before the quote
C:\some\name
- String literals (strings enclosed in quotes) next to each other (including across lines) auto-concat
‘string’ ‘string’ auto concats to ‘stringstring’
- Can repeat a string with: number * ‘stringHere’
‘string’ ‘string’ auto concats to ‘stringstring’
- Can pull out individual chars from string with stringName[num]. First letter is 0.
- To pull starting from end of string, use negative nums
- Python strings are immutable
String Methods of Interest
- String length: len(myString)
- Slice: myString[num:num] #inclusive 1st num, exclusive 2nd
-
- If omit num, will slice using start or/and end instead
- Can also slice starting from end with negative nums
- myString.capitalize() – uppercases first lettermyString.find(‘search’) – returns char index for first occurrence of myString or -1 if not found
- myString.find(‘search’) – returns char index for first occurrence of myString or -1 if not found
- myString.lower()
- myString.upper()
- myString.replace(‘old’, ‘new’)
- myString.split(‘deliminator’) - returns a list split by deliminator
Lists
- Initialize: fibs = [1, 1, 2, 3, 5, 8]
- Slice: myList[num:num] #inclusive 1st num, exclusive 2nd, same rules as string slice
- Slices, etc. return new lists, not mod existing lists
- Concat: myList + anotherList
- Can use slice to change parts of the list: myList[2:4] = [newElm1, newElem2, newElm3] will replace those indexes
- Length: len(myList)