初学者 Python 编程面试问题

Python 是一种动态类型、通用、垃圾收集的高级编程语言,它专注于通过使用缩进来实现对读者友好的代码。Python 支持多种范式,例如过程式(逐步)编程、函数式编程和面向对象编程。

Python 由Guido von Rossum于 1991 年创建,其灵感来自英国喜剧团体 Monty Python’s Flying Circus 的名称。2008 年,Guido 决定,已经使用了很长时间的 Python 版本 2 有一些他和社区想要改变的东西。因此,在 2008 年,他们决定创建 Python 3,这是 2008 年发布的语言的新版本。Python 3 不向后兼容以前的版本。Python 版本 2 已于 2020 年停止使用,版本为 2.7.18。

Python 如何执行代码?

当我们谈论Python语言时,我们指的是实现。本质上,我们不是在谈论语言本身,因为Python这种语言只是一种规范。您可以将其视为某人写的一份文件,上面写着“嘿!当我写下defprint一词时,这在 Python 中意味着某些东西。但是翻译机呢?我们可以拥有很多。不同的解释器,不同的编译器。

例如,当下载Python时,我们实际上是在下载CPython,因为它是用C编程语言编写的。它是一个用 C 编写的程序,用于读取 Python 文件,然后在计算机上运行它。但还有其他实现。例如,Jython 项目这是一个用Java语言编写的翻译器PyPy,它是用 Python 编写的。所以,它是一个用 Python 编写的解释器或翻译机。还有像IronPython之类的东西,它是为dot net框架编写的。

当我们从Python下载时,官方语言是CPython我们正在下载遵循Python规范的解释器。但归根结底,它是一台由某人制造的机器,并且这些机器可以有多种形式。因此,当大多数人谈论 Python 时,他们谈论的是CPython,它负责我们的翻译。我们通过解释器CPython运行的 Python 文件会创建称为字节码的东西口译员在幕后自动为我们完成这项工作。

现在,一旦它创建了更接近机器代码的字节码,它就会使用运行该代码的CPython虚拟机或VM,然后该代码可以在我们的计算机、笔记本电脑、手机和许多其他设备上运行。因此,当我们从www.python.org下载时,我们下载的是解释器CPython VM这两个部分,我们可以运行 Python。

Python 代码执行

初学者需要了解的 Python 编程问题

Python 是整个科技行业最顶级的编程语言之一。在本文中,我们将讨论 Python 面试中提出的一些重要问题。

1. 展示一些示例来检查 Python 中数字的不同数据类型。

解决方案:

print(type(11))
print(type(11.05))
print(type(11.05j))
 
"""
Output:
 
<class 'int'>
<class 'float'>
<class 'complex'>
 
"""

2. 用 Python 编写模/余数、指数和底除运算的示例。

解决方案:

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
 
 
print(f"Modulo/Remainder: {num1 % num2}")
print(f"Exponent: {num1 ** num2}")
print(f"Floor Division: {num1 // num2}")
 
"""
Output:
 
Enter first number: 10
Enter second number: 3
Modulo/Remainder: 1
Exponent: 1000
Floor Division: 3
 
"""

3. 编写一个程序来查找三个用户输入数字中最大的数字。

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
 
if (num1 >= num2) and (num1 >= num3):
    largest = num1
elif (num2 >= num1) and (num2 >= num3):
    largest = num2
else:
    largest = num3
 
print("The largest number is", largest)
 
"""
Output:
 
Enter first number: 45
Enter second number: 67
Enter third number: 23
The largest number is 67.0
 
"""

4. 编写一个函数来计算两个数字的和。

解决方案:

def my_sum(num1, num2):
    return num1 + num2
 
print(my_sum(10, 39))  # Output: 49

5. 用Python编写一个匿名函数来计算两个数字的乘法。

解决方案:

multiply_func = lambda num1, num2: num1 * num2
 
print(multiply_func(2, 6))  # Output: 12

6. 编写一个 lambda 函数,将整数值转换为字符串值并打印输出。另外,检查输出类型。

解决方案:

conversion_func = lambda value: str(value)
 
result = conversion_func(123)
 
print(result)  # Output: 123
print(type(result))  # Output: <class 'str'>

