Touge training platform Python

Table of contents

Python first experience - Hello world

Level 1 Hello Python, here I come!

Python control structure (1)※

Level 1 Introduction to the if branch※

Level 2 Introduction to while loop branches※

Learning-Python loop structure for...else... to find the number of daffodils

Level 1 Learning-Python loop structure for...else...finding the number of daffodils

Python programming_training 4_loop statement training

Level 1 Prime Numbers

Level 2 Greatest Common Divisor

Level 3 The number of prime numbers

Level 4 Goldbach's Conjecture

Exercise - Function return value of Python function

Level 1 Exercise - Function return value of Python function

Learning - function recursive call of Python function

Level 1 Learning - Function recursive call of Python function

Exercise - Application of Python List II

Level 1 Exercise - Application of Python List II

Exercise - Application of Python Tuples II

Level 1 Exercise - Application of Python Tuples II

Exercise - Application of Python Dictionary II

Level 1 Exercise-Python Dictionary Application II

Exercise-Python exception handling try...except...

Level 1 Practice-Python exception handling try...except...

Exercise-Python exception handling try...except...else...

Level 1 Practice-Python exception handling try...except...else...

Python first experience - Hello world

Level 1: Hello Python, here I come!

mission details

The Python programming language is concise and easy to read, and provides two different modes of interactive programming and script programming, which are easy for learners to get started. The tasks of this level are: (1) Complete printing Hello world , integer addition and subtraction, and use Helpcommands to query the use of corresponding built-in functions, etc.; (2) Use the built-in functions provided by Python print()to print out Hello world .

# coding=utf-8
# 请在此添加代码,实现编程要求
########## Begin ##########
print('Hello Python')
########## End ##########

Python control structure (1)※

Level 1: Introduction to if branch※

programming requirements

Begin-EndAccording to the prompt, supplement the code in the editor on the right to complete the following requirements:

first question

month with 31days as [1,3,5,7,8,10,12]month

Please write a program that outputs an input 1~12integer if its corresponding month is 31a day yes, otherwise outputs it no.

second question

In weather forecasting, hurricanes are generally classified according to wind speed, and the corresponding relationship is given in the table below.

wind speed 74-95 96-110 111-130 131-154 155 and above
level 1 2 3 4 5

Please write a program to output the corresponding hurricane level according to the wind speed input by the user.

# 第一题

month = int(input())
# 31天的月份:1~7之间的奇数月、8~12之间的偶数月
# 如果是31天的月份输出yes
####### begin #######
if month in [1,3,5,7,8,10,12]:
    print("yes")
####### end #########
# 如果不是31天的月份,输出no
####### begin #######
else:
    print("no")
####### end #########
print('\n***********************\n')

#第二题
# 从测试集得到风速
velocity = int(input())
# 默认是0级
rank = 0
# 如果风速在74到95之间,输出1
####### begin #######
if 74<=velocity<=95:
    rank=rank+1
####### end #########
# 如果风速在96到110之间,输出2
####### begin #######
elif 96<=velocity<=110:
    rank=rank+2
####### end #########
# 如果风速在111到130之间,输出3
####### begin #######
elif 111<=velocity<=130:
    rank=rank+3
####### end #########
# 如果风速在131到154之间,输出4
####### begin #######
elif 131<=velocity<=154:
    rank=rank+4
####### end #########
# 如果风速大于155,输出5
####### begin #######
elif velocity>=155:
    rank=rank+5
####### end #########
print(rank)

Level 2: Introduction to while loop branches※

programming requirements

Begin-EndAccording to the prompt, supplement the code in the editor on the right to complete the following requirements:

first question

Programmatically calculate the value of the following formula

12+32+52+...+9952+9972+9992

and output the result

second question

