- Write a program that prints all even numbers from 1 to 100.
for i in range(2, 101, 2):
print(i)
- 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
- 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)
- 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)
- 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)
- 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:]
- 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('不是回文字符串')
- 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)
- 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)
- 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.