Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Friday, April 28, 2023

Top 24 Python Interview Questions and Answers

1. What is Python?

    Python is a high-level, interpreted programming language that is widely used for general-purpose programming, web development, scientific computing, data analysis, and artificial intelligence. It was first released in 1991 and is now one of the most popular programming languages in the world.

2. What are the benefits of using Python?

    Some of the key benefits of using Python include its ease of use, readability, portability, vast library of modules and frameworks, dynamic typing, and support for multiple programming paradigms such as object-oriented, functional, and procedural programming.


3. What is PEP 8?

    PEP 8 is a style guide for Python code that provides guidelines and best practices for writing readable, maintainable, and consistent code. It covers topics such as naming conventions, indentation, spacing, and commenting.


4. What are decorators in Python?

    Decorators are a feature in Python that allow you to modify the behavior of a function or class without changing its source code. Decorators are implemented as functions that take another function or class as input and return a new function or class with modified behavior.


5. What is a Python module?

    A Python module is a file containing Python code that defines functions, classes, and other objects that can be used in other Python programs. Modules are used to organize code, share code between programs, and prevent naming conflicts.


6. What is a lambda function in Python?

    A lambda function is a small, anonymous function in Python that can take any number of arguments, but can only have one expression. Lambda functions are often used as a quick and easy way to define small, throwaway functions.


7. What is a generator in Python?

    A generator in Python is a special type of function that can be used to generate a sequence of values on-the-fly, without generating the entire sequence in memory at once. Generators are useful for working with large datasets or infinite sequences of data.


8. What is a virtual environment in Python?

A virtual environment in Python is a self-contained directory that contains a specific version of the Python interpreter and any additional modules or packages needed for a specific project. Virtual environments are used to isolate different projects from each other and to ensure that each project uses the correct version of Python and its dependencies.


9. What is the difference between a list and a tuple in Python?

    A list is a mutable sequence of elements, whereas a tuple is an immutable sequence of elements. This means that you can add, remove, and modify elements in a list, but not in a tuple.


10. What is the difference between range and xrange in Python?

    range and xrange are both used to generate a sequence of numbers in Python, but range generates a list of numbers in memory, whereas xrange generates the numbers on-the-fly as you iterate over them. This means that xrange can be more memory-efficient for large sequences.


11. What is the difference between a shallow copy and a deep copy in Python?

    A shallow copy of a Python object creates a new object that references the same memory locations as the original object, whereas a deep copy creates a new object with its own copy of all the data. This means that changes to the original object will affect a shallow copy, but not a deep copy.


12. What is a module in Python?

    A module in Python is a file containing Python code that defines functions, classes, and other objects that can be used in other Python programs. Modules are used to organize code, share code between programs, and prevent naming conflicts.


13. What is a package in Python?

A package in Python is a collection of modules that are organized into a directory hierarchy. Packages are used to organize and share large sets of related modules and provide a namespace for the modules within them.


14. What is the Global Interpreter Lock (GIL) in Python?

    The Global Interpreter Lock (GIL) is a mechanism in Python that prevents multiple threads from executing Python bytecodes simultaneously. This means that only one thread can execute Python code at a time, even on multi-core CPUs. The GIL is designed to prevent race conditions and other thread-related issues, but can also limit the performance of multi-threaded Python programs.


15. What is a list comprehension in Python?

A list comprehension is a concise way to create a new list in Python by applying an expression to each element of an existing list or iterable. List comprehensions are often used as a shorthand way to filter and transform data in Python.


16. What is the difference between a function and a method in Python?

    A function in Python is a standalone block of code that takes inputs and returns outputs, whereas a method is a function that is associated with an object and can access and modify its state. Methods are defined inside classes and are called on instances of the class.


17. What is a decorator in Python?

    A decorator is a function that takes another function as input and returns a modified version of the input function. Decorators are often used to add functionality to an existing function without modifying its source code.


18. What is the difference between a local variable and a global variable in Python?

A local variable is a variable that is defined inside a function and can only be accessed within that function, whereas a global variable is a variable that is defined outside of any function and can be accessed from anywhere in the program.


19. What is a lambda function in Python?

    A lambda function is an anonymous function in Python that can be defined on a single line of code. Lambda functions are often used to define small, one-off functions that are passed as arguments to other functions.


20. What is the difference between a set and a frozenset in Python?

    A set is an unordered collection of unique elements, whereas a frozenset is an immutable set. This means that you can add, remove, and modify elements in a set, but not in a frozenset.


21. What is a generator in Python?

    A generator is a type of iterator in Python that generates values on-the-fly as they are requested, rather than generating all values at once and storing them in memory. Generators are often used to generate large sequences of values or to perform operations on large datasets in a memory-efficient way.


