Python Programming quick reference



Strings:

#string concatenation

>>> first_name = 'Yu'
>>> last_name = 'Zhang'
>>> full_name = first_name + ' ' + last_name
>>> print(full_name)
Yu Zhang

#string repetition

>>> print(5*'-' + 'hello world' + 5*'-')
-----hello world-----

#string indexing(positive + negative indice)

>>> full_name
'Yu Zhang'
>>> full_name[1]
'u'
>>> full_name[-1]
'g'

#string slicing(range, instead of a single character)
#[beginning index: ending index]
#element referenced by beginning index is always included
#element referenced by ending index is always excluded
#to get the end, leave ending index blank

>>> full_name[3:]
'Zhang'
>>> full_name[3:7]
'Zhan'

#Python stings are immutable, meaning they cannot be changed

>>> full_name[2] = 'j'
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    full_name[2] = 'j'
TypeError: 'str' object does not support item assignment

# use built-in function len() to get the length of the string

>>> print('The length of full_name is ' + str(len(full_name)))
The length of full_name is 8




Lists:

#lists can be indexed and sliced

>>> scores = [65, 77, 58, 100, 99]

#index into a particular index, returns element at that index

>>> scores[0]
65

#since ending index is always excluded, the returned list only includes one element: 77
#notice the square brackets surrounding '77', slice operation always return a new list

>>> scores[1:2]
[77]
>>> scores[1:4]
[77, 58, 100]
>>> scores[1:]
[77, 58, 100, 99]

#lists also support concatenation
#notice this generate a new list
#but since we do not assign it back to scores, the content of scores remain untouched

>>> scores + [55, 56, 57, 58]
[65, 77, 58, 100, 99, 55, 56, 57, 58]
>>> print(scores)
[65, 77, 58, 100, 99]

#Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content

>>> scores[0] = 100
>>> scores[1] = 100
>>> print(scores)
[100, 100, 58, 100, 99]

#assignment to slices can update the values of elements, change the size of the list and even empty the list

>>> scores[0:4] = [80, 80, 80, 80]
>>> print(scores)
[80, 80, 80, 80, 99]
>>> scores[0:4] = []
>>> print(scores)
[99]
>>> scores[0:] = []
>>> print(scores)
[]

#The built-in function len() also applies to lists:

Lists:

#lists can be indexed and sliced

>>> scores = [65, 77, 58, 100, 99]

#index into a particular index, returns element at that index

>>> scores[0]
65

#since ending index is always excluded, the returned list only includes one element: 77
#notice the square brackets surrounding '77', slice operation always return a new list

>>> scores[1:2]
[77]
>>> scores[1:4]
[77, 58, 100]
>>> scores[1:]
[77, 58, 100, 99]

#lists also support concatenation
#notice this generate a new list
#but since we do not assign it back to scores, the content of scores remain untouched

>>> scores + [55, 56, 57, 58]
[65, 77, 58, 100, 99, 55, 56, 57, 58]
>>> print(scores)
[65, 77, 58, 100, 99]

#Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content

>>> scores[0] = 100
>>> scores[1] = 100
>>> print(scores)
[100, 100, 58, 100, 99]

#assignment to slices can update the values of elements, change the size of the list and even empty the list

>>> scores[0:4] = [80, 80, 80, 80]
>>> print(scores)
[80, 80, 80, 80, 99]
>>> scores[0:4] = []
>>> print(scores)
[99]
>>> scores[0:] = []
>>> print(scores)
[]

#The built-in function len() also applies to lists:

>>> print('The length of list scores is ' + str(len(scores)))
The length of list scores is 0


Functions:

#define a new function using keyword def

>>> def print_intro(my_name):
          print('Hello, everyone')
          print('My name is ' + my_name)
          print('I am learning Python')

#call the function, pass in parameter

>>> print_intro('Jason')
Hello, everyone
My name is Jason
I am learning Python

#use 'return' statement to return values, by default it returns 'NONE'

>>> def print_intro(my_name):
          print('Hello, everyone')
          print('My name is ' + my_name)
          print('I am learning Python')
          return 3
>>> num_printed_lines = print_intro('Hi')
Hello, everyone
My name is Hi
I am learning Python
>>> print(num_printed_lines)
3

#default argument values

>>> def print_msg(msg='Hello world'):
         print(msg)
>>> print_msg()
Hello world
>>> print_msg('My name is Jason')
My name is Jason

#TODO: add keyword arguments

#lambda expressions

f points to an anonymous function that has input x and returns x+10 
>>> f = lambda x:x+10
>>> f(1)
11

we can also have a function that generates anonymous functions based on input

>>> def gen_lambda(n):
    return lambda a:a*n
>>> f = gen_lambda(10)
#f now points to a function that multiplies input by 10
>>> f(1)
10
>>> f(2)
20
>>> f = gen_lambda(100)
#f now points to a function that multiplies input by 100
>>> f(1)
100
>>> f(2)
200

Starting with Python 2.4, both list.sort() added a key parameter to specify a function to be called on each list element prior to making comparisons.
lambda pair: pair[1] returns a function that takes a pair and returns the second element in the pair
So here it sorts based on the second element of all the pairs in that list
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]


if Statement:

#if, elif, else
>>> def check_number(num):
         if num < 0:
             print('negative')
         elif num == 0:
             print('zero')
         else:
             print('positive')
>>> check_number(-1)
negative
>>> check_number(0)
zero
>>> check_number(100)
positive

for Statement:

>>> names = ['Jason', 'Yu', 'David', 'Nick']
>>> for student_name in names:
    print(student_name)
Jason
Yu
David
Nick

#loop through a slice of a list

>>> for student_name in names[1:3]:
    print(student_name)
Yu
David

The range function:


>>> for i in range(5):
    print(i)
0
1
2
3
4

>>> names
['Jason', 'Yu', 'David', 'Nick']
>>> for i in range(len(names)):
    print(i,names[i])
0 Jason
1 Yu
2 David
3 Nick


Comments

Popular Posts