Foundations of Python

You are currently auditing this course.
87 / 134

Break and Continue

We may have certain cases where we would like to skip the iteration or stop all further iterations and move ahead in the program.

break and 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 total as 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 try 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.

  • Remember whatever input we take from the user, it is in str format,
  • break and continue process on the innermost loops in case of nested loops.
INSTRUCTIONS
  • Define a function with the name special_func which takes an argument num
  • Initialize a variable total with value 0
  • Check if num is positive int.
  • If 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 num). 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'

  • if num is negative or if the type of num is not intthen return -10.

Sample Input:

  • special_func(12)

  • special_func(15)

  • special_func(-1)

  • special_func('abcd')

Sample Output:

  • 4

  • 24

  • -10

  • -10

See Answer

No hints are availble for this assesment

Loading comments...