22. What is the difference between the append() and extend() methods of a list in Python?

    The append() method adds a single element to the end of a list, whereas the extend() method adds multiple elements to the end of a list. The elements added with extend() must be iterable.


23. What is the difference between the pass, continue, and break statements in Python?

    The pass statement does nothing and is used as a placeholder when no action is required. The continue statement skips to the next iteration of a loop. The break statement immediately exits the loop.


24. What is the purpose of the __init__ method in a Python class?

    The __init__ method is a special method in a Python class that is called when an object of the class is created. It is used to initialize the object's attributes and perform any other setup that is required.


Wednesday, November 16, 2022

Python Programming for Beginners Practice Exercises

Python

Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation. Python is dynamically-typed and garbage-collected. It supports multiple programming paradigms, including structured, object-oriented and functional programming.

Here is a list of practice exercises and solutions to get started with Python programming.

  1. Exercise 1 - Strings and Variables
  2. Exercise 2 - Strings and Variables
  3. Exercise 3 - Strings and Variables
  4. Exercise 4 - Numbers
  5. Exercise 5 - Numbers
  6. Exercise 6 - Booleans and Conditionals
  7. Exercise 7 - Functions
  8. Exercise 8 - Lists
  9. Exercise 9 - Dictionaries
  10. Exercise 10 - Tuples
  11. Exercise 11 - Modules
  12. Exercise 12 - Files
  13. Exercise 13 - Files

Strings and Variables 3 - Python Programming for Beginners Practice Exercise

Exercise 3:

Write a Python program that prompts for input and displays a cat "saying" what was provided by the user. Place the input provided by the user inside a speech bubble. Make the speech bubble expand or contract to fit around the input provided by the user.

Sample Output:


Solution:

#!/usr/bin/env python3

text = input('What would you like the cat to say? ')
text_length = len(text)

print('            {}'.format('_' * text_length))
print('          < {} >'.format(text))
print('            {}'.format('-' * text_length))
print('          /')
print(' /\_/\   /')
print('( o.o )')
print(' > ^ <')

Strings and Variables 2 - Python Programming for Beginners Practice Exercise

Exercise 2:

Write a Python program that prompts the user for input and simply repeats what the user entered.

Sample Output:

Please type something and press enter: Hello there!
You entered:
Hello there!

Solution:

#!/usr/bin/env python3

user_input = input('Please type something and press enter: ')
print('You entered:')
print(user_input)

Strings and Variables 1 - Python Programming for Beginners Practice Exercise

Exercise 1:

Write a Python program that uses three variables. The variables in your program will be animal, vegetable, and mineral. Assign a string value to each one of the variables. Your program should display "Here is an animal, a vegetable, and a mineral." Next, display the value for animal, followed by vegetable, and finally mineral. Each one of the values should be printed on their own line. Your program will display four lines in total.

Sample Output:

Here is an animal, a vegetable, and a mineral.

dog

tomato

gold

Solution:

#!/usr/bin/env python3
animal = 'dog'
vegetable = 'tomato'
mineral = 'gold'

print('Here is an animal, a vegetable, and a mineral.')
print(animal)
print(vegetable)
print(mineral)

Tuples - Python Programming for Beginners Practice Exercise 10

Exercise 10:

Create a list of airports that includes a series of tuples containing an airport's name and its code. Loop through the list and utilize tuple assignment. Use one variable to hold the airport name and another variable to hold the airport code. Display the airport's name and code to the screen.

Sample Output:

The code for O’Hare International Airport is ORD.

The code for Los Angeles International Airport is LAX.

The code for Dallas/Fort Worth International Airport is DFW.

The code for Denver International Airport is DEN.

Solution:

#!/usr/bin/env python3

airports = [
    ("O’Hare International Airport", 'ORD'),
    ('Los Angeles International Airport', 'LAX'),
    ('Dallas/Fort Worth International Airport', 'DFW'),
    ('Denver International Airport', 'DEN')
]

for (airport, code) in airports:
    print('The code for {} is {}.'.format(airport, code))

Numbers 1 - Python Programming for Beginners Practice Exercise 4

Exercise 4:

Building on the previous example, let's also assume that you have saved $918 to fund your new adventure. You wonder how many days you can keep one server running before your money runs out. Of course, you hope your social network becomes popular and requires 20 servers to keep up with the demand. How much will it cost to operate at that point?

Write a Python program that displays the answers to the following questions:

How much does it cost to operate one server per day?

How much does it cost to operate one server per month?

How much does it cost to operate twenty servers per day?

How much does it cost to operate twenty servers per month?

