[Touge-Python] Python Chapter 4 Homework (Elementary)

Level 1 Function with no parameters and no return value

Task description
The task of this level: write a small program with no parameters and no return value function.

Relevant knowledge
In order to complete this task, you need to master:

  1. Function with no parameters and no return value

Function with no parameters and no return value
Define a function with no parameters and no return valueprint_hi_human(). When calling the function, the computer can send greetings to the world. , output "Hello, human!" in the function. ‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬

Non-return value functions generally have output statements or drawing statements inside the function. The return value of the function is None. There is no need to use assignment statements or print() functions when calling the function.

Code example:

print("Hello world")

Programming requirements
According to the prompts, add code in the editor on the right to complete a program with no parameters and no return value function.

Testing instructions
The platform will test the code you write:

Input:
Output:

人类,你好!

Reference Code

def print_hi_human():  # 函数名用小写字母
    """文档注释,双引号,说明函数的参数、功能和返回值等。
    定义一个名为print_hi_human的无参数函数,其功能是打印一句问候语,
    这个函数没有return语句,即没有返回值,或者说其返回值为None。
    # >>> print_hi_human()
    # 人类,你好!
    """
    # ==================Begin=====================================
    # 此处去掉注释符号“#”并补充你的代码
    print('人类,你好!')
    # ===================End====================================

if __name__ == '__main__':
    # 直接使用函数名来调用函数
    # ==================Begin=====================================
    # 此处去掉注释符号“#”并补充你的代码
    print_hi_human()
    # ===================End====================================

Level 2 Function with no parameters and return value

Task description
The task of this level: write a small program with no parameters and a return value function.

Relevant knowledge
In order to complete this task, you need to master:

  1. Function with no parameters and return value

Function without parameters and return value
Define a function without parameters and return valuesay_hi_human(). When calling the function, the return value of the function is output. Let The computer sends a greeting to the world, returning the string "Hello, human!". ‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬

For functions that have a return value, use the return statement to return the processing result of the function to the calling place. When calling the function, use the print() function to directly output the processing result of the function, or use the assignment statement: The return value is named for subsequent processing.

Programming requirements
According to the prompts, add code in the editor on the right to complete a small program with no parameters and a return value function.

Testing instructions
The platform will test the code you write:

Output:

输出:人类,你好!

Reference Code

def say_hi_human():  # 函数名用小写字母
    """定义一个名为print_hi_human的无参数函数,其功能是返回字符串-人类,你好!"""
    #========================Begin===============================
    #补充你的代码
    return '人类,你好!'
    #==========================End=============================

if __name__ == '__main__':
    # 函数名作为print()函数的参数,输出say_hi_human()的返回值
    #========================Begin===============================
    #补充你的代码
    print(say_hi_human())
    #==========================End=============================

Level 3 Functions with parameters and return values

Task description
The task of this level: write a small program with parameters and a return value function.

Relevant knowledge
In order to complete this task, you need to master:

  1. Function with parameters and return value

Function with parameters and return value
Define a functionsay_hi_person() with one parameterfull_name that accepts the characters of a person's name The string is a parameter, and the return value of the function is“XXX,你好!”. For example, the parameter of the function is "Li Bai" and the return value is "Hello, Li Bai!"

Programming requirements
According to the prompts, add code in the editor on the right to complete a small program with parameters and return value functions.

Testing instructions
The platform will test the code you write:

Input:李白;
Output:李白,你好!

Reference Code

def say_hi_person(full_name):  # 函数名用小写字母,函数名填空
    """定义一个名为say_hi_person的有参数函数,接受人名的字符串为参数,函数的返回值为“***,你好!”,
    例如函数的参数为“李白”,返回值为“李白,你好!”。"""
    #====================Begin===================================
    # 补充你的代码
    return full_name + ',你好!'
    #=====================End==================================

if __name__ == '__main__':
    #  函数名作为print()函数的参数,输出say_hi_human()的返回值。输入的人名作为函数的参数
    person_name = input()              # 输入人名
    #====================Begin===================================
    # 补充你的代码
    print(say_hi_person(person_name))
    #=====================End==================================

Level 4 Multi-parameter function

Task description
The task of this level: write a multi-parameter function to perform computer greetings on a small program.

Relevant knowledge
In order to complete this task, you need to master:

  1. multi-parameter function

Multi-parameter function
defines a functionsay_hi_gender() with 2 parametersfull_name and gender, accept a string of name and gender ("male" or "female") as parameters, and the return value of the function is "Dear Mr./Ms. XXX, welcome to Mars!" . The title is determined based on the gendergender value. Men are called "Mr." and women are called "Ms.". When the gender is uncertain, it is called "Mr./Ms.". The return value is the name and title replaced. Welcome string.

