Variable names
- Case-sensitive
- Can’t start with a number
- Can’t be a Python keyword
- OK—name, my_name, my_1st_name, name2
- Not OK—13_numbers, print
Strings
Description |
Operator |
Example |
Output |
---|---|---|---|
Equality | == | 'me' == 'ME' 'you' == 'you' | False True |
Inequality | != | 'me' != 'ME' 'you' != 'you' | True False |
Less than | < | 'A' < 'a' 'b' < 'a' | True False |
Less than or equal | <= | 'Z' <= 'a' 'a' <= 'a' | True True |
Greater than | > | 'a' > 'B' 'a' > 'z' | True False |
Greater than or equal | >= | 'a' >= 'a' 'a' >= 'z' | True False |
Contains | in | 'Go' in 'Gopher' 'py' in 'PYTHON' | True False |
Length | len | len('program') len('') | 7 0 |
String indexing for s = "Python Cheat Sheet"
Indexing/slicing |
Result |
---|---|
s[0] | 'P' |
s[-1] | 't' |
s[6] | ' ' |
s[2:10] | 'thon Che' |
s[7:15:2] | 'CetS' |
s[4:8:-1] | '' |
s[13:3:-2] | 'SteCn' |
s[::] | 'Python Cheat Sheet' |
s[::-1] | 'teehS taehC nohtyP' |
Lists for L = ['hello', 'hi', 'welcome']
Slice |
Result |
---|---|
Indexing/slicing | Same as for strings |
L[0][0] | 'h' |
len(L) | 3 |
L.append([]) | ['hello', 'hi', 'welcome', []] |
'hi' in L | True |
L[1] = 'bye' | ['hello', 'bye', 'welcome'] |
L.remove('welcome') | ['hello', 'hi'] |
- Immutable—integer, float, string, Boolean.
- Mutable—list, dictionary.
- Be careful about mutating while iterating.
- Keys can’t be mutable objects.
- Values can be mutable or immutable.
Get Get Programming