How many days can I operate one server with $918?

Solution:

#!/usr/bin/env python3

# The cost of one server per hour.
cost_per_hour = 0.51

# Compute the costs for one server.
cost_per_day = 24 * cost_per_hour
cost_per_month = 30 * cost_per_day

# Compute the costs for twenty servers
cost_per_day_twenty = 20 * cost_per_day
cost_per_month_twenty = 20 * cost_per_month

# Budgeting
budget = 918
operational_days = budget / cost_per_day

# Display the results.
print('Cost to operate one server per day is ${:.2f}.'.format(cost_per_day))
print('Cost to operate one server per month is ${:.2f}.'.format(cost_per_month))
print('Cost to operate twenty servers per day is ${:.2f}.'.format(cost_per_day_twenty))
print('Cost to operate twenty servers per month is ${:.2f}.'.format(cost_per_month_twenty))
print('A server can operate on a ${0:.2f} budget for {1:.0f} days.'.format(budget, operational_days))

Numbers 2 - Python Programming for Beginners Practice Exercise 5

Exercise 5:

Let's assume you are planning to use your Python skills to build a social networking service. You decide to host your application on servers running in the cloud. You pick a hosting provider that charges $0.51 per hour. You will launch your service using one server and want to know how much it will cost to operate per day and per month.

Write a Python program that displays the answers to the following questions:

How much does it cost to operate one server per day?

How much does it cost to operate one server per month?

Solution:

#!/usr/bin/env python3

# The cost of one server per hour.
cost_per_hour = 0.51

# Compute the costs for one server.
cost_per_day = 24 * cost_per_hour
cost_per_month = 30 * cost_per_day

# Display the results.
print('Cost to operate one server per day is ${:.2f}.'.format(cost_per_day))
print('Cost to operate one server per month is ${:.2f}.'.format(cost_per_month))

Modules - Python Programming for Beginners Practice Exercise 11

Exercise 11:

Update the "What Did the Cat Say" program from an earlier section so that it can be run directly or imported as a module. When it runs as a program is should prompt for input and display a cat "saying" what was provided by the user. Place the input provided by the user inside a speech bubble. Make the speech bubble expand or contract to fit around the input provided by the user.

Sample output when run interactively


Next, create a new program called cat_talk.py that imports the cat_say module. Use a function from the cat_say() module to display various messages to the screen.

Sample output when used as a module:


Solution 1:

#!/usr/bin/env python3

def cat_say(text):
    """Generate a picture of a cat saying something"""
    text_length = len(text)
    print('            {}'.format('_' * text_length))
    print('          < {} >'.format(text))
    print('            {}'.format('-' * text_length))
    print('          /')
    print(' /\_/\   /')
    print('( o.o )')
    print(' > ^ <')

def main():
    text = input('What would you like the cat to say? ')
    cat_say(text)

if __name__ == '__main__':
    main()

Solution 2:

#!/usr/bin/env python3

import cat_say

def main():
    cat_say.cat_say('Feed me.')
    cat_say.cat_say('Pet me.')
    cat_say.cat_say('Purr.  Purr.')

if __name__ == '__main__':
    main()

Tuesday, November 15, 2022

Lists - Python Programming for Beginners Practice Exercise 8

Exercise 8:

Create a Python program that captures and displays a person's to-do list. Continually prompt the user for another item until they enter a blank item. After all the items are entered, display the to­do list back to the user.

Sample Output:


Enter a task for your to-do list. Press <enter> when done: Buy cat food.
Task added.
Enter a task for your to-do list. Press <enter> when done: Mow the lawn.
Task added.
Enter a task for your to-do list. Press <enter> when done: Take over the world.
Task added.
Enter a task for your to-do list. Press <enter> when done:

Your To-Do List:
-------------------
Buy cat food.
Mow the lawn.
Take over the world.

Solution:

#!/usr/bin/env python3

# Create a list to hold the to-do tasks.
to_do_list = []
finished = False
while not finished:
    task = input('Enter a task for your to-do list.  Press  when done: ')
    if len(task) == 0:
        finished = True
    else:
        to_do_list.append(task)
        print('Task added.')

# Display the to-do list.
print()
print('Your To-Do List:')
print('-' * 16)
for task in to_do_list:
    print(task)

Functions - Python Programming for Beginners Practice Exercise 7

Exercise 7:

Create a fill in the blank word game. Prompt the user to enter a noun, verb, and an adjective. Use those responses to fill in the blanks and display the story.

Write a short story. Remove a noun, verb, and an adjective.

Create a function to get the input from the user.

Create a function that fills in the blanks in the story you created.

Ensure each function contains a docstring.