Programming requirements
According to the prompts, add code in the editor on the right to complete a small program with a multi-parameter function for computer greeting.

Testing instructions
The platform will test the code you write:

Test input:

李白
男

Output:

尊敬的李白先生,欢迎来到火星!

Reference Code

def say_hi_gender(full_name, gender):  # name 和gender为形式参数
    """定义一个名为say_hi的有参数函数,其功能是打印一句问候语
    根据性别gender值确定称谓,男性称为“先生”,女性称为“女士”,不确定性别时称为“先生/女士”
    返回值为替换了姓名与称谓的欢迎字符串
    例如:尊敬的李白先生,欢迎来到火星!"""
    # ====================Begin===================================
    # 此处去掉注释符号“#”并补充你的代码
    g = '先生/女士'
    if gender == '男':
        g = '先生'
    if gender == '女':
        g = '女士'
    return f'尊敬的{
      
      full_name}{
      
      g},欢迎来到火星!'
    # =======================================================

if __name__ == '__main__':
    # 直接使用函数名来调用函数
    # ====================Begin===================================
    # 此处去掉注释符号“#”并补充你的代码
    print(say_hi_gender(input(), input()))
    # =======================================================

Level 5 Any number of parameters

Task description
The task of this level: write a small program that can perform computer greetings with any number of parameters.

Relevant knowledge
In order to complete this task, you need to master:

  1. any number of parameters

Any number of parameters
Define a functionsay_hi_multi_parameter so that it can receive any number of names as parameters. When calling the function, you can pass multiple parameters . ‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬

Sometimes you don’t know in advance how many actual parameters a function requires. In this case, you can pass a sequence type parameter starting with “*” to the function, for example: “*id”, the asterisk in front of the formal parameter name id will cause Python to create an empty tuple and encapsulate all collected actual parameter values ​​into this tuple inside.

Programming requirements
According to the prompts, add code in the editor on the right to complete a small program that can perform computer greetings with any number of parameters.

Testing instructions
The platform will test the code you write:

Input format :
No input for this question

Output format :
Branch outputs "XXX, Hello!" for each incoming parameter

Output:

孟浩然,你好!
杜甫,你好!
李白,你好!
柳宗元,你好!
李商隐,你好!

Reference Code


def say_hi_multi_parameter(*names):    # 括号里填上参数
    for name in names:
        print(name + ',你好!')

#调用say_hi_multi_parameter并传入参数
say_hi_multi_parameter('孟浩然')
say_hi_multi_parameter('杜甫', '李白', '柳宗元', '李商隐')

Level 6 Detailed explanation of pow function

Task Description
The task of this level is to write a small program that can calculate and output the nth power of x.

Relevant knowledge
In order to complete this task, you need to master:

  1. Detailed explanation of pow function
  2. Custom pow function

Detailed explanation of pow function
pow() function is a built-in function of Python, which calculates and returns x's The value of y raised to the power.

pow(x, y, z)

name Remark illustrate
x base Parameters that cannot be omitted
and index Parameters that cannot be omitted
With Remainder number Parameters that can be omitted. When z exists, the function return value is equal to pow(x, y)%z

Programming example:

  1. When parameterz is omitted, when the remainder digitz is omitted, the pow function returnsx to the y power.
print(pow(2, 3))   # 输出8
print(pow(4, 0.5))  # 输出2.0
  1. When the parameterz exists and the parameterz exists, the return result of pow(x, y, z) is equal topow(x, y) Find the remainder of z.
print(pow(8, 2, 5))  # 输出4

Precautions

  1. zWhen the parameter is omitted, the return value is x raised to the y power.
print(pow(2, 4))  # 输出16
  1. zWhen the parameter is omitted, the values ​​of x and y can be integers and floating-point numbers. When x or y exist floats When the number is a point, the return result of the pow() function is also a floating point number, otherwise it is an integer.
print(pow(4, 0.5))         # 输出2.0
print(type(pow(4, -0.5)))  # 输出<class 'float'>
print(pow(4, 2))           # 输出16
print(type(pow(4, 2)))     # 输出<class 'int'>
  1. Parameterz cannot be 0 When parameter z is 0, < /span>Python will throw an exception.
print(pow(4, 2, 0))
'''
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: pow() 3rd argument cannot be 0
'''
  1. When the parameterz exists, x and y can only be integers when z When present, x and y must be integers. Otherwise Python will throw an exception.
print(pow(3, 0.7, 1))
'''
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: pow() 3rd argument not allowed unless all arguments are integers
'''

Customized pow function
Problem description: Enter a valuex and a positive integer n, and call the custom pow() function to calculate and output the power of x. n

Programming requirements
Follow the prompts, add code in the editor on the right, complete the calculation and output x of n A small program to the third power.

Testing instructions
The platform will test the code you write:

Test input:

2
16

Expected output:

