Exercise: Use control flow and loops to solve a problem - ibrahimrifats/Back-End-development GitHub Wiki
Instructions
-
Under the num_list create a new for loop and print out each value on the list in sequential order.
-
Inside the for loop, create a condition that will look for all numbers that are greater than 45 and print out only numbers that meet that condition
-
Change the print statement to “Over 45” and add an else condition with a print statement of “Under 45”.
-
Update the for loop to use the enumerate function so you can get and use the index. Alter the condition to look for number 36 and print out the following: ‘Number found at position: ‘, index number
-
Next, create a new variable called count and assign it a value of 0 and place it outside the for loop.
-
Inside the for loop increment the counter by 1.
-
Add a print statement outside the for loop to print the value of the count variable.
-
Finally, add a break statement directly after the print statement inside the if condition for finding the number.
Step 1
num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11] for num in num_list: print(num)
step 2
num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11] for num in num_list: if num > 45: print(num)
step 3
num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11] for num in num_list: if num > 45: print('Over 45') else: print('Under 45')
step 4
num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11] for x,num in enumerate(num_list): if num == 36: print('Number found at ', x)
step 5,6,7
num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11] count = 0 for x,num in enumerate(num_list): count += 1 if num == 36: print('Number found at ', x) print(count)
step 8
num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11] count = 0 for x,num in enumerate(num_list): count += 1 if num == 36: print('Number found at ', x) break print(count)