Get started quickly with Python programming - automate tedious work Chapter 3 Function Exercises and Answers

Chapter 3 Function Exercises and Answers

1. Why is it beneficial to add functions to a program?

A: Functions reduce repetitive code. This makes programs shorter, easier to read, and easier to modify.

2. When does the code in the function execute: when the function is defined, or when the function is called?

Answer: Code in a function is executed when the function is called, not when the function is defined.

3. What statement creates a function?

Answer: The def statement defines (creates) a function.

4. What is the difference between a function and a function call?

Answer: Functions contain def statements and code in def clauses. A function call lets program execution go inside a function, and the function call evaluates to the return value of that function.

5. How many global scopes are there in a Python program? How many local scopes are there?

Answer: When a function is called, a global function and a local scope are created.

6. When the function call returns, what happens to the variables in the local scope?

Answer: When the function returns, the local scope is destroyed and all variables in it are forgotten.

7. What is the return value? Can the return value be part of an expression?

Answer: The result of function call evaluation when returning a value. Like all values, the return value can be part of an expression.

8. If a function has no return statement, what is the return value of a call to it?

Answer: If the function has no return statement, its return value is None.

9. How to force a variable in a function to refer to a global variable?

Answer: The global statement forces a variable in the function to reference the global variable.

10. What is the data type of None?

Answer: The data type of None is None Type.

11. What does the import areallyourpetsnamederic statement do?

A: The import statement imports the areallyourpetsnamederic module (which is not a real Python module by the way).

12. If there is a function named bacon() in a module named spam, how to call it after span is introduced?

Answer: This function can be called by spam.bacon().

13. How to prevent the program from crashing when encountering an error?

A: Put lines of code that could cause errors in a try clause.

14. What happens in the try clause? What happens in the except clause?

Answer: Code that can cause errors is placed in a try clause. When an error occurs, the code to be executed is placed in the except clause.

 

3.11 Practice Project As a practice, write a program to complete the following tasks

3.11.1 Collatz sequences

    Write a function called collatz() that has a parameter called number. If the argument is even, then collatz() prints number//2
and returns that value. If number is odd, collatz() prints and returns 3*number + 1
    Then write a program that lets the user enter an integer and keeps calling collatz() on that number until the function returns 1 (surprisingly, This sequence
is valid for any integer, and with this sequence you will get 1 sooner or later! Even mathematicians can't be sure why. Your program is working on what is called a "Collatz sequence",
which is sometimes later called "the simplest, impossible math problem").
    Remember to convert the return value of input() to an integer using the int function, otherwise it will be a string.
Hint: If number % 2 == 0, the integer number is even. If number % 2 == 1, it is odd.
answer:

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Author: davie
"""
    Write a function called collatz() that has a parameter called number. If the argument is even, then collatz() prints number//2,
and return that value. If number is odd, collatz() prints and returns 3*number + 1
    Then write a program that lets the user input an integer and keeps calling collatz() on that number until the function returns a value of 1 (amazingly, this sequence
Valid for any integer, with this sequence you'll get 1 sooner or later! Even mathematicians can't be sure why. Your program is studying so-called "Collatz sequences",
It is sometimes later called "the easiest, impossible math problem").
    Remember to convert the return value of input() to an integer using the int function, otherwise it will be a string.
Hint: If number % 2 == 0, the integer number is even. If number % 2 == 1, it is odd.
"""
def collatz(number):
    if number == 1:
        return 1
    elif number % 2 == 0:
        return number // 2
    elif number % 2 == 1:
        return 3*number + 1
print(collatz(18))
print(collatz(17))

3.11.2 Input validation

    Add try and except statements to the previous project to check if the user has entered a non-integer string. Under normal circumstances, the int() function will generate a ValueError when a non-integer string is passed in, such as int('puppy'). In the execpt clause, output a message to the user telling them that they must enter an integer.

answer:

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Author: davie
"""
    Write a function called collatz() that has a parameter called number. If the argument is even, then collatz() prints number//2,
and return that value. If number is odd, collatz() prints and returns 3*number + 1
    Then write a program that lets the user input an integer and keeps calling collatz() on that number until the function returns a value of 1 (amazingly, this sequence
Valid for any integer, with this sequence you'll get 1 sooner or later! Even mathematicians can't be sure why. Your program is studying so-called "Collatz sequences",
It is sometimes later called "the easiest, impossible math problem").
    Remember to convert the return value of input() to an integer using the int function, otherwise it will be a string.
Hint: If number % 2 == 0, the integer number is even. If number % 2 == 1, it is odd.
"""
def collatz(number):
    if number == 1:
        return 1
    elif number % 2 == 0:
        numbers = number // 2
        print(numbers)
        collatz(numbers)
    elif number % 2 == 1:
        numbers = 3*number + 1
        print(numbers)
        collatz(numbers)
try:
    number = int(input( " Please enter an integer ->: " ))
    collatz(number)
except ValueError:
    print("please input a integer number")

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325099782&siteId=291194637