Use whilethe statement to complete the program logic, find the following algorithm to find the approximate value of the square root x. (For example, xwhen3 the algorithm outputs approx 1.7320508.

The algorithm is as follows:

  1. Input x, if xit is a negative number, output "no real solution", and the algorithm ends;

  2. Order g=x/2;

  3. Calculate the error value by the following formula, if ∣x−g∗g∣<10−6, output g, the algorithm ends;

  4. Otherwise, it will be (g+x/g)/2used as a new guess value and still recorded as g.

  5. Repeat steps 3 and 4

from math import *

i = 1 # 当前计算的值
s = 0 # 计算出来的和
# 第一题
########### begin ##########

# 请在此输入循环控制语句
while i<=999:
######### end     ####
    s = s + i ** 2
    i = i + 2

print(s)

########## 第二题 ##############
x = int(input())

if x<0:
    print('无实数解')
else:
    g = x/2
    #######begin##############
    # 请输入循环控制语句
while abs(x-g*g)>=0.000001:
    #######end#################
        g = (g+x/g)/2
print(g)

Learning-Python loop structure for...else... to find the number of daffodils

Level 1: Learning - Python loop structure for...else... to find the number of daffodils

mission details

The task of this level: Given an integer n, judge whether the positive number within n contains the number of daffodils. The daffodil number refers to a 3-digit integer whose sum of the 3 powers of the digits in each digit is equal to itself.

i= int(input())
for num in range(2,i):
    a = num % 10
    b =(( num -a)/10)%10
    c = (num - b* 10 - a) /100
#print(‘num’, num)
#print(a)
#print(b)
#print©
    if num == a**3 + b**3 +c**3:
        print("有水仙花数")
        break
else:
    print('没有水仙花数')

Python programming_training 4_loop statement training

Level 1 prime numbers

mission details

The task of this level: input a greater 1than int, judge whether it is a prime number.

If it is a prime number, output it Prime. Otherwise, output Heshu.

related information

A prime number is 1a number that has no factors other than the sum itself.

For example, 7it is a prime number, because 7the factors of are only 1sum and 7. Instead 9of a prime number, because 9the factors of are in addition to 1the sum .93

n=int(input())
from math import sqrt
m=int(sqrt(n))
for i in range(2,m+1):
    if n%i==0:
        print("Heshu")
        break
else:
    print("Prime")

Level 2 Greatest Common Divisor

mission details

The task of this level: Given 2a positive int, find its greatest common divisor.

related information

The so-called agreatest bcommon divisor of the sum is not only aa factor of , but also ba factor of , and it is the largest among all numbers satisfying the condition.

For example 12, 8the common factors of the sum and are 1/2/4therefore the greatest common divisor of the sum.4128

#********** Begin **********#
def gcd(a,b):
    if a<b:
        a,b=b,a
    while(a%b !=0):
        c=a%b
        a=b
        b=c
    return b
a,b=map(int,input().split())
c=gcd(a,b)
print(c)
#********** End **********#

Level 3 Number of Prime Numbers

mission details

The task of this level: Find [a,b]the number of prime numbers in the interval.

Input 2a positive integer sum aand boutput the answer. (guarantee a≤b)

In particular, note that 1it is not a prime number!

related information

Consider the most straightforward approach, first write a forloop from ato b. Then judge whether each number is a prime number. And judging the prime number requires a loop, so a double loop needs to be written.

#********** Begin **********#
n=0
a,b=input().split()
a=eval(a)
b=eval(b)
for i in range(a,b+1):
    if i ==1:
        n=n+1
        continue
    for d in range(2,i):
        if i%d==0:
            n=n+1
            break
print (b-a-n+1)
#********** End **********#

Level 4 Goldbach's conjecture

mission details

The task of this level: Given a positive even number int, decompose it into 2a sum of prime numbers. Output the 2prime numbers from small to large, separated by a space. (If there are multiple possibilities, output the answer that differs as much as possible.)

For example, input 6, output should be: 3 3if input 10, then “3 7”both “5 5”. But 2the prime numbers of the former are more different, so the answer should be:3 7

#********** Begin **********#
import math
n=int(input())
a=2
b=n-a
gede1,gede2=1,1
while gede1==1 or gede2==1:
    if a==2:
        gede1=0
    else:
        for i in range(2,a):
            if a%i == 0:
                gede1 = 1
                break
            else:
                gede1 = 0
    if b == 2:
        gede2 = 0
    else:
        for i in range(2,int(math.sqrt(b))+2):
            if b%i == 0:
                gede2 = 1
                break
            else:
                gede2 = 0
        if gede1 == 1 or gede2 == 1:
            a = a+1
            b = n-a
print('{} {}'.format(a,b))
#********** End **********#

Exercise - Function return value of Python function

Level 1 exercise - function return value of Python function

mission details

The task of this level: define a function average, which is used to calculate the average score of the test score. The number of parameters passed in each time is uncertain. Please write code to realize this function.

"""
任务:定义一个函数 average,用于计算考试成绩的平均分,每次传入的参数个数不确定,如果参数中出现了小于 0 或者大于 100 的数时,输出"分数数据异常",否则输出平均分。
"""
 
# 请在下面的Begin-End之间按照注释中给出的提示编写正确的代码
##########Begin##########
# 定义函数 average,计算平均分并按照要求打印结果
def average(*args):
    num = 0 
    for x in args:
        if x<0 or x>100:
            return
        num += x
    return num/len(args)
##########End##########
# 请勿修改下列代码
score = eval(input())     # 将输入的字符串转换为可执行的表达式
if score:
    print("平均分为",score)
else:
    print("分数数据异常")
"""
任务:定义一个函数 average,用于计算考试成绩的平均分,每次传入的参数个数不确定,如果参数中出现了小于 0 或者大于 100 的数时,输出"分数数据异常",否则输出平均分。
"""

 
# 请在下面的Begin-End之间按照注释中给出的提示编写正确的代码
##########Begin##########
# 定义函数 average,计算平均分并按照要求返回结果
def average(*args):
    n=len(args)
    sum1=0
    for i in args:
        if 0<=i<=100:
            sum1+=i
        else:
            return False
    return sum1/n

##########End##########
# 请勿修改下列代码
score = eval(input())     # 将输入的字符串转换为可执行的表达式
if score:
    print("平均分为",score)
else:
    print("分数数据异常")

Learning - function recursive call of Python function

Level 1 learning - function recursive call of Python function

mission details

The Fibonacci sequence is an exponential sequence starting from the third item, and each item is equal to the sum of the previous two. For example:1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610......


"""
任务:使用递归打印斐波拉契数列的前 n 位数字。n 通过 input 函数获取。
"""

 
# 请在下面的Begin-End之间按照注释中给出的提示编写正确的代码
########## Begin ##########
# 定义一个函数,使用递归打印斐波拉契数列的前 n 位数字
n=eval(input())
def he(x):
    if x==1 or x==2:
        return 1
    else:
        a=he(x-1)+he(x-2)
        return a
print(he(n))
 
########## End ##########

Exercise - Application of Python List II

Level 1: Exercise - Application of Python List II

mission details

The task of this level: Given an array, use the for loop to copy the array, then remove the duplicate elements in the list, and finally sort the list. Print a deduplicated and sorted copy list.

"""
任务:给定一个数组,使用 for 循环复制这个数组,然后去除列表内的重复元素,最后对列表进行排序。打印去重且排序后的复制列表。
"""
 
list1 = [88,5,8,6,1,23,1,15,1,61,31,6,51,1,984,9849,1,-100,513,891,3,1,48,465,132,165,4,6,132,498,46,132,165,468,498,484,11,6,84,65,132,1,64,684,6981,324,984,61,32,468,4651,6,4,9814,654,984,68,7]
 
# 请在下面的Begin-End之间按照注释中给出的提示编写正确的代码
##########Begin##########
# 使用 for 循环复制这个数组,然后去除列表内的重复元素,最后对列表进行排序。打印去重且排序后的复制列表
list2=list(set(list1))
for i in list2:
    n=list2.count(i)
    if n>1:
        for j in range(1,n):
            del list2[list2.index(i)]
list2.sort()
print(list2)
##########End##########

Exercise - Application of Python Tuples II

Level 1: Exercise - Application of Python Tuples II

mission details

The task of this level: Given a tuple, use the mutual conversion between the list and the tuple to change the elements of the tuple, and remove the integer data in the tuple.

"""
任务:给定一个元组,利用列表和元组的相互转换实现元组元素的更改,去除元组中的整型数据。打印更改后的元组。
"""
tup = (1,"3",4,5,"4","a",(1,2,3,4),"b","c",6,17,"d",("a","b","c"),0,"e","f",True,10,"False",11,"h","A","B","C",30,"D",-35,-60,(-1,-2,-5))
# 请在下面的Begin-End之间按照注释中给出的提示编写正确的代码
##########Begin##########
# 利用列表和元组的相互转换实现元组元素的更改,去除元组中的整型数据
list1 = []
for x in tup:
    if type(x) != int:
        list1.append(x)
print(tuple(list1))
##########End##########

Exercise - Application of Python Dictionary II

Level 1 Exercise - Application of Python Dictionary II

mission details

This mission: given a dictionary, the value of the dictionary can only be integer data, the key is the character type of the number, for example, {"5":5}but the key-value pairs in the dictionary are not all sorted according to this rule, what may {"5":4}happen , please write code to change the value of the dictionary to an integer value consistent with the key.

"""
任务:给定一个字典,该字典的值只能是整型数据,键为该数字的字符型,比如`{"5":5}`。
但是字典中的键值对并不是都按照这个规则排序的,可能出现`{"5":4}`的情况,请编写代码将字典的值改为和键一致的整型数值。
例如:{"5":4,"3":2}改为{"5":5,"3":3}
"""
 
dict1 = {"4":3,"14":14,"5":6,"33":33,"25":25,"18":68,"0":0,"10":3,"42":24,"7":1,"64":64,"49":49,"90":90,"48":48,"68":86,"41":12,"46":46,"91":91,"75":75,"27":39,"34":3,"57":11}
 
# 请在下面的Begin-End之间按照注释中给出的提示编写正确的代码
##########Begin##########
# 请编写代码实现任务要求,打印更改后的字典
for i in dict1:
    if eval(i)!=dict1[i]:
        dict1[i]=eval(i)
print(dict1)
##########End##########

Exercise-Python exception handling try...except...

Level 1: Practice-Python exception handling try...except...

mission details

The task of this level: find the quotient of the given two numbers, and catch the exception that the divisor is 0.

programming requirements

Carefully read the code frame and comments given in the editing area on the right, and follow the prompts to write the program code between Begin-End. Specific requirements are as follows:

  • Use 2 input functions to receive the dividend and the divisor, the first is used to receive the dividend, and the second is the divisor;
  • Find the quotient of two numbers, if there is no exception, print the result, if there is an exception that the divisor is 0, then catch the exception, and output a prompt statement after catching the exception: "The divisor cannot be 0".
    # 请在下面的 Begin-End 之间按照注释中给出的提示编写正确的代码
    ########## Begin ##########
    # 计算两个数的商,捕获除数为 0 时的异常
    try:
        a=eval (input())
        b=eval (input())
        print(a/b)
    except:
        print("除数不能为0")
    
    ########## End ##########

Exercise-Python exception handling try...except...else...

Exercise 1 - Python exception handling try...except...else...

mission details

The task of this level: Get 5 integers and put them into a list.

programming requirements

Carefully read the code frame and comments given in the editing area on the right, and follow the prompts to write the program code between Begin-End. Use the input function to get the background data 5 times, if the 5 data are numbers, add the numbers to the list and print the list. If there is data that is not an integer, print "Please enter an integer."

# 请在下面的 Begin-End 之间按照注释中给出的提示编写正确的代码
########## Begin ##########
# 获取 5 个整数,放入一列表中,如果 5 个数都是整数,则打印该列表
list1 = []
for i in range(5):
    try:
        j=int(input())
    except:
        print('请输入整数!')
        break
    else:
        list1.append(j)
if len(list1) == 5:
    print(list1)

Guess you like

Origin blog.csdn.net/qq_58715818/article/details/121448679