After the noun, verb, and adjective have been collected from the user, display the story using their input.

Solution:

#!/usr/bin/env python3

def get_word(word_type):
    """Get a word from a user and return that word."""

    # The lower() function converts the string to lowercase before testing it
    if word_type.lower() == 'adjective':
        # Use 'an' in front of 'adjective'
        a_or_an = 'an'
    else:
        # Otherwise, use 'a' in front of 'noun' or 'verb'
        a_or_an = 'a'
    return input('Enter a word that is {0} {1}: '.format(a_or_an, word_type))


def fill_in_the_blanks(noun, verb, adjective):
    """Fills in the blanks and returns a completed story."""

    # The \ lets the string continue on the next line to make the code easier to read
    story = "In this course you will learn how to {1}.  " \
            "It's so easy even a {0} can do it.  " \
            "Trust me, it will be very {2}.".format(noun, verb, adjective)
    return story


def display_story(story):
    """Displays a story."""
    print()
    print('Here is the story you created.  Enjoy!')
    print()
    print(story)


def create_story():
    """Creates a story by capturing the input and displaying a finished story."""
    noun = get_word('noun')
    verb = get_word('verb')
    adjective = get_word('adjective')

    the_story = fill_in_the_blanks(noun, verb, adjective)
    display_story(the_story)

create_story()

Files 1 - Python Programming for Beginners Practice Exercise 12

Exercise 12:

Read the contents of animals.txt and produce a file named animals­sorted.txt that is sorted alphabetically.

The contents of animals.txt:

man
bear
pig
cow
duck
horse
dog

Sample Output:

bear
cow
dog
duck
horse
man
pig

Solution:

#!/usr/bin/env python3

unsorted_file_name = 'animals.txt'
sorted_file_name = 'animals-sorted.txt'
animals = []

try:
    with open(unsorted_file_name) as animals_file:
        for line in animals_file:
            animals.append(line)
    animals.sort()
except:
    print('Could not open {}.'.format(unsorted_file_name))

try:
    with open(sorted_file_name, 'w') as animals_sorted_file:
        for animal in animals:
            animals_sorted_file.write(animal)
except:
    print('Could not open {}.'.format(sorted_file_name))

Files 2 - Python Programming for Beginners Practice Exercise 13

Exercise 13:

Create a program that opens file.txt. Read each line of the file and prepend it with a line number.

The contents of files.txt:

This is line one.
This is line two.
Finally, we are on the third and last line of the file.

Sample Output:

1: This is line one.
2: This is line two.
3: Finally, we are on the third and last line of the file.

Solution:

#!/usr/bin/env python3

with open('file.txt') as file:
    line_number = 1
    for line in file:
        print('{}: {}'.format(line_number, line.rstrip()))
        line_number += 1

Dictionaries - Python Programming for Beginners Practice Exercise 9

Exercise 9:

Create a dictionary that contains a list of people and one interesting fact about each of them. Display each person and their interesting fact to the screen. Next, change a fact about one of the people. Also add an additional person and corresponding fact. Display the new list of people and facts. Run the program multiple times and notice if the order changes.

Sample Output:

Jeff: Is afraid of clowns.
David: Plays the piano.
Jason: Can fly an airplane.
Jeff: Is afraid of heights.
David: Plays the piano.
Jason: Can fly an airplane.
Jill: Can hula dance.



Solution:

#!/usr/bin/env python3

def display_facts(facts):
    """Displays facts"""
    for fact in facts:
        print('{}: {}'.format(fact, facts[fact]))
    print()

facts = {
    'Jason': 'Can fly an airplane.',
    'Jeff':  'Is afraid of clowns.',
    'David': 'Plays the piano.'
}

display_facts(facts)

facts['Jeff'] = 'Is afraid of heights.'
facts['Jill'] = 'Can hula dance.'

display_facts(facts)

Booleans and Conditionals - Python Programming for Beginners Practice Exercise 6

Exercise 6:

Create a program that asks the user how far they want to travel. If they want to travel less than three miles tell them to walk. If they want to travel more than three miles, but less than three hundred miles, tell them to drive. If they want to travel three hundred miles or more tell them to fly.

Sample Output:

How far would you like to travel in miles? 2500
I suggest flying to your destination.

Solution:

#!/usr/bin/env python3

# Ask for the distance.
distance = input('How far would you like to travel in miles? ')

# Convert the distance to an integer.
distance = int(distance)

# Determine what mode of transport to use.
if distance < 3:
    mode_of_transport = 'walking'
elif distance < 300:
    mode_of_transport = 'driving'
else:
    mode_of_transport = 'flying'

# Display the result.
print('I suggest {} to your destination.'.format(mode_of_transport))