This article is participating in Python Theme Month. See the link to the event for more details


100 Basic Python Interview Questions Part 1 (1-20) | Python topic month

Q-1: What is Python, what are the benefits of using it, and what do you understand about PEP 8? Q-2: What is the output of the following Python snippet? Prove your answer. Q-3: What statements can be used in Python if the program does not need an action but syntactically requires it? Q-4: What is the process of using “~” to get the home directory in Python? Q-5: What are the built-in types available in Python? Q-6: How do I find errors or perform static analysis in a Python application? Q-7: When to use Python decorators? Q-8: What are the main differences between lists and tuples? Q-9: How does Python handle memory management? Q-10: What are the main differences between lambda and DEF? Q-11: Write a reg expression using the Python reg expression module “re” to verify the email ID? Q-12: What do you think the output of the following code snippet is? Are there any errors in the code? Q-13: Are there switch or case statements in Python? If not, what is the same reason? Q-14: What is Python’s built-in function for iterating over sequences of numbers? Q-15: What are the possible optional statements in Python’s try-except block? Q-16: What is a string in Python? Q-17: What is a slice in Python? Q-18: What is %s in Python? Q-19: Are strings immutable or mutable in Python? Q-20: What are indexes in Python?

Let’s get started on answering basic Python interview questions.

Q-1: What is Python, what are the benefits of using it, and what do you understand about PEP 8?

What is a Python

Python is one of the most successful interpreted languages. When you write a Python script, it does not need to be compiled before execution. Very few other interpreted languages are PHP and Javascript.

Benefits of Python programming

  • Python is a dynamically typed language. This means that you don’t need to mention the data type of the variable in the declaration. It allows setting variables such as VAR1 =101 and VAR2 = “You’re an engineer” without any errors.
  • Python supports object-oriented programming because you can define classes as well as composition and inheritance. It does not use public or private access specifiers.
  • Functions in Python are like first-class objects. It suggests that you can assign them to variables that are returned from other methods and passed as arguments.
  • Developing in Python is fast, but running it is generally slower than compiling languages. Fortunately, Python is able to include “C” language extensions, so you can optimize your scripts.
  • Python has many uses, such as Web-based applications, test automation, data modeling, big data analysis, and more. Alternatively, you can use it as a “glue” layer for other languages.

PEP 8

PEP 8 is the latest Python coding standard, a set of coding recommendations. It guides you to more readable Python code.

Return to the directory


Q-2: What is the output of the following Python snippet? Prove your answer.

def extendList(val, list= []) :
    list.append(val)
    return list

list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')

print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3
Copy the code

The result of the above Python snippet is:

list1 = [10.'a']
list2 = [123]
list3 = [10.'a']
Copy the code

You might mistakenly assume that list1 is equal to [10] and list3 matches [‘a’], assuming that every time extendList is called, the list argument is initialized to its default value [].

However, the process is like creating a new list after the function is defined. The same method is used every time someone calls the extendList method without a list argument. It works this way because the evaluation of the expression (in the default argument) happens when the function is defined, not during the call.

Thus, list1 and list3 run on the same default list, while list2 runs on a separate object of its own creation (by passing an empty list as the value of the list argument).

You can change the definition of the extendList function in the following ways.

def extendList(val, list=None) :
  if list is None:
    list = []
  list.append(val)
  return list
Copy the code

With this revised implementation, the output will be:

list1 = [10]
list2 = [123]
list3 = ['a']
Copy the code

Return to the directory


Q-3: What statements can be used in Python if the program does not require actions but the syntax does?

The pass statement is an empty operation. Nothing happens during execution. You should use the lowercase “pass” keyword. If you write “Pass”, you will get something like “NameError: Name Pass is not defined”. Python statements are case sensitive.

letter = "hai sethuraman"
for i in letter:
    if i == "a":
        pass
        print("pass statement is execute ..............")
    else:
        print(i)
Copy the code

Return to the directory


Q-4: What is the process of using “~” to get the home directory in Python?

You need to import the OS module and then do the rest in a single line.

import os
print (os.path.expanduser('~'))
Copy the code

Output:

/home/runner
Copy the code

Return to the directory


Q-5: What are the built-in types available in Python?

Here is a list of the most common built-in types supported by Python:

Python’s immutable built-in data types Python’s mutable built-in data types
digital The list of
string The dictionary
tuples A collection of

Return to the directory


Q-6: How do I find errors or perform static analysis in a Python application?

  • You can use PyChecker, which is a static parser. It identifies errors in Python projects and reveals errors related to style and complexity.
  • Another tool is Pylint, which checks to see if Python modules meet coding standards.

Return to the directory


Q-7: When to use Python decorators?

Python decorators are relative changes made in Python syntax to quickly adjust functionality.

Return to the directory


Q-8: What are the main differences between lists and tuples?

The main difference between lists and tuples is that the former is mutable, whereas tuples are not.

Tuples can be hashed, for example, using them as dictionary keys.

Return to the directory


