Python basic test questions (with answers)

  1. Write a program that prints all even numbers from 1 to 100.
for i in range(2, 101, 2):
    print(i)

  1. Write a function that takes a string as an argument and returns the sum of all numbers in the string.
def sum_of_numbers(s):
    sum = 0
    for c in s:
        if c.isdigit():
            sum += int(c)
    return sum

  1. Write a program to convert all string elements in a list to uppercase.
lst = ['hello', 'world', 'python']
lst_upper = [s.upper() for s in lst]
print(lst_upper)

  1. Write a function that takes two lists as arguments and returns all elements that are the same in both lists.
def common_elements(lst1, lst2):
    return set(lst1) & set(lst2)

  1. Write a program to input a string from the keyboard and capitalize the first letter of all the words in it.
s = input('请输入字符串:')
s_title = s.title()
print(s_title)

  1. Write a function that takes an integer as an argument and returns the binary representation of that integer.
def dec2bin(n):
    return bin(n)[2:]

  1. Write a program that inputs a string from the keyboard and checks whether the string is a palindrome.
s = input('请输入字符串:')
if s == s[::-1]:
    print('是回文字符串')
else:
    print('不是回文字符串')

  1. Write a function that takes a list as an argument and returns the maximum and minimum values ​​in that list.
def min_max(lst):
    return min(lst), max(lst)

  1. Write a program that takes a string input from the keyboard and replaces all spaces in it with underscores.
s = input('请输入字符串:')
s_new = s.replace(' ', '_')
print(s_new)

  1. Write a function that takes a string as an argument and returns the most frequently occurring character in that string.
def most_common_char(s):
    count = {
    
    }
    for c in s:
        if c in count:
            count[c] += 1
        else:
            count[c] = 1
    return max(count, key=count.get)

The above are the reference answers to ten Python basic training questions, hoping to help Python beginners better master the basic knowledge of Python.

Guess you like

Origin blog.csdn.net/achen0511/article/details/130723267