Homework01
Homework01
When you wanna to calcute how many items(elements) in the List or String
data = [1,3,5,7]
hello = 'hello'
n = len(data)
m = len(hello)
print('length of data: ', n) #4, four eles in the variable of data
print('length of hello: ', m) #5, five letter in the variable of hello
1.2 max()
When you wanna get the biggest num form List or two variable
data = [7, 2, 5, 9, 1]
print('the biggest num of data is :', max(data))
a = 10
b = 15
print('the biggest num from a and b is :', max(a, b))
1.3 input()
Tips: the data type of input from console always String , Don't forget to convert to the appropriate data
type, such as integer.
For example, split the input string by specific letter ',' , and convert the string number to float number
one by one based on for loop
This function is usually used with for loop and len() function to traversal the element by index from
List or String
data = [1, 3, 5, 7]
for i in range(len(data)):
print(i, data[i])
hello = 'hello'
for j in range(len(hello)):
print(j, hello[j])
# Do not forget use list function converting the data type to list
# including the start, excluding the end
a = list(range(5)) # range(start=0,end=5,step=1) => [0,1,2,3,4]
b = list(range(3, 5)) # range(start=3,end=5,step=1 =>[3,4]
c = list(range(3, 10, 2)) # range(start=3,end=10,step=2 =>[3,5,7,9]
print(a)
print(b)
print(c)
Keep in your mind, how to control the Loop by using the key word of continue and break or return
The continue is used when you wanna to skip the current loop
The break or return is used to terminate the whole loop, jump out of the whole loop.
2. Try to analysis the output to fully understand the contine and break .
3. Detect the num either odd num or even, we use the num mod (%) 2 to verify it.
for i in range(10):
if i > 7:
break
if i == 5 or i == 3:
continue
if i % 2 == 0:
print('the num={} is odd'.format(i))
else:
print('the num={} is even'.format(i))
3. Challenge
Do not search the answer from online or ask ChatGPT !!!
Try to think by yourself, or discuss your idea with your friends or classmates!!!
Try to think by yourself, or discuss your idea with your friends or classmates!!!
Try to think by yourself, or discuss your idea with your friends or classmates!!!
3.1 Task1
Given the list of interger data , return the top2 biggest num which form a new list of [biggest_num,
second_biggest_num]
Example1
Example2
Example3
def get_top2_biggest_num(data=[]):
return xxx
3.2 Task2
Given the list of interge data , and a interger flag , if flag =1, then return the list which contains all
odd num, if flag =0, then return the list which contains all even num , otherwise, return the original list.
Example1
Example2
Example3