65536.0

Reference Code

def pow(x, y):
    return 1.0*x**y

a = eval(input())
b = eval(input())
print(pow(a, b))

Level 7 fabs() function

Task description
The task of this level: write a small program that uses a customized fabs() function output.

Relevant knowledge
In order to complete this task, you need to master:

  1. fabs() function
  2. Custom fabs() function

fabs() function in python
fabs() The function returns the absolute value of the number, such as math.fabs(-5) returns 5.0.< The difference between /span> function returns a floating-point value. function is that
and abs()fabs()

  • Parameter
    x numerical expression
  • Return value
    Returns the absolute value of the value.

Code example:

import math
math.fabs(x)
#注意:fabs() 是不能直接访问的,需要导入 math 模块,通过静态对象调用该方法。

Code example:

import math
print(math.fabs(-45))  # 45.0

Customized fabs() function
Problem description: Enter a valuex and call the customized fabs() The function calculates and outputs the absolute value of this number as a floating point number.

Programming requirements
Follow the prompts, add code in the editor on the right, and use the customized fabs() function to output the corresponding value.

Test instructions
The platform will test the code you wrote:
Test input: -3; a>
Expected output:

3.0

Reference Code

def fabs(x):
    """返回x的绝对值"""
    return -x if x<0 else x

if __name__ == '__main__':
    n = float(input())
    print(fabs(n))

Level 8 Car Fan

Task description
Xiao Ming is a car fan. When he sees a car, he can immediately tell the year, model and brand of the car. Define a function that can output the introduction of the car. ‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬

For example, enter:
2020 AMG_S65 Mercedes-Benz

can output:
This is a Mercedes-Benz car produced in 2020, model AMG_S65 ‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬ .

The required function has the following functions: when the user only enters the production year and model, the brand is output as "BMW".

Input format
Enter year, model and brand separated by spaces (brand may not be available)

Output format
This is a brand car produced in 2006 and model number. (Replace based on user input)

Example
Import: 2020 AMG_S65 奔驰
Export:

这是一辆2020年生产,型号是AMG_S65的奔驰牌汽车。

Reference Code

def Car(*ls): # 括号里补充你的代码
#####
    brand = '宝马'
    if len(ls)>2:
        brand = ls[-1]
    return f'这是一辆{
      
      ls[0]}年生产,型号是{
      
      ls[1]}{
      
      brand}牌汽车。'

# 以下内容不要修改
ls = input().split()  # 根据空格切分输入字符串为列表
print(Car(*ls))       # 调用函数,取列表中的全部数据做参数

Level 9: Write a function to output a self-divisor

Task Description
A number that does not contain 0 is a self-divisor if it can be divided by each of its digits. For example, 128 is a self-divisor because 128 is divisible by 1, 2, and 8. Write a functionselfDivisor(num) to determine whethernum is a self-divisor, and use this function to output all self-divisors not greater than N. ‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬
(Note that numbers containing the number 0 are not self-divisors)

Input format
The input is a line and a positive integer N (N>=1).

Output format
The output is one line, which is all self-divisors not greater than N. There is a space after each number. .

Example 1
Import: 1
Export: 1

Example 2
Import: 22
Export: 1 2 3 4 5 6 7 8 9 11 12 15 22

Reference Code

def selfDivisor(num):
    for i in str(num):
        if i=='0' or num%int(i):
            return False
    return True

num = int(input())
for i in range(1, num+1):
    if selfDivisor(i):
        print(i, end=' ')

Level 10: Find square root B using bisection method

Task description
Design a function that uses the bisection method to calculate the square root of a real number that is greater than or equal to0 , real numbers and calculation precision control are input by the user in the same line, separated by commas, and the output results strictly retain bits decimal. When is less than or equal to the set accuracy, it is approximately considered as . ‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬ nsqrt_binary(n)n8(abs(x * x - n) )x * x == n

Note: The initial interval is taken as[0,n+0.25]

Input format
Enter a floating point number on the same line n (greater than or equal to 0) and a floating point number representing the precision (can be entered in the format 1e-m), separated by commas.

Output format
The first line outputs the square root calculated using the function you designed. ‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪
The second line outputs the square root calculated using the square root function of the math library

Example
Import: 5.0,1e-7
Export:

2.23606796
2.23606798

Reference Code

import math

def sqrt_binary(n, e):
    low, high = 0, n+0.25
    while True:
        mid = (low+high)/2
        if abs(mid**2 - n) < e:
            return mid
        else:
            if mid**2 > n:
                high = mid
            else :
                low = mid

n, e = map(eval, input().split(','))
print(f'{
      
      sqrt_binary(n, e):.8f}')  
print(f'{
      
      math.sqrt(n):.8f}')

Guess you like

Origin blog.csdn.net/qq_45801887/article/details/134908487