官术网_书友最值得收藏!

Iterative Functions

In the For Loops section in Chapter 1, Vital Python – Math, Strings, Conditionals, and Loops, you were introduced to the syntax for looping over objects in Python. As a refresher, here is an example where you perform five iterations and print the i variable in each loop:

for i in range(5):

    print(i)

You should get the following output:

0

1

2

3

4

For loops can also be placed within functions.

Exercise 48: A Simple Function with a for Loop

In this exercise, you create a sum_first_n function that sums up the first n integers. For example, if you pass the n=3 function, it should return 1 + 2 + 3 = 6:

  1. In a Python shell, enter the function definition. Note that the tab spacing needs to match the following output:

    def sum_first_n(n):

        result = 0

        for i in range(n):

            result += i + 1

        return result

       

  2. Test the sum_first_n function on an example:

    sum_first_n(100)

    You should get the following output:

    5050

In this exercise, you successfully implemented a simple sum_first_n function with a for loop to find the total sum of n numbers.

Exiting Early

You can exit the function at any point during the iterations. For instance, you might want the function to return a value once a certain condition is met.

Exercise 49: Exiting the Function During the for Loop

In this exercise, you will create a function that (inefficiently) checks whether a certain number x is a prime. The function does this by looping through all the numbers from 2 to x and checks whether x is divisible by it. If it finds a number that x is divisible by, the iteration will stop and return False, as it has ascertained that x is not prime:

  1. In a Python shell, enter the function definition. Note that the tab spacing needs to match the following output:

    def is_prime(x):

        for i in range(2, x):

            if (x % i) == 0:

            return False

        return True

  2. Test the function on a couple of examples:

    is_prime(7)

    You should get the following output:

    True

    Now, find out if 1000 is a prime number or not.

    is_prime(1000)

    You should get the following output:

    False

In this exercise, you successfully implemented a code that checks whether the x variable is prime by looping through numbers. In the case that it is divisible, it will exit the loop and provide the output as False.

Activity 10: The Fibonacci Function with an Iteration

You work in an IT firm, and your colleague has realized that being able to quickly compute elements of the Fibonacci sequence will reduce the time taken to execute the testing suite on one of your internal applications. You will use an iterative approach to create a fibonacci_iterative function that returns the nth value in the Fibonacci sequence.

The steps are as follows:

  1. Create a fibonacci.py file.
  2. Define a fibonacci_iterative function that takes a single positional argument representing which number term in the sequence you want to return.
  3. Run the following code:

    from fibonacci import fibonacci_iterative

    fibonacci_iterative(3)

    You should get the following output:

    2

    Another example to test your code can be as mentioned in the following code snippet:

    fibonacci_iterative(10)

    You should get the following output:

    55

    Note

    The solution for this activity is available on page 530.

主站蜘蛛池模板: 广汉市| 宜兰市| 商洛市| 吴江市| 宾阳县| 花莲市| 石家庄市| 全椒县| 邹城市| 永修县| 枝江市| 浦县| 黔江区| 荔波县| 丰宁| 富民县| 衡阳市| 汤原县| 綦江县| 襄垣县| 新竹市| 临颍县| 明溪县| 黑水县| 恩平市| 弋阳县| 延边| 江西省| 西丰县| 西吉县| 古丈县| 新巴尔虎左旗| 高唐县| 汝州市| 伊宁县| 弋阳县| 潮安县| 清涧县| 闽清县| 黄山市| 寿光市|