7. 编写一个函数,接受两个字符串类型的数字并计算总和。

解决方案:

def my_sum(num1, num2):
    return int(num1) + int(num2)
 
print(my_sum("21", "34"))  # Output: 55

8. 编写一个函数来连接两个字符串输入。

解决方案:

concat_strings = lambda s1, s2: s1 + s2
 
print(concat_strings("123", "hello"))  # Output: 123hello
print(concat_strings("67", "89"))  # Output: 6789

如果您想更好地理解这个概念,我们还更详细地介绍了lambda 函数或匿名函数。

9. 编写一个程序,接受两个字符串并打印较长的字符串。

解决方案:

def compare_func(str1, str2):
 
    if len(str1) > len(str2):
        return f"{str1} is longer than {str2}"
 
    elif len(str1) < len(str2):
        return f"{str2} is longer than {str1}"
 
    elif len(str1) == len(str2):
        return f"{str1} and {str2} have same length"
 
 
print(compare_func("three", "four"))
# Output: three is longer than four
 
print(compare_func("one", "two"))
# Output: one and two have same length

您还可以了解有关Python 中 if-else 块的更多信息,以更好地掌握此代码。

10. 编写一个程序,找出所有能被 9 整除,但不是 6 的倍数的数字。这些数字应该在 300 到 500 之间(两者都应该包括在内)。结果应打印在一行中,每个结果应以逗号分隔。

解决方案:

my_list = []
for eachItem in range(300, 501):
    if (eachItem % 9 == 0) and (eachItem % 6 != 0):
        my_list.append(str(eachItem))
 
print(",".join(my_list))
 
"""
Output:
 
315,333,351,369,387,405,423,441,459,477,495
 
"""

这里我们使用Python 中的join 列表追加函数。

11. 编写一个程序来计算给定数字的阶乘。

解决方案:

def factorial_function(arg):
    if arg == 0:
        return 1
    return arg * factorial_function(arg - 1)
 
 
num = int(input("Enter a number: "))
 
print(f"Factorial {num} is {factorial_function(num)}")
 
"""
Output:
 
Enter a number: 7
Factorial 7 is 5040
 
"""

