Flash Sale: Flat 70% + Addl. 25% Off on all Courses | Use Coupon DS25 in Checkout | Offer Expires InEnroll Now
We may have certain cases where we would like to skip the iteration or stop all further iterations and move ahead in the program.
continue statements help us fulfill that purpose as well. In the last exercise, we returned the sum of all integers up to the number passed to the function as an argument. Suppose, if we would like to calculate the sum of all numbers input by the user. In this case,
If we take the input one by one, we can give the option to the user to end the process when he/she is done with inputting all the numbers.
total = 0 while True: n = input("Enter 1 to enter a number, Enter 2 to stop the process\n") if n is "1": number = input("Enter the number\n") try: total = total + int(number) except: print("Please enter a valid number\n") continue elif n is "2": break else: print("Please enter a valid choice\n") continue
Here, we initialized the
0 and then there is a
while statement whose condition will always be
True (infinite loop). We give the option to the user at every iteration, whether to enter a new number or to stop entering the numbers.
If the user enters
1, we ask to enter the number. We take the precaution using
except statements to check whether the input given by the user is a valid number or not. If it is a valid number we add it to the sum, else we ask to enter a valid number. The
continue stops that iteration there and goes to the next iteration.
If the user enters
2 we use
break statement to stop the complete loop and the flow goes out.
If the user enters anything other than given choices we ask to enter a valid choice.
continueprocess on the innermost loops in case of nested loops.
special_funcwhich takes an argument
num is positive int, find out all the factors of that number and return the sum of odd factors i.e.
total of all factors which are odd.
(Factors are the numbers you multiply together to get the number equal to
For example, the factors of 24 are 1, 2, 3, 4, 6, 8, 12 and 24. Out of which only 1 and 3 are odd , So the
total(sum of odd factors) here should be '4'
num is negative or if the type of
num is not
No hints are availble for this assesment
Answer is not availble for this assesment
Note - Having trouble with the assessment engine? Follow the steps listed here