python练习题(持续更新)

这篇博客整理了100道Python练习题,覆盖从基础到进阶的不同难度,包括递归函数、进制转换、列表表达式、正则表达式、迭代器等知识点。每道题都有等级划分,适合不同水平的学习者。博主还提供了自己的解答和原答主的解法,部分题目还特别解释了如何使用Python内置函数和库。
部署运行你感兴趣的模型镜像

python 100道练习题

这些题都是我从GitHub上找到的,原题都是英文的,我对每道题都做了翻译,也附上了自己的做法,一般情况下,第二种解法是原答主给出的解决方法,如果一道题我只给出了一个解法就说明我的解法和原答主是相同的。
我会一点点的发出来的,希望大家和我们一起进步。
原答主用的是python2.x版本,可能会有一些语法不同,我只修改了其中的一部分.
原网址如下:
原答主的题目链接
强调:
每一道题都是有等级评定的,按照原答主的理解,可以分为以下三类:

1 lv1

# Question:
# Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5,
# between 2000 and 3200 (both included).
# The numbers obtained should be printed in a comma-separated sequence on a single line.
# 问题:
# 写一个程序,找出所有在2000至3200之间(包括2000和3200)的能被7整除但不是5的倍数的数,
# 获得的数字应该以逗号分隔的序列打印在单行上。

```python
list1=[]
for i in range(2000,3201):
    list1.append(i)
print(list((filter(lambda x: x % 7 == 0 and x % 5 != 0,list1))))

l=[]
for i in range(2000, 3201):
    if (i%7==0) and (i%5!=0):
        l.append(str(i))
print(','.join(l))

2 lv1

用递归函数求解

# Question:
# Write a program which can compute the factorial of a given numbers.
# The results should be printed in a comma-separated sequence on a single line.
# Suppose the following input is supplied to the program:
# 8
# Then, the output should be:
# 40320
#写一个计算阶乘的程序
#当输入8时,输出40320
def fact(n):
    if n==0:
        return 1
    else:
        return n*fact(n-1)
x=int(input())
print(fact(x))

3 lv1

# Question:
# With a given integral number n, write a program to generate a dictionary that contains (i, i*i)
# such that is an integral number between 1 and n (both included). and then the program should print the dictionary.
# Suppose the following input is supplied to the program:
# 8
# Then, the output should be:
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
#生成从1到n的一个字典,这个字典的key是i,value是i*i,输出如下例:
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
dict1={}
def generate_dict(n):
    for i in range(1,n+1):
        dict1[i]=i*i
    return dict1
print(generate_dict(8))

n=int(raw_input())
d=dict()
for i in range(1,n+1):
    d[i]=i*i

print d

4 lv1

# Question:
# Write a program which accepts a sequence of comma-separated numbers from console
# and generate a list and a tuple which contains every number.
# Suppose the following input is supplied to the program:
# 34,67,55,33,12,98
# Then, the output should be:
# ['34', '67', '55', '33', '12', '98']
# ('34', '67', '55', '33', '12', '98')
#以用逗号隔开的一串数字作为输入,并且产生由这串数字组成的列表和元祖,如:
#输入
# 34,67,55,33,12,98
# 输出
# ['34', '67', '55', '33', '12', '98']
# ('34', '67', '55', '33', '12', '98')

n=int(input())
list1=[]
for i in range(0,n):
    list1.append(input())
print(list1)
print(tuple(list1))


values=input()
print(type(values))
l=values.split(",")
t=tuple(l)
print(l)
print(t)

5 lv1

# Question:
# Define a class which has at least two methods:
# getString: to get a string from console input
# printString: to print the string in upper case.
# Also please include simple test function to test the class methods.
# 定义一个至少有两种方法的类:
# 一、获取输入控制台的字符串
# 二、用大写的形式将其打印出来
# 三、包含一些简单的测试函数去测试这些方法
class in_and_out_string():
    def __init__(self):
        self.st=''
    def get_string(self):
        self.st=input()
    def print_string(self):
        print(self.st.upper())
test=in_and_out_string()
test.get_string()
test.print_string()

先来5道题吧,以后会一直更新的,如果有帮到大家,可以点一个赞或者关注!


我打算把所有的题目全部搬到这儿来,方便大家阅读。

6 lv2

这一道题我在写代码的时候做了一些修改,没有对一些变量进行赋值。

# Question:
# Write a program that calculates and prints the value according to the given formula:
# Q = Square root of [(2 * C * D)/H]
# Following are the fixed values of C and H:
# C is 50. H is 30.
# D is the variable whose values should be input to your program in a comma-separated sequence.
# Example
# Let us assume the following comma separated input sequence is given to the program:
# 100,150,180
# The output of the program should be:
# 18,22,24
#写一个这样的程序,在满足Q=[(2*50*D)/30]^0.5的情况下,D为任意值,当输入100,150,180,它的输出结果是18,22,24
a=input()
b=a.split(',')
P=[]
import math
for i in range(0,len(b)-1):
    Q=math.sqrt((2*50*int(b[i]))/30)
    print(int(Q),end='')
    print(',',end='')
Q=math.sqrt((2*50*int(b[-1]))/30)
print(int(Q))
for i in b:
    P.append(str(int(math.sqrt((2 * 50 * int(i)) / 30))))
print(P)
print(','.join(P))

7 lv2

# Question:
# Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array.
# The element value in the i-th row and j-th column of the array should be i*j.
# Note: i=0,1.., X-1; j=0,1,¡­Y-1.
# Example
# Suppose the following inputs are given to the program:
# 3,5
# Then, the output of the program should be:
# [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
# 写一个二维数组,第i行和第j列的值为i*j,如:
# 当输入3,5时
# 输出:
# [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
x=input()
i=int(x.split(',')[0])
j=int(x.split(',')[1])
two_dimensional_array=[]
save=[]
for k in range(0,i):
    for l in range(0,j):
       save.append(k*l)
    two_dimensional_array.append(save)
    save=[]
print(two_dimensional_array)


input_str = input()
dimensions=[int(x) for x in input_str.split(',')]
rowNum=dimensions[0]
colNum=dimensions[1]
multilist = [[0 for col in range(colNum)] for row in range(rowNum)]

for row in range(rowNum):
    for col in range(colNum):
        multilist[row][col]= row*col

print(multilist)

8 lv2

# Question:
# Write a program that accepts a comma separated sequence of words as input
# and prints the words in a comma-separated sequence after sorting them alphabetically.
# Suppose the following input is supplied to the program:
# without,hello,bag,world
# Then, the output should be:
# bag,hello,without,world
#写一个程序,接受逗号隔开的单词作为输入,并且将它们按单词表排序用以逗号隔开的方式打印
#例如:输入:
# without,hello,bag,world
# 输出:
# bag, hello, without, world
items=[x for x in input().split(',')]
items.sort()
print(','.join(items))
#我们可以通过冒泡排序来进行排序,代码如下:(其实是没有必要的,因为python是面向对象的语言)
def bubble(x):
    n=len(x)
    for i in range(n-1,0):
        for j in range(0,i):
            if x[j]>x[j+1]:
                temp=x[j]
                x[j]=x[j+1]
                x[j+1]=temp
    return x
print(bubble(items))

9 lv2

# Question:
# Write a program that accepts sequence of lines as input and
# prints the lines after making all characters in the sentence capitalized.
# Suppose the following input is supplied to the program:
# Hello world
# Practice makes perfect
# Then, the output should be:
# HELLO WORLD
# PRACTICE MAKES PERFECT
# 写一个接受句子的程序并且将它们转换为大写输出,输入格式如下:
# Hello world
# Practice makes perfect
# 输出如下:
# HELLO WORLD
# PRACTICE MAKES PERFECT
lines=[]
while True:
    s=input()
    if s:
        lines.append(s.upper())
    else:
        break
for line in lines:
    print(line)

10 lv2

# Question:
# Write a program that accepts a sequence of whitespace separated words as input and prints the words
# after removing all duplicate words and sorting them alphanumerically.
# Suppose the following input is supplied to the program:
# hello world and practice makes perfect and hello world again
# Then, the output should be:
# again and hello makes perfect practice world
#写一个接受一串单词的程序,并且移除复制的成分(相同的成分),最后将这些单词按照单词表顺序输出
#输入:
# hello world and practice makes perfect and hello world again
#输出:
# again and hello makes perfect practice world
words=[x for x in input().split(' ')]
words.sort()
wlen=len(words)
for i in range(1,wlen):
    if words[i-1]== words[i]:
        words[i-1]=0
for word in words:
    if word==0:
        words.remove(0)

print(' '.join(words))
#我们可以用集合轻松的筛选出相同的成分并将其剔除

print(' '.join(sorted(list(set(words)))))

11 lv2

这道题用第一种方法是无法得到题目要求的结果的,大家可以去试一下,我用第一种办法旨在说明一些进制转换函数。

转换到十进制

  • int( , )第一部分填写数字,第二部分填写被转换数的进制。
    如,二进制转十进制就是
    int(‘0100’,2)

转换到十六进制

  • 十进制转十六进制:
    hex(1033)
  • 其余进制数转换为十六进制可以先转换为十进制,再转换为十六进制
    如:
    hex(int(‘17’,8))

转换到二进制

  • 十进制转二进制:
    bin(1000)
  • 其余进制数转换方法同十六进制。

转换到八进制

  • oct(),可以将任意数直接转换
# question:
# Write a program which accepts a sequence of comma separated 4 digit binary numbers as
# its input and then check whether they are divisible by 5 or not.
# The numbers that are divisible by 5 are to be printed in a comma separated sequence.
# Example:
# 0100,0011,1010,1001
# Then the output should be:
# 1010
# Notes: Assume the data is input by console.
#写一个接受用逗号隔开的二进制数作为程序的输入并且检测它是否可以被5整除。可以被5整除的那个数
#用以逗号隔开的形式输出,例:
#输入:
# 0100,0011,1010,1001
# 输出:
# 1010
values=[x for x in input().split(',')]
items=[]
for value in values:
    value=int(f'{value}',2)
    if value % 5 == 0 :
        value=bin(value)
        items.append(value)
print(','.join(items))

values=[x for x in input().split(',')]
items=[]
for value in values:
    x=int(value,2)
    if not x % 5 :
        items.append(value)
print(','.join(items))

12 lv2

# Question:
# Write a program, which will find all such numbers between 1000 and 3000 (both included)
# such that each digit of the number is an even number.
# The numbers obtained should be printed in a comma-separated sequence on a single line.
# 找出1000到3000之间的所有偶数,并且把它们用以逗号隔开的形式单行输出
even_nums=[x for x in range(1000,3001)]
save=[]
for even_num in even_nums:
    if even_num % 2 == 0:
       save.append(str(even_num))
print(','.join(save))

13 lv2

# Question:
# Write a program that accepts a sentence and calculate the number of letters and digits.
# Suppose the following input is supplied to the program:
# hello world! 123
# Then, the output should be:
# LETTERS 10
# DIGITS 3
# 写一个这样的程序:接收一个句子并且计算其中的字母数和数字的数量,
# 输入格式如下:
# hello world! 123
# 输出格式如下:
# LETTERS 10
# DIGITS 3
sentence = input()
sentence.lower()
l_count = 0
d_count = 0
for i in range(len(sentence)):
    if 'a' <= sentence[i] <= 'z':
        l_count += 1
    elif '0' <= sentence[i] <= '9':
        d_count += 1
print('LETTERS %d'%l_count)
print('DIGITS %d'%d_count)

s = input()
d={"DIGITS":0, "LETTERS":0}
for c in s:
    if c.isdigit():
        d["DIGITS"]+=1
    elif c.isalpha():
        d["LETTERS"]+=1
    else:
        pass
print("LETTERS", d["LETTERS"])
print("DIGITS", d["DIGITS"])

14 lv2

# Write a program that accepts a sentence and calculate the number of upper case letters
# and lower case letters.
# Suppose the following input is supplied to the program:
# Hello world!
# Then, the output should be:
# UPPER CASE 1
# LOWER CASE 9
# 写一个统计该句子中大写字母和小写字母数目的代码
# 输入应该是类似于:
# Hello world!
# 输出:
# UPPER CASE 1
# LOWER CASE 9
sentence=str(input())
d={'UPPER CASE':0 , 'LOWER CASE':0}
for letter in sentence:
    if letter.isupper():
        d['UPPER CASE']+=1
    elif letter.islower():
        d['LOWER CASE']+=1
print('UPPER CASE',d['UPPER CASE'])
print('LOWER CASE',d['LOWER CASE'])

15 lv2

# Question:
# Write a program that computes the value of a+aa+aaa+aaaa with a given digit
# as the value of a.
# Suppose the following input is supplied to the program:
# 9
# Then, the output should be:
# 11106
# 输入一个数字a,计算a+aa+aaa+aaaa
# 输入:
# 9
# 输出:
# 11106
a=str(input())
c=a
count = 1
sums = 0
while count < 5:
    b = int(a)
    sums =sums+b
    a=a+c
    count+=1
print(sums)

a = input()
n1 = int( "%s" % a )
n2 = int( "%s%s" % (a,a) )
n3 = int( "%s%s%s" % (a,a,a) )
n4 = int( "%s%s%s%s" % (a,a,a,a) )
print(n1+n2+n3+n4)

16 lv2

列表表达式的应用。

# Question:
# Use a list comprehension to square each odd number in a list.
# The list is input by a sequence of comma-separated numbers.
# Suppose the following input is supplied to the program:
# 1,2,3,4,5,6,7,8,9
# Then, the output should be:
# 1,3,5,7,9
# 用列表表达式输入一个列表中的奇数
# 列表是通过由逗号隔开的数字输入的
# 如,输入:
# 1,2,3,4,5,6,7,8,9
# 输出:
# 1,3,5,7,9
list1=[num for num in input().split(',') if int(num) % 2 != 0]
print(','.join(list1))

17 lv2

# Question:
# Write a program that computes the net amount of a bank account based a transaction log
# from console input. The transaction log format is shown as following:
# D 100
# W 200
# D means deposit while W means withdrawal.
# Suppose the following input is supplied to the program:
# D 300
# D 300
# W 200
# D 100
# Then, the output should be:
# 500
# 编写一个程序,根据控制台输入的事务日志计算银行账户的净金额。
# 事务日志格式如下:
# D 100
# W 200
# D表示存款,W表示取款。
# 假设向程序提供了以下输入:
# D 300
# D 300
# W 200
# D 100
# 那么,输出应该是:
# 500
dic={'D':0,'W':0}
list1=[]
while True:
    x=input()
    if x:
        list1=x.split(' ')
        if list1[0] == 'D':
            dic['D']=int(list1[1])+(dic['D'])
        elif list1[0] == 'W':
            dic['W']=int(list1[1])+dic['W']
        else:
            pass
    else:
        break
print(dic['D']-dic['W'])


netAmount = 0
while True:
    s = raw_input()
    if not s:
        break
    values = s.split(" ")
    operation = values[0]
    amount = int(values[1])
    if operation=="D":
        netAmount+=amount
    elif operation=="W":
        netAmount-=amount
    else:
        pass
print netAmount

18 lv2(re模块)

这道题我的方法显然显得有些过于复杂了,代码量较大,在python中没有switch语句,但是可以用if–elif来代替,可以实现题目要求功能。答案中用re模块轻松的解决了这一问题。

# Question:
# A website requires the users to input username and password to register.
# Write a program to check the validity of password input by users.
# Following are the criteria for checking the password:
# 1. At least 1 letter between [a-z]
# 2. At least 1 number between [0-9]
# 1. At least 1 letter between [A-Z]
# 3. At least 1 character from [$#@]
# 4. Minimum length of transaction password: 6
# 5. Maximum length of transaction password: 12
# Your program should accept a sequence of comma separated passwords
# and will check them according to the above criteria.
# Passwords that match the criteria are to be printed, each separated by a comma.
# Example
# If the following passwords are given as input to the program:
# ABd1234@1,a F1#,2w3E*,2We3345
# Then, the output of the program should be:
# ABd1234@1
# 网站要求用户输入用户名和密码才能注册。
# 编写一个程序来检查用户输入的密码的有效性。
# 密码检查标准如下:
# 1 [a-z]之间至少有一个字母
# 2 [0-9]之间至少有一个数字
# 1 [A-Z]之间至少有一个字母
# 3 [$#@]中至少一个字符
# 4 交易密码最小长度:6
# 5 交易密码最大长度:12
# 您的程序应该接受一系列逗号分隔的密码,并将根据上述标准检查它们。
# 匹配条件的密码将被打印出来,每个密码之间用逗号分隔。
# (与实例不符似乎是用空格分开的)
# 例子
# 如果程序输入了以下密码:
# ABd1234@1 F1 # 2 w3e * 2 we3345
# 那么,程序的输出应该是:
# ABd1234@1



passwords=[s for s in input().split(' ')]
n=0
fit_ones=[]
for password in passwords:
    for i in range(len(password)):
        if 'a' <= password[i] <= 'z' :
            n+=1
            break
    for l in range(len(password)):
        if 'A' <=password[l] <= 'Z':
            n+=1
            break

    for j in range(len(password)):
        if '0' <= password[j] <= '9':
            n+=1
            break
    for k in range(len(password)):
        if password[k] == '@':
            n+=1
            break
        elif password[k] == '$':
            n+=1
            break
        elif password[k] == '#':
            n+=1
            break
    if 6 <= len(password) <= 12:
        n+=1
    if n == 5:
        fit_ones.append(password)
        n=0
    else:
        n=0
        continue
print(','.join(fit_ones))

import re
value = []
items=[x for x in input().split(' ')]
for p in items:
    if len(p)<6 or len(p)>12:
        continue
    else:
        pass
    if not re.search("[a-z]",p):
        continue
    elif not re.search("[0-9]",p):
        continue
    elif not re.search("[A-Z]",p):
        continue
    elif not re.search("[$#@]",p):
        continue
    elif re.search("\s",p):
        continue
    else:
        pass
    value.append(p)
print(",".join(value))

19 lv2

operator.itemgetter()函数

  • operator.itemgetter()定义了一个函数,所以在使用过程应该是像这样的。
from operator import itemgetter
a=list(range(1,11))
b=itemgetter(5,7,3)
print(a)
print(b(a))

输出结果如下:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
(6, 8, 4)

sorted(list,key=)

  • sorted()在使用过程中,可以通过定义一个匿名函数来确定一个列表中的元素的优先级,如题目所示:(同样也可以用itemgetter函数来实现)
# You are required to write a program to sort the (name, age, height) tuples
# by ascending order where name is string, age and height are numbers.
# The tuples are input by console. The sort criteria is:
# 1: Sort based on name;
# 2: Then sort based on age;
# 3: Then sort by score.
# The priority is that name > age > score.
# If the following tuples are given as input to the program:
# Tom,19,80
# John,20,90
# Jony,17,91
# Jony,17,93
# Json,21,85
# Then, the output of the program should be:
# [('John', '20', '90'), ('Jony', '17', '91'),
# ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]
# 我们希望有这样一个程序,将(姓名,年龄,高度)装在一个元组中,分组原则如下:
# 基于名字分组
# 然后基于年龄
# 最后基于分数(高度),优先级与上述顺序相同
# 例,输入:
# Tom,19,80
# John,20,90
# Jony,17,91
# Jony,17,93
# Json,21,85
# 输出:
#[('John', '20', '90'), ('Jony', '17', '91'),
# ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]
list1=[]
while True:
    x=input()
    if x:
        list1.append(x.split(','))
    else:
        break
list1.sort(key=lambda x: (x[0],x[1],x[2]))
for i in range(len(list1)):
    list1[i]=tuple(list1[i])
print(list1)


from operator import itemgetter, attrgetter

l = []
while True:
    s = input()
    if not s:
        break
    l.append(tuple(s.split(",")))

print(sorted(l, key=itemgetter(0,1,2)))

20 lv3(迭代器)

第一道lv3的题目哦
其实很简单,就是迭代器的使用,我是严格按照题目要求做的,但是答案似乎没有定义这个类。

# Question:
# Define a class with a generator which can iterate the numbers,
# which are divisible by 7, between a given range 0 and n.
#定义一个可以迭代数据的带生成器的类,在一个给定的范围0到n,输出可以被7整除的数

class divisible():
    def div(self):
        self.n=int(input())
        for i in range(self.n):
            if i % 7 ==0:
                yield i

y=divisible()
gen=y.div()
print([i for i in gen])
for i in gen:
    print(i)


def putNumbers(n):
    i = 0
    while i<n:
        j=i
        i=i+1
        if j%7==0:
            yield j

for i in putNumbers(100):
    print(i)

21 lv3

# Question£º
# A robot moves in a plane starting from the original point (0,0).
# The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps.
# The trace of robot movement is shown as the following:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# ¡­
# The numbers after the direction are steps.
# Please write a program to compute the distance from current position after a sequence of
# movement and original point.
# If the distance is a float, then just print the nearest integer.
# Example:
# If the following tuples are given as input to the program:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# Then, the output of the program should be:
# 2
# 有一个机器人我们可以通过如下的输入控制:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# 数字就是走的步数,机器人的初始点为(0,0),我们计算机器人在移动后距初始点的距离,如果输出结果是浮点数
# 那么就输出离该数最近的整数,如:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# 输出结果为2
import math
d={'UP':0,
   'DOWN':0,
   'RIGHT':0,
   'LEFT':0}
while True:
    robot=input()
    if robot:
        robot_act=robot.split(' ')
        if robot_act[0] == 'UP':
            d['UP']+=int(robot_act[1])
        elif robot_act[0] == 'DOWN':
            d['DOWN'] += int(robot_act[1])
        elif robot_act[0] == 'RIGHT':
            d['RIGHT'] += int(robot_act[1])
        elif robot_act[0] == 'LEFT':
            d['LEFT'] += int(robot_act[1])
        else:
            pass
    else:
        break
y=abs(d['UP']-d['DOWN'])
x=abs(d['RIGHT']-d['LEFT'])
dis=math.sqrt(math.pow(x,2)+math.pow(y,2))
print(round(dis))


22 lv3

	# Question:
# Write a program to compute the frequency of the words from the input.
# The output should output after sorting the key alphanumerically.
# Suppose the following input is supplied to the program:
# New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
# Then, the output should be:
# 2:2
# 3.:1
# 3?:1
# New:1
# Python:5
# Read:1
# and:1
# between:1
# choosing:1
# or:2
# to:1
# 写一个计算单词频率的程序,输出格式应该按照字母表顺序。
# 假使输入如下:
# New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
# 输出如下:
# 2:2
# 3.:1
# 3?:1
# New:1
# Python:5
# Read:1
# and:1
# between:1
# choosing:1
# or:2
# to:1
list1=[x for x in input().split(' ')]
freq={}#用字典储存结果

for word in list1:
    freq[word]=freq.get(word,0)+1

list2=list(freq.keys())
list2.sort()

for w in list2:
    print(f'{w}:{freq[w]}')

23–30(对函数和类有基本了解,且可以熟练使用的可以跳过这一部分,新手还是推荐稍微学习一下的)

因为题目比较简单,所以整合在一个程序里了

# Question:
#     Write a method which can calculate square value of number
# 写一个计算平方根的方法
import math
class cal():
    def square(self):
        return self*self
y=cal
print(y.square(int(input())))


# Question:
#     Python has many built-in functions, and if you do not know how to use it,
#     you can read document online or find some books.
#     But Python has a built-in document function for every built-in functions.
#     Please write a program to print some Python built-in functions documents,
#     such as abs(), int(), raw_input()
# python有很多内置函数,使用方法你可以在书上查阅,但是python有它自己的内置文件函数。
# 请写一个程序去打印一些内置函数文件,例如abs(), int(), raw_input()
print(abs.__doc__)
print(int.__doc__)

print(input.__doc__)

def squ(num):
    '''
    计算一个数的平方数
    最好使用整数,否则可能会出现精度缺失
    '''
    return num**2
print(squ(0.1))
print(squ(5))
print(squ.__doc__)



# Question:
#     Define a class, which have a class parameter and have a same instance parameter.
#定义一个类,这个类中有一个类参数和一个实例参数
class Stu():
    #定义一个类参数
    name = 'stu'
stu= Stu
stu.name='Wang'
print(stu.name)
#这是答案给的解决方案
class Person:
    # Define the class parameter "name"
    name = "Person"

    def __init__(self, name=None):
        # self.name is the instance parameter
        self.name = name


jeffrey = Person("Jeffrey")
print("%s name is %s" % (Person.name, jeffrey.name))

nico = Person()
nico.name = "Nico"
print("%s name is %s" % (Person.name, nico.name))



# Question:
# Define a function which can compute the sum of two numbers.
# 定义一个可以计算两数和的函数
def c_sum(num1 , num2):
    return num1 + num2
print(c_sum(int(input()),int(input())))



# Question:
# Define a function that can convert a integer into a string and print it in console.
# 定义一个将整数转换为字符串并将其打印在控制台的函数
def convert(integer):
    string=str(integer)
    return string
print(convert(9))



# Question:
# Define a function that can receive two integral numbers in string form
# and compute their sum and then print it in console.
# 定义一个可以接受两个字符串型的整数,并且计算它们的和
def st_sum(string1, string2):
    return int(string1)+int(string2)
print(st_sum(1,2))



#
# Question:
# Define a function that can accept two strings as input
# and concatenate them and then print it in console.
# 定义一个可以接受两个字符串并且将它们连接的函数
def concatenate(string1 , string2):
    return str(string2)+str(string1)
print(concatenate(1,2))


# Question:
# Define a function which can print a dictionary where the keys are numbers between
# 1 and 3 (both included) and the values are square of keys.
# 定义一个函数,这个函数可以输出key值在1到3之间的数并且value值是Key的平方的字典
def gene_dic(n):
    d={x:x**2 for x in range(1,n+1)}
    return d


print(gene_dic(3))


def printDict():
    d = dict()
    d[1] = 1
    d[2] = 2 ** 2
    d[3] = 3 ** 2
    print(d)


printDict()

# Question:
# Define a function which can print a dictionary where the keys are numbers
# between 1 and 20 (both included) and the values are square of keys.
# 定义一个函数,这个函数可以输出key值在1到20之间的数并且value值是Key的平方的字典

print(gene_dic(20))


def printDict1():
    d = dict()
    for i in range(1, 21):
        d[i] = i ** 2
    print(d)


printDict1()


# Question:
# Define a function which can generate a dictionary where the keys are numbers between 1 and 20
# (both included) and the values are square of keys.
# The function should just print the values only.
# 定义一个函数,这个函数可以输出key值在1到20之间的数并且value值是Key的平方。函数只输出value值

# for i in range(1,21):
#     print(gene_dic(20)[i])
print(gene_dic(20).values())

def printDict2():
	d=dict()
	for i in range(1,21):
		d[i]=i**2
	for (k,v) in d.items():
		print(v)

printDict2()

# Question:
# Define a function which can generate a dictionary where the keys are numbers between 1 and
# 20 (both included) and the values are square of keys.
# The function should just print the keys only.
# 定义一个函数,这个函数可以输出key值在1到20之间的数并且value值是Key的平方。函数只输出key值

print(gene_dic(20).keys())


def printDict3():
    d = dict()
    for i in range(1, 21):
        d[i] = i ** 2
    for k in d.keys():
        print(k)


printDict3()



# Question:
# Define a function which can generate a list
# where the values are square of numbers between 1 and 20 (both included).
# Then the function needs to print the first 5 elements in the list.
#
# 定义一个生成一个1-20平方的列表的函数.然后输出前5个元素
def gene_list(n):
    list1=[x**2 for x in range(1,n+1)]
    return list1
print(gene_list(20)[:5])


def printList1():
    li = list()
    for i in range(1, 21):
        li.append(i ** 2)
    print(li[:5])

printList1()

# Question:
# Define a function which can generate a list
# where the values are square of numbers between 1 and 20 (both included).
# Then the function needs to print the last 5 elements in the list.
# 定义一个生成一个1 - 20平方的列表的函数.然后输出后5个元素
print(gene_list(20)[-5:])


def printList2():
    li = list()
    for i in range(1, 21):
        li.append(i ** 2)
    print(li[-5:])


printList2()


# Question:
# Define a function which can generate a list
# where the values are square of numbers between 1 and 20 (both included).
# Then the function needs to print all values except the first 5 elements in the list.
# 定义一个生成一个1 - 20平方的列表的函数.然后输出除前5个元素所有值

print(gene_list(20)[5:])

def printList3():
	li=list()
	for i in range(1,21):
		li.append(i**2)
	print(li[5:])


printList3()


# Question:
# Define a function which can generate and print a tuple
# where the value are square of numbers between 1 and 20 (both included).
# 定义一个生成一个1 - 20平方的元组的函数.然后输出除前5个元素所有值
def gene_tuple(n):
    tuple1=tuple([x**2 for x in range(1,n+1)])
    return tuple1
print(gene_tuple(20)[:5])

# Question:
# With a given tuple (1,2,3,4,5,6,7,8,9,10),
# write a program to print the first half values in one line and
#the last half values in one line.
#给定一个元组(1,2,3,4,5,6,7,8,9,10),写一个程序可以一行一行输出前一半和后一半的数据。
tuple1=tuple(list(x for x in range(1,11)))
print(tuple1[:5])
print(tuple1[5:])

tp=(1,2,3,4,5,6,7,8,9,10)
tp1=tp[:5]
tp2=tp[5:]
print(tp1)
print (tp2)


# Question:
# Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10).
# 写一个程序打印出另一个元组,其中的数值是给定元组(1,2,3,4,5,6,7,8,9,10)中的偶数。
tuple1=tuple(list(x for x in range(1,11)))
print(tuple(filter(lambda x:x%2==0,tuple1)))
#答案有错误!
tp=(1,2,3,4,5,6,7,8,9,10)
li=list()
for i in tp:
	if i%2==0:#tp[i]%2==0:
		li.append(i)

tp2=tuple(li)
print (tp2)

# Question:
# Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise print "No".
# 写一个接受字符串的程序,当这个字符串是"yes"或"YES"或"Yes"时输出"Yes",否则就输出"No"

string=input()
if string=='YES' or string=='Yes' or string=='yes':
    print('Yes')
else:
    print('No')

# Question:
# Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10].
# 用filter函数筛选出列表中的偶数,这个列表是[1,2,3,4,5,6,7,8,9,10]

list1=list(x for x in range(1,11))
print(list(filter(lambda x:x%2==0,list1)))

# Question:
# Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10].
# 用map函数将[1,2,3,4,5,6,7,8,9,10]所有的数平方

print(list(map(lambda x:x**2,list(x for x in range(1,11)))))

li = [1,2,3,4,5,6,7,8,9,10]
squaredNumbers = map(lambda x: x**2, li)
print(squaredNumbers)

# Question:
# Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10].
# 用map函数和filter函数将[1,2,3,4,5,6,7,8,9,10]所有的偶数平方

x=map(lambda x:x**2,filter(lambda x:x%2==0,list1))
print(list(x))

li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li))
print(evenNumbers)


您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论 9
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值