This is an optional exercise to test your understanding of Python Basics. If you find this extremely challenging, then you probably are not ready for the rest of this course yet and don’t have enough programming experience to continue. I would suggest you take another course more geared towards complete beginners, such as Complete Python Bootcamp

the testing code is stored at /User/johnny.lu/python3/PCCE

#### Exercise 1:

What is 7 to the power of 4?

``print(7**4)``

output: `2401`

#### Exercise 2:

Split the string
Here is a string: “Hi there Sam!”
split the string into each words into a list

``string = "Hi there Sam!"print(string.split())``

output: `['Hi', 'there', 'Sam!']`

A little introduction of the tool: “Split”

Split the binary sequence into subsequences of the same type, using sep as the delimiter string.
If maxsplit is given and non-negative, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements).
If maxsplit is not specified or is -1, then there is no limit on the number of splits (all possible splits are made).

如果给定了一个参数 maxsplit，且这个参数不是负数，分裂器至多会分裂出 maxsplit + 1 个元素
如果未给值，或者给了 -1作为值，那么就表示没有限制分裂数量（他会尽可能的分裂）

Example_1:

``temp_str = "Today is a good day."list_str = temp_str.split(' ')print(list_str)``

output: `['Today', 'is', 'a', 'good', 'day.']`

不难发现，这里打印的是一个列表。

Example_2:

``temp_str = "Today is a good day."print(temp_str.split(' ', maxsplit=2))``

output: `['Today', 'is', 'a good day.']`

Official Python3.7 document

The official Site

str.split(sep=None, maxsplit=-1)
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most `maxsplit+1` elements).If maxsplit is not specified or `-1` then there is no limit on the number of splits (all possible splits are made).

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `1,,2`.split(',')`returns `['1', '', '2']`The sep argument may consist of multiple characters (for example, `'1<>2<>3'.split('<>')` returns `['1', '2', '3']`) Splitting an empty string with a specified separator returns `['']`

For example:

``>>> '1,2,3'.split(',')['1', '2', '3']>>> '1,2,3'.split(',', maxsplit=1)['1', '2,3']>>> '1,2,,3,'.split(',')['1', '2', '', '3', '']``

If sep is not specified or is `None` a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a `None` separator returns `[]`

For Example:

``>>> '1 2 3'.split()['1', '2', '3']>>> '1 2 3'.split(maxsplit=1)['1', '2 3']>>> '   1   2   3   '.split()['1', '2', '3']``

#### Exercise 3:

Given the variables:

``planet = "Earth"diameter = 12742``

Use .format() to print the following string:

``The diameter of Earth is 12742 kilometers.``

Solution:

``planet = "Earth"diameter = 12742print("The diameter of {} is {} kilometers.".format(planet, diameter))#or, you can do it like that:print(f"The diameter of {planet} is {diameter} kilometers.")``

#### Exercise 4:

Given this nested list, use indexing to grab the word “hello”

``lst = [1,2,[3,4],[5,[100,200,['hello']],23,11],1,7]``

Solution:

``lst = [1,2,[3,4],[5,[100,200,['hello']],23,11],1,7]print(lst[3][1][2][0])``

#### Exercise 5:

Given this nested dictionary grab the word “Hello”.

`d = {'k1':[1,2,3,{'tricky':['oh','man','inception',{'target':[1,2,3,'hello']}]}]}`

Solution:
`print(d['k1'][3]["tricky"][3]['target'][3])`

#### Exercise 6:

What is the main difference between a Tuple and a List?

``t = (1, 2, 3)list = [1, 2, 3, 4, 5]'''tuple is immutable, and list is muutable元组是不能够修改的，然而列表可以无限制修改'''``

#### Exercise 7:

Create a function that grabs the email website domain from a string into the form:

for example, passing “user@domain.com” will return: domain.com

``def domainGet(email):    print("Your domain is: " + email.split('@')[-1])email = input("Please enter your email: >")domainGet(email)``

#### Exercise 8:

Create a basic function that returns True if the word ‘dog’ is contained in the input string. No need to worry about the edge cases

``def findDog(st):    if 'dog' in st.lower():        print("True")    else:        print("False")st = input("Please key a string: >")findDog(st)``

#### Exercise 9:

Create a function that counts the number of times the word “dog” occurs in a string. Again ignore edge cases.
solution:

``#-*- coding: utf-8 -*-#User/johnny.lu/Download/python3/PCCE/ex9.py'''**Create a function that counts the number of times the word "dog"occurs in a string. Again ignore edge cases.**'''string = input("Please enter your string: ")def countdogs(string):    count = 0    for word in string.lower().split():        if word == 'dog' or word == 'dogs':            count = count + 1            print(count)countdogs(string)``

#### Exercise 10:

Use lambda expressions and the filter() function to filter out words from a list that don’t start with the letter ‘s’. For example:

for example
`seq = ['soup','dog','salad','cat','great']`

should be filtered down to:
`['soup','salad']`

Solution

``seq = ['soup','dog','salad','cat','great']list(filter(lambda word: word[0]=='s',seq))``

#### About the “Lambda” and “map”:

see a pic of code:

``#-*- coding:utf-8 -*-#User/johnny.lu/python3/PCCEseq = [1,2,3,4,5,6,7,8,9,10]def times2(var):    return var*2print(list(map(times2, seq)))t = lambda var: var*2print(t(5))print(list(map(lambda num: num*3, seq)))``

The output:

``➜  PCCE python3 ex10_pre.py[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]10[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]➜  PCCE``

``def times(var):    print(var*2)var = input("Please input the var: ")times(var)``
``➜  PCCE python3 ex9.pyPlease input the var: >222``

hmmmmm……not correct right? so what’s wrong?
see below:

``def times(var):    print(var*2)num = input("Please input the var: >")var = int(num)times(var)``
``➜  PCCE python3 ex9.pyPlease input the var: >24``

because:
`var = input("Please input the var: ")`

now the ‘var’ is string, not a number, so when it put into the function, it will double the string, so, string’2', double it, become ‘22’
what we need to do it convert this string into integer:

``num = input("Please input the var: >")var = int(num)``

aha, done.

#### Final Problem:

You are driving a little too fast, and a police officer stops you. Write a function to return one of 3 possible results: “No ticket”, “Small ticket”, or “Big Ticket”. If your speed is 60 or less, the result is “No Ticket”. If speed is between 61 and 80 inclusive, the result is “Small Ticket”. If speed is 81 or more, the result is “Big Ticket”. Unless it is your birthday (encoded as a boolean value in the parameters of the function) — on your birthday, your speed can be 5 higher in all cases.

Solution:

``#-*- coding:utf-8 -*-#/User/johnny.lu/python3/PCCE/final_problem.pyprint("Please enter the speed(km/h)(only number please): \n")speed = int(input("> "))print("Please enter your birthday: (in DD/MM/YYYY format)\n")birthday = str(input("> "))def speeding(speed, birthday):    if birthday == '29/08/1989':        s = speed - 5    else:        s = speed    if s <= 60:        print("You pass.")    elif s > 61 and s <= 80:        print("You get a small ticket")    else:        print("You get a big ticket.")speeding(speed, birthday)``

Output

``➜  PCCE python3 final_problem.pyPlease enter the speed(km/h)(only number please):> 100Please enter your birthday: (in DD/MM/YYYY format)> 25/04/1964You get a big ticket.➜  PCCE python3 final_problem.pyPlease enter the speed(km/h)(only number please):> 80Please enter your birthday: (in DD/MM/YYYY format)> 18/08/1986You get a small ticket➜  PCCE``