Q-9: How does Python handle memory management?

  • Python uses a private heap to maintain its memory. So the heap contains all Python objects and data structures. This area is accessible only to the Python interpreter; Programmers can’t use it.
  • It is the Python memory manager that handles the private heap. It performs the required memory allocation for the Python object.
  • Python uses a built-in garbage collector, which reclaims all unused memory and offloads it into heap space.

Return to the directory


Q-10: What are the main differences between lambda and DEF?

  • Def can hold multiple expressions, whereas lambda is a single-expression function.
  • Def generates a function and specifies a name so that it can be called later. Lambda forms a function object and returns it.
  • Def can have a return statement. Lambda cannot have a return statement.
  • Lambda supports use in lists and dictionaries.

Return to the directory


Q-11: Write a reg expression using the Python reg expression module “re” to verify the email ID

Python has a regular expression module “re”.

View “re” expressions that can check E-mail ids for the.com and.co.in subfields.

import re 
print(re.search(r"[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$"."micheal.pages@mp. com"))
Copy the code

Return to the directory


Q-12: What do you think the output of the following code snippet is? Are there any errors in the code?

list = ['a'.'b'.'c'.'d'.'e']
print (list[10:)Copy the code

The result of the above line of code is []. There won’t be any errors like IndexError.

You should know that trying to get a member from a list using an index that exceeds the member count (for example, trying to access the list[10] given in the problem) will result in an IndexError. By the way, only slices above the starting index of no are retrieved. Items in the list do not cause IndexError. It just returns an empty list.

Return to the directory


Q-13: Are there switch or case statements in Python? If not, what is the same reason?

No, there is no Switch statement in Python, but you can write a Switch function and use it.

Return to the directory


Q-14: What is Python’s built-in function for iterating over sequences of numbers?

Range() generates a list of numbers to iterate over the for loop.

for i in range(5) :print(i)
Copy the code

The range() function takes two sets of arguments.

Range (stop)

  • Stop: It is not. The integer to be generated and started from zero. For example. Range (3) == [0, 1, 2].

Scope ([start], Stop [, step])

  • Start: This is the start number. In the sequence.
  • Stop: This specifies the upper limit of the sequence.
  • Step: Generate the increment factor of the sequence.

Notes:

  • Only integer arguments are allowed.
  • The parameters can be positive or negative.
  • The range() function in Python starts at the zeroth index.

Return to the directory


Q-15: What are the possible optional statements in Python’s try-except block?

You can use two optional clauses in the try-except block.

“Else” clause

  • This is useful if you want to run a piece of code without creating an exception in the try block.

“Finally” clause

  • It’s useful when you want to perform some run step, whether or not an exception occurs.

Return to the directory


Q-16: What is a string in Python?

A string in Python is a series of alphanumeric characters. They are immutable objects. This means that they are not allowed to change once they are assigned. Python provides a variety of methods, such as join(), replace(), or split(), to change strings. But none of this changes the original object.

Return to the directory


Q-17: What is a slice in Python?

Slicing is a string operation that extracts part of a string, or part of a list. In Python, a string (such as text) starts at index 0, and the NTH character is stored at position text[n-1]. Python can also perform reverse indexing with the help of negative numbers, that is, reverse indexing. In Python, slice() is also a constructor that generates slice objects. The result is a set of indexes referred to by range(start, stop, step). The slice() method allows three parameters. 1. Start – Start number of a slice. 2. Stop – Indicates the end of the slice. 3. step – incrementing value after each index (default = 1).

Return to the directory


Q-18: What is %s in Python?

Python supports formatting any value as a string. It can contain fairly complex expressions.

One common use is to push the value into a string with a %s format specifier. Formatting in Python has a similar syntax to the C function printf().

Return to the directory


Q-19: Are strings immutable or mutable in Python?

Python strings are indeed immutable.

Let’s take an example. We have a “STR” variable that holds the string value. We cannot change the container, which is a string, but we can change what it contains, which is the value of a variable.

Return to the directory


Q-20: What are indexes in Python?

An index is an integer data type that represents a position in an ordered list or string.

In Python, strings are also lists of characters. We can access them using an index from zero to length minus one.

For example, in the string “Program”, the index happens like this:

Program 0 1 2 3 4 5
Copy the code

Return to the directory


Summary – 100 basic Python interview questions

I’ve been writing a tech blog for a long time, and this is one of my interview questions to share. Hope you like it! Here is a summary of all my original and work source code:

Making, Gitee

Recommended articles of the past:

  • Teach you to use Java to make a gobang game
  • 30 Python tutorials and tips | Python theme month
  • Interesting way to talk about the history of JavaScript ⌛
  • The output of a Java program | Java exercises 】 【 7 sets (including parsing)
  • ❤️5 VS Code extensions that make refactoring easy ❤️
  • 140000 | 400 multichannel JavaScript 🎓 interview questions with answers 🌠 items (the fifth part 371-424)

If you do learn something new from this post, like it, bookmark it and share it with your friends. 🤗 Finally, don’t forget ❤ or 📑 for support