12. 编写一个程序,打印一个字典,其格式为 KEY: VALUE 对{num, num*num*num}“num”是应由用户输入的整数。结果字典应包含输入整数的整个长度的结果:例如:如果输入是 5,则结果应为{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

解决方案:

num = int(input("Enter a number: "))
result_dictionary = dict()
 
for eachItem in range(1, num + 1):
    result_dictionary[eachItem] = eachItem**3
 
print(result_dictionary)
 
 
"""
Output:
 
Enter a number: 5     
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
 
"""

13. 编写一个程序,要求输入项目列表并将其转换为元组。显示两个序列。

解决方案:

input_items = input("Enter a list of items: ")
my_list = input_items.split(",")
 
my_tuple = tuple(my_list)
 
print(my_list)
print(my_tuple)
 
"""
Output:
 
Enter a list of items: apple,orange
['apple', 'orange']
('apple', 'orange')
 
"""

14. 下面给出了一个对象类“Dog”,它在构造函数中将名称和年龄作为参数。写出下列问题的代码。

class Dog:
    # constructor
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    # Class Object Attribute
    scientific_name = "Canis lupus familiaris"
  • 问题 1:实例化此类中的 3 只狗,并标明名称和年龄。
  • 问题 2:打印出“scientific_name”属性。
  • 问题 3:编写一个函数来查找最年长的狗。
  • 问题 4:打印以下内容:“最年长的狗是 x 岁。” 使用第三个问题中的函数,x 将是最大的狗的年龄。

解决方案:

# 1 Instantiate the Dog object with 3 dogs
Dog1 = Dog("Arnold", 2)
Dog2 = Dog("Stan", 4)
Dog3 = Dog("Hufflepuff", 6)
 
# 2 Print out class attribute
print(f"The scientific name for Dog is {Dog.scientific_name}")
 
 
# 3 Create a function that finds the oldest dog
def oldest_dog(*args):
    return max(args)
 
 
# 4 Print out: "The oldest dog is x years old." x will be the oldest dog's age by using the function from the third question."
print(f"The oldest dog is {oldest_dog(Dog1.age, Dog2.age, Dog3.age)} years old")
 
"""
Output:
 
The scientific name for Dog is Canis lupus familiaris
The oldest dog is 6 years old
 
"""

15. 编写一个程序,接受一个句子作为输入,并按字母顺序打印出单词。在程序中使用列表理解。

解决方案:

words = [eachItem for eachItem in input("Enter a sentence: ").split(" ")]
words.sort()
 
print(f"Rearranged Sequence: {' '.join(words)}")
 
"""
Output:
 
Enter a sentence: hi how are you doing today
Rearranged Sequence: are doing hi how today you
 
"""

16. 编写一个程序,将一个句子作为输入。程序应该删除重复的单词,并按字母数字顺序排列/排序单词。

解决方案:

input_sentence = input("Enter a sentence: ")
words = [eachWord for eachWord in input_sentence.split(" ")]
print(" ".join(sorted(list(set(words)))))
 
"""
Output:
 
Enter a sentence: I felt happy because I saw the others were happy and because I knew I should feel happy
I and because feel felt happy knew others saw should the were
 
"""

17. 编写一个程序来计算输入句子的数字和字母的数量。

解决方案:

sentence = input("Enter a sentence with numbers as well: ")
letter_count, digit_count = 0, 0
 
for each in sentence:
    if each.isalpha():
        letter_count += 1
    elif each.isnumeric():
        digit_count += 1
print(
    f"Number of letters: {letter_count}\nNumber of digits: {digit_count}"
 
"""
Output:
 
Enter a sentence with numbers as well: my name is alpha47
Number of letters: 13
Number of digits: 2
 
"""

18. 编写一个程序,计算输入句子中大写和小写字母的数量。

解决方案:

sentence = input("Enter a sentence with different cases: ")
num_upper, num_lower = 0, 0
 
for each in sentence:
    num_lower += each.islower()
    num_upper += each.isupper()
 
print(
    f"Numer of Upper Case Letters: {num_upper}\nNumer of Lower Case Letters: {num_lower}"
)
 
 
"""
Output:
 
Enter a sentence with different cases: HELLO My Name is QUINN
Numer of Upper Case Letters: 12
Numer of Lower Case Letters: 6
 
"""

19. 编写一个程序来计算序列 (z + zz + zzz + zzzz + zzzzz) 的值,其中“z”是用户输入的数字。

解决方案:

def calc_func(num):
    return sum(int(num * n) for n in range(1, 6))
 
 
digit_value = input("Enter a digit between 0 to 9: ")
 
print(f"The sequence total is: {calc_func(digit_value)}")
 
"""
Output:
 
Enter a digit between 0 to 9: 7
The sequence total is: 86415
 
"""

20. 使用Python functools 模块中的reduce 函数,编写一个程序来计算序列(z + zz + zzz + zzzz + zzzzz) 的值,其中“z”是用户输入的数字。

解决方案:

from functools import reduce
 
input_digit = input("Enter a digit between 0 to 9: ")
total = reduce(
    lambda accumulator, eachItem: int(accumulator) + int(eachItem),
    [input_digit * i for i in range(1, 6)],
)
 
print(f"The sequence total with the reduce function is: {total}")
 
"""
Output:
 
Enter a digit between 0 to 9: 7
The sequence total with the reduce function is: 86415
 
"""

21. 从用户提供的数字列表中,编写一个程序来查找偶数并打印立方体。

解决方案:

my_list = input("Enter a list of numbers: ")
 
only_even_cubed_list = [
    str(int(eachNum) ** 3) for eachNum in my_list.split(",") if int(eachNum) % 2 == 0
]
 
print(f"The new list is: {','.join(only_even_cubed_list)}")
 
"""
Output:
 
Enter a list of numbers: 3,5,2,7,8
The new list is: 8,512
 
"""

22. 编写一个程序,根据作为输入提供的交易金额计算银行帐户中的金额。

解决方案:

acc_balance = 0
confirm_msg = "Account balance Updated Successfully!"
 
while True:
    user_request = input(
        "B for Balance|| D for Deposit || W for Withdraw || E for Exit: "
    ).lower()
 
    if user_request == "d":
        add_balance = input("Enter deposit amount: ")
        acc_balance = acc_balance + int(add_balance)
        print(confirm_msg)
 
    elif user_request == "w":
        withdraw_amount = input("Enter withdrawal amount: ")
        acc_balance = acc_balance - int(withdraw_amount)
        print(confirm_msg)
 
    elif user_request == "b":
        print(acc_balance)
 
    else:
        quit()
 
"""
 
Output:
 
B for Balance|| D for Deposit || W for Withdraw || E for Exit: d
Enter deposit amount: 1200
Account balance Updated Successfully!
B for Balance|| D for Deposit || W for Withdraw || E for Exit: w
Enter withdrawal amount: 500
Account balance Updated Successfully!
B for Balance|| D for Deposit || W for Withdraw || E for Exit: b
700
B for Balance|| D for Deposit || W for Withdraw || E for Exit: e
 
"""

23. 编写一个 Python 类和一个生成器,可以遍历可被 3 整除的数字范围并打印出这些数字。

解决方案:

class CalcFunc:
    def three_divisor(self, num):
        for eachNum in range(1, num + 1):
            if eachNum % 3 == 0:
                yield eachNum
 
 
my_instance = CalcFunc()
 
user_number = int(input("Enter a number: "))
 
generator_function = my_instance.three_divisor(user_number)
 
for eachItem in generator_function:
    print(eachItem)
 
"""
Output:
 
Enter a number: 10
3
6
9
 
"""

24. 编写一个程序来统计用户输入中每个单词出现的次数。另外,打印结果,其中键按字母数字排序。请参阅下面的示例输入和输出语句。

Input: I bought 3 oranges and finished eating all 3 of them.
 
Expected Output:
 
'3' x 2 times
'I' x 1 times
'all' x 1 times
'and' x 1 times
'bought' x 1 times
'eating' x 1 times
'finished' x 1 times
'of' x 1 times
'oranges' x 1 times
'them.' x 1 times

解决方案:

user_input_sentence = input("Enter a sentence: ")
splitted = user_input_sentence.split()
 
unique_and_sorted = sorted(set(splitted))
 
for eachItem in unique_and_sorted:
    print(f"'{eachItem}' x {user_input_sentence.count(eachItem)} times")
 
 
"""
Output:
 
Enter a sentence: I bought 3 oranges and finished eating all 3 of them.
'3' x 2 times
'I' x 1 times
'all' x 1 times
'and' x 1 times
'bought' x 1 times
'eating' x 1 times
'finished' x 1 times
'of' x 1 times
'oranges' x 1 times
'them.' x 1 times
 
"""

25.如何查看Python内置函数的文档?举例说明。另外,为自定义函数编写文档。

print(float.__doc__)
# Output: Convert a string or number to a floating point number, if possible.
 
print(abs.__doc__)
# Output: Return the absolute value of the argument.
def cube(num):
    """
    Docstring: Returns the cube of a number
    """
    return num**3
 
 
print(cube(5))
print(cube.__doc__)
 
"""
Output:
 
125
 
    Docstring: Returns the cube of a number
 
"""

26. 编写一个程序将温度从摄氏温度转换为华氏温度,反之亦然。公式:Celcius = (5 / 9) * (Fahrenheit - 32)

解决方案:

input_temperature = float(input("Enter a temperature value: "))
input_unit = input(
    "Choose a unit for the above temperature: C for Celcuis || F for Fahrenheit: "
)
 
 
if input_unit == "C" or input_unit == "c":
    temp_in_F_units = 9 / 5 * input_temperature + 32
    print(f"Temperature in Fahrenheit is {temp_in_F_units}")
 
elif input_unit == "F" or input_unit == "f":
    temp_in_C_units = 5 / 9 * (input_temperature - 32)
    print(f"Temperature in Celsius is {temp_in_C_units}")
else:
    print("Invalid unit provided")
 
"""
Output:
 
Enter a temperature value: 40
Choose a unit for the above temperature: C for Celcuis || F for Fahrenheit: c
Temperature in Fahrenheit is 104.0
 
"""

27. 编写一个程序来计算作为输入参数提供的前 n 个自然数的立方和。

解决方案:

def series_summation_func(num):
    accumulated_sum = 0
 
    for eachNum in range(1, num + 1):
        accumulated_sum += eachNum**3
 
    return accumulated_sum
 
 
print(series_summation_func(4))  # Output: 100
print(series_summation_func(5))  # Output: 225

28. 编写一个程序来检查用户输入的数字是否是素数。

解决方案:

user_input = int(input("Please enter a number: "))
 
is_prime = True
 
if user_input > 1:
    # Factor Checking
    for each in range(2, user_input):
        if user_input % each == 0:
            is_prime = False
            break
 
if is_prime:
    print(f"{user_input} is a prime number.")
else:
    print(f"{user_input} is a not prime number.")
 
 
"""
Output:
 
Please enter a number: 23
23 is a prime number.
 
"""

29. 编写一个函数,根据用户输入的半径计算圆的面积。

解决方案:

def calc_circle_area(radius):
    PI = 3.147
    return PI * (radius**2)
 
 
input_radius = float(input("Please enter a radius value: "))
print(f"Area of the circle is {calc_circle_area(input_radius)} ")
 
"""
Output:
 
Please enter a radius value: 10
Area of the circle is 314.7
 
"""

30. 编写一个程序从给定的数字列表中查找最大的偶数。

解决方案:

my_list = [11, 2, 3, 4, 14, 8, 10]
 
 
def highest_even_func(lst):
    even_list = []
 
    for eachItem in lst:
        if eachItem % 2 == 0:
            even_list.append(eachItem)
 
    return max(lst)
 
 
val = highest_even_func(my_list)
print(f"Highest even number in the list is {val}")
 
# Output: Highest even number in the list is 14

31. 编写一个程序从给定列表中查找重复项并将这些项目打印到新列表中。

解决方案:

my_list = ["a", "a", "b", "c", "a", "e", "d", "c", "c", "e"]
 
list_of_duplicates = []
 
for eachItem in my_list:
    if my_list.count(eachItem) > 1:
        if eachItem not in list_of_duplicates:
            list_of_duplicates.append(eachItem)
 
print(list_of_duplicates)  # Output: ['a', 'c', 'e']

32. 使用列表理解,编写与上面相同的程序,从给定列表中打印出重复项目的新列表。

解决方案:

some_random_list = ["b", "n", "m", "n", "a", "b", "c"]
 
list_with_duplicate_items = list(
    set([value for value in some_random_list if some_random_list.count(value) > 1])
)
print(list_with_duplicate_items)
 
# Output: ['b', 'n']

33. 编写一个程序,将所有列表项转换为 2 次方并输出一个新列表。

解决方案:

my_list = [12, 10, 31, 4, 7]
 
def squared(item):
    return item**2
 
mapped = map(squared, my_list)
 
print(f"Original List: {my_list}")
print(f"Squared List: {list(mapped)}")
 
"""
Output:
 
Original List: [12, 10, 31, 4, 7]
Squared List: [144, 100, 961, 16, 49]
 
"""

34.Python中的reduce函数如何使用?举个例子。

解决方案:

from functools import reduce
 
my_list = [1, 2, 3, 4]
 
def add_numbers(accumulator, number):
    return accumulator + number
 
# reduce(function, iterable, initial_value)
result_obtained = reduce(add_numbers, my_list, 10)
 
print(f"Accumulated Result is {result_obtained}")
 
# Output: Accumulated Result is 20

35. 编写一个程序来检查输入字符串是否是回文。

解决方案:

my_str = input("Enter a string: ")
 
my_str = my_str.lower()
 
rev_str = reversed(my_str)
 
if list(my_str) == list(rev_str):
    print("The input string is a palindrome.")
else:
    print("The input string is not a palindrome.")
 
 
"""
Output:
 
Enter a string: MAlAYaLAm
The input string is a palindrome.
 
"""

结论

这些是 Python 面试中最常见的一些编程问题。掌握解决给定问题的基本概念和语法非常重要。最重要的是,需要大量的时间和努力才能擅长编码。因此,祝您在编码面试中取得好运,我希望本文能够以某种方式帮助您更好地解决 Python 编程问题。快乐编码!