30 Python practice questions worth collecting (with detailed explanations)

王林
Release: 2023-04-14 18:01:06
forward
1784 people have browsed it

30 Python practice questions worth collecting (with detailed explanations)

1. Given that a string is "hello_world_yoyo", how to get a queue ["hello","world","yoyo"]?

Use the split function to split the string and convert the data into a list type:

test = 'hello_world_yoyo'
print(test.split("_"))
12
Copy after login

Result:

['hello', 'world', 'yoyo']
Copy after login

2. There is a list [“hello”, “world ", "yoyo"], how to connect the strings in the list to get the string "hello_world_yoyo"?

Use the join function to convert the data into a string:

test = ["hello", "world", "yoyo"]
print("_".join(test))
Copy after login

Result:

hello_world_yoyo
Copy after login

If you do not rely on the join method provided by python, you can also use a for loop and then add the characters String splicing, but when using " " to connect strings, the result will generate a new object. When using join, the result is just to splice the elements in the original list, so join is more efficient.

The for loop is spliced ​​as follows:

test = ["hello", "world", "yoyo"]
# 定义一个空字符串
j = ''
# 通过 for 循环打印出列表中的数据
for i in test:
 j = j + "_" + i
# 因为通过上面的字符串拼接,得到的数据是“_hello_world_yoyo”,前面会多一个下划线_,所以把这个下划线去掉
print(j.lstrip("_"))
Copy after login

3. Replace each space in the string s with " ", input: s = "We are happy.", output: "We are happy."

Use the replace function and replace the characters:

s = 'We are happy.'
print(s.replace(' ', '%20'))
12
Copy after login

Result:

We%20are%20happy.
Copy after login

4. How to print the 99 multiplication table in Python?

for loop printing:

for i in range(1, 10):
 for j in range(1, i+1):
 print('{}x{}={}t'.format(j, i, i*j), end='')
 print()
Copy after login

while loop implementation:

i = 1
while i <= 9:
 j = 1
 while j <= i:
 print("%d*%d=%-2d"%(i,j,i*j),end = ' ')# %d: 整数的占位符,'-2'代表靠左对齐,两个占位符
 j += 1
 print()
 i += 1
Copy after login

Result:

1x1=1
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
1x4=4 2x4=8 3x4=12 4x4=16
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81
Copy after login

5. Start indexing from subscript 0 and find the word " welcome" appears in the string "Hello, welcome to my world." and returns -1 if it cannot be found.

def test():
 message = 'Hello, welcome to my world.'
 world = 'welcome'
 if world in message:
 return message.find(world)
 else:
 return -1
print(test())
Copy after login

Result:

7
Copy after login

6. Count the number of times the letter w appears in the string "Hello, welcome to my world."

def test():
 message = 'Hello, welcome to my world.'
 # 计数
 num = 0
 # for 循环 message
 for i in message:
 # 判断如果 ‘w’ 字符串在 message 中,则 num +1
 if 'w' in i:
 num += 1
 return num
print(test())
# 结果
2
Copy after login

7. Input a string str and output the m-th character that only appears n times. For example, in the string gbgkkdehh, find the second character that only appears once and output the result: d

def test(str_test, num, counts):
 """
 :param str_test: 字符串
 :param num: 字符串出现的次数
 :param count: 字符串第几次出现的次数
 :return:
 """
 # 定义一个空数组,存放逻辑处理后的数据
 list = []
 # for循环字符串的数据
 for i in str_test:
 # 使用 count 函数,统计出所有字符串出现的次数
 count = str_test.count(i, 0, len(str_test))
 # 判断字符串出现的次数与设置的counts的次数相同,则将数据存放在list数组中
 if count == num:
 list.append(i)
 # 返回第n次出现的字符串
 return list[counts-1]
print(test('gbgkkdehh', 1, 2))
结果:
d
Copy after login

8. Determine whether the string a = “welcome to my world” contains the word b = “world”. If it does, it will return True, if it does not, it will return False.

def test():
 message = 'welcome to my world'
 world = 'world'
 if world in message:
 return True
 return False
print(test())
结果:
True
Copy after login

9. Start counting from 0 and output the specified string

def test():
 message = 'hi how are you hello world, hello yoyo!'
 world = 'hello'
 return message.find(world)
print(test())
结果:
15
Copy after login

10. Start counting from 0 and output the specified string A = “hello” in string B = “hi how are you hello world, hello yoyo!", if B does not contain A, then -1 is output.

def test(string, str):
 # 定义 last_position 初始值为 -1
 last_position = -1
 while True:
 position = string.find(str, last_position+1)
 if position == -1:
 return last_position
 last_position = position
print(test('hi how are you hello world, hello yoyo!', 'hello'))
结果:
28
Copy after login

11. Given a number a, determine whether a number is odd or even.

while True:
 try:
 # 判断输入是否为整数
 num = int(input('输入一个整数:'))
 # 不是纯数字需要重新输入
except ValueError:
 print("输入的不是整数!")
 continue
 if num % 2 == 0:
 print('偶数')
 else:
 print('奇数')
 break
结果:
输入一个整数:100
偶数
Copy after login

12. Enter a name to determine whether the surname is Wang.

def test():
 user_input = input("请输入您的姓名:")
 if user_input[0] == '王':
 return "用户姓王"
 return "用户不姓王"
print(test())
结果:
请输入您的姓名:王总
用户姓王
Copy after login

13. How to determine whether a string is composed of pure numbers?

Use the type conversion provided by Python to convert the data input by the user into a floating point number type. If the conversion throws an exception, it is judged that the number is not composed of pure numbers.

def test(num):
 try:
 return float(num)
 except ValueError:
 return "请输入数字"
print(test('133w3'))
Copy after login

14. Convert the string a = “This is string example….wow!” to all uppercase, and convert the string b = “Welcome To My World” to all lowercase.

a = 'This is string example….wow!'
b = 'Welcome To My World'
print(a.upper())
print(b.lower())
Copy after login

15. Remove the leading and trailing spaces from the string a = "welcome to my world"

Python provides the strip() method to remove the leading and trailing spaces, rstrip() removes the trailing spaces, lstrip () removes leading spaces, replace(" ", "") removes all spaces.

a = 'welcome to my world '
print(a.strip())
Copy after login

It can also be realized through recursion:

def trim(s):
 flag = 0
 if s[:1]==' ':
 s = s[1:]
 flag = 1
 if s[-1:] == ' ':
 s = s[:-1]
 flag = 1
 if flag==1:
 returntrim(s)
 else:
 return s
print(trim('Hello world!'))
Copy after login

Through while loop:

def trim(s):
 while(True):
 flag = 0
 if s[:1]==' ':
 s = s[1:]
 flag = 1
 if s[-1:] == ' ':
 s = s[:-1]
 flag = 1
 if flag==0:
 break
 return s
print(trim('Hello world!'))
Copy after login

16. String s = "ajldjlajfdljfddd", remove duplicates and go from small to small Large sort output "adfjl".

def test():
 s = 'ajldjlajfdljfddd'
 # 定义一个数组存放数据
 str_list = []
 # for循环s字符串中的数据,然后将数据加入数组中
 for i in s:
 # 判断如果数组中已经存在这个字符串,则将字符串移除,加入新的字符串
 if i in str_list:
 str_list.remove(i)
 str_list.append(i)
 # 使用 sorted 方法,对字母进行排序
 a = sorted(str_list)
 # sorted方法返回的是一个列表,这边将列表数据转换成字符串
 return "".join(a)
print(test())
结果:
adfjl
Copy after login

17. Print out the following pattern (diamond):

30 Python practice questions worth collecting (with detailed explanations)

def test():
 n = 8
 for i in range(-int(n/2), int(n/2) + 1):
 print(" "*abs(i), "*"*abs(n-abs(i)*2))
print(test())
结果:
 **
****
 ******
********
 ******
****
 **
Copy after login

18. Give a positive integer with no more than 5 digits (such as a = 12346 ), find out how many digits it is and print out the digits in reverse order.

class Test:
 # 计算数字的位数
 def test_num(self, num):
 try:
 # 定义一个 length 的变量,来计算数字的长度
 length = 0
 while num != 0:
 # 判断当 num 不为 0 的时候,则每次都除以10取整
 length += 1
 num = int(num) // 10
 if length > 5:
 return "请输入正确的数字"
 return length
 except ValueError:
 return "请输入正确的数字"
 # 逆序打印出个位数
 def test_sorted(self, num):
 if self.test_num(num) != "请输入正确的数字":
 # 逆序打印出数字
 sorted_num = num[::-1]
 # 返回逆序的个位数
 return sorted_num[-1]
print(Test().test_sorted('12346'))
结果:
1
Copy after login

19. If a 3-digit number is equal to the sum of the cubes of its digits, it is called a daffodil number. For example: 153 = 13 53 33, so 153 is a daffodil number. So how to find the number of daffodils within 1000 (3 digits).

def test():
 for num in range(100, 1000):
 i = num // 100
 j = num // 10 % 10
 k = num % 10
 if i ** 3 + j ** 3 + k ** 3 == num:
 print(str(num) + "是水仙花数")
test()
Copy after login

20. Find the sum of 1 2 3… 100.

i = 1
for j in range(101):
 i = j + i
print(i)
结果:
5051
Copy after login

21. Calculate the value of 1-2 3-4 5-…-100.

def test(sum_to):
 # 定义一个初始值
 sum_all = 0
 # 循环想要计算的数据
 for i in range(1, sum_to + 1):
 sum_all += i * (-1) ** (1 + i)
 return sum_all
if __name__ == '__main__':
 result = test(sum_to=100)
 print(result)
-50
Copy after login

22. The existing calculation formula is 13 23 33 43 ……. n3, how to implement: when input n = 5, the output is 225 (corresponding formula: 13 23 33 43 53 = 225).

def test(n):
 sum = 0
 for i in range(1, n+1):
 sum += i*10+i
 return sum
print(test(5))
结果:
225
Copy after login

23. It is known that the value of a is "hello" and the value of b is "world". How to exchange the values ​​​​of a and b to get the value of a to be "world" and the value of b to be "hello" "?

a = 'hello'
b = 'world'
c = a
a = b
b = c
print(a, b)
Copy after login

24. How to determine whether an array is a symmetric array?

For example [1, 2, 0, 2, 1], [1, 2, 3, 3, 2, 1], such arrays are all symmetric arrays. Use Python to judge whether it is a symmetric array that prints True, not False.

def test():
 x = [1, 'a', 0, '2', 0, 'a', 1]
 # 通过下标的形式,将字符串逆序进行比对
 if x == x[::-1]:
 return True
 return False
print(test())
结果:
True
Copy after login

25. If there is a list a = [1,3,5,7,11], then how to reverse it into [11,7,5,3,1] and get an odd number Place value of numbers [1,5,11]?

def test():
 a = [1, 3, 5, 7, 11]
 # 逆序打印数组中的数据
 print(a[::-1])
 # 定义一个计数的变量
 count = 0
 for i in a:
 # 判断每循环列表中的一个数据,则计数器中会 +1
 count += 1
 # 如果计数器为奇数,则打印出来
 if count % 2 != 0:
 print(i)
test()
结果:
[11, 7, 5, 3, 1]
1
5
11
Copy after login

26. Sort the numbers in the list a = [1, 6, 8, 11, 9, 1, 8, 6, 8, 7, 8] from small to large.

a = [1, 6, 8, 11, 9, 1, 8, 6, 8, 7, 8]
print(sorted(a))
结果:
[1, 1, 6, 6, 7, 8, 8, 8, 8, 9, 11]
Copy after login

27. Find the maximum and minimum values ​​in the list L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88].

L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]
print(max(L1))
print(min(L1))
结果:
88
1
Copy after login

The above is implemented through the functions that come with Python, as follows, you can write a calculation program yourself:

class Test(object):
 def __init__(self):
 # 测试的列表数据
 self.L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]
 # 从列表中取第一个值,对于数据大小比对
 self.num = self.L1[0]
 def test_small_num(self, count):
 """
 :param count: count为 1,则表示计算最大值,为 2 时,表示最小值
 :return:
 """
 # for 循环查询列表中的数据
 for i in self.L1:
 if count == 1:
 # 循环判断当数组中的数据比初始值小,则将初始值替换
 if i > self.num:
 self.num = i
 elif count == 2:
 if i < self.num:
 self.num = i
 elif count != 1 or count != 2:
 return "请输入正确的数据"
 return self.num
print(Test().test_small_num(1))
print(Test().test_small_num(2))
结果:
88
1
Copy after login

28. 找出列表 a = [“hello”, “world”, “yoyo”, “congratulations”] 中单词最长的一个。

def test():
 a = ["hello", "world", "yoyo", "congratulations"]

 # 统计数组中第一个值的长度
 length = len(a[0])
 for i in a:
 # 循环数组中的数据,当数组中的数据比初始值length中的值长,则替换掉length的默认值
 if len(i) > length:
 length = i
 return length
print(test())
结果:
congratulations
Copy after login

29. 取出列表 L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88] 中最大的三个值。

def test():
 L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]
 return sorted(L1)[:3]
print(test())
结果:
[1, 2, 2]
Copy after login

30. 把列表 a = [1, -6, 2, -5, 9, 4, 20, -3] 中的数字绝对值。

def test():
 a = [1, -6, 2, -5, 9, 4, 20, -3]
 # 定义一个数组,存放处理后的绝对值数据
 lists = []
 for i in a:
# 使用 abs() 方法处理绝对值
 lists.append(abs(i))
 return lists
print(test())
结果:
[1, 6, 2, 5, 9, 4, 20, 3]
Copy after login

The above is the detailed content of 30 Python practice questions worth collecting (with detailed explanations). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template