Python

What is Python?

Python is an object-oriented programming language created by Guido Rossum in 1989. It is ideally designed for rapid prototyping of complex applications. It has interfaces to many OS system calls and libraries and is extensible to C or C++. Many large companies use the Python programming language include NASA, Google, YouTube, BitTorrent, etc.
Python programming is widely used in Artificial Intelligence, Natural Language Generation, Neural Networks and other advanced fields of Computer Science. Python had deep focus on code readability & this class will teach you python from basics.

  • It provides rich data types and easier to read syntax than any other programming languages
  • It is a platform independent scripted language with full access to operating system API’s
  • Compared to other programming languages, it allows more run-time flexibility
  • It includes the basic text manipulation facilities of Perl and Awk
  • A module in Python may have one or more classes and free functions
  • Libraries in Pythons are cross-platform compatible with Linux, Macintosh, and Windows
  • For building large applications, Python can be compiled to byte-code
  • Python supports functional and structured programming as well as OOP
  • It supports interactive mode that allows interacting Testing and debugging of snippets of code
  • In Python, since there is no compilation step, editing, debugging and testing is fast.

What is a Variable in Python?

A Python variable is a reserved memory location to store values. In other words, a variable in a python program gives data to the computer for processing.

Every value in Python has a datatype. Different data types in Python are Numbers, List, Tuple, Strings, Dictionary, etc. Variables can be declared by any name or even alphabets like a, aa, abc, etc.

Local & Global Variables

In Python when you want to use the same variable for rest of your program or module you declare it a global variable, while if you want to use the variable in a specific function or method, you use a local variable.

Let’s understand this difference between local and global variable with the below program.

  1. Variable “f” is global in scope and is assigned value 101 which is printed in output
  2. Variable f is again declared in function and assumes local scope. It is assigned value “I am learning Python.” which is printed out as an output. This variable is different from the global variable “f” define earlier
  3. Once the function call is over, the local variable f is destroyed. At line 12, when we again, print the value of “f” is it displays the value of global variable f=101.

What is Tuple in Python?

A tuple is just like a list of a sequence of immutable python objects. The difference between list and tuple is that list are declared in square brackets and can be changed while tuple is declared in parentheses and cannot be changed. However, you can take portions of existing tuples to make new tuples.

What is a Function in Python?

A Functions in Python are used to utilize the code in more than one place in a program, sometimes also called method or procedures. Python provides you many inbuilt functions like print(), but it also gives freedom to create your own functions.

What is Loop?

Loops can execute a block of code number of times until a certain condition is met. Their usage is fairly common in programming. Unlike other programming language that have For Loop, while loop, dowhile, etc.

What is For Loop?

For loop is used to iterate over elements of a sequence. It is often used when you have a piece of code which you want to repeat “n” number of time.

What is While Loop?

While Loop is used to repeat a block of code. Instead of running the code block once, It executes the code block multiple times until a certain condition is met.

How to use “For Loop”

In Python, “for loops” are called iterators.

Just like while loop, “For Loop” is also used to repeat the program.

But unlike while loop which depends on condition true or false. “For Loop” depends on the elements it has to iterate.

What is a Class?

A Class is a logical grouping of data and functions. It gives the freedom to create data structures that contains arbitrary content and hence easily accessible.

For example, for any bank employee who want to fetch the customer details online would go to customer class, where all its attributes like transaction details, withdrawal and deposit details, outstanding debt, etc. would be listed out.

Course Outline

Lesson 1

Getting started with Python programming

      • Overview
      • Introductory Remarks about Python
      • A Brief History of Python
      • How python is differ from other languages
      • Python Versions
      • Installing Python and Environment Setup
      • IDLE
      • Getting Help
      • How to execute Python program
      • Writing your first Python program
      • How to work on different Popular IDE’s [ Pycharm , Jupyter Notebook , Spyder etc.]

Lesson 2

Variables, Keywords and Operators

      • Variables
      • Memory mapping of variables
      • Keywords in Python
      • Comments in python
      • Operators
          1. Arithmetic Operators
          1. Assignment Operators
          1. Comparision Operators
          1. Logical Operators
          1. Membership Operators
          1. Identity Operators
        1. Bitwise Operators
      • Basics I/O and Type casting
    • Getting user input

Lesson 3

Data types in Python

      • Numbers
      • Strings
      • Lists
      • Tuples
      • Dictionary
    • Sets

Lesson 4

Numbers and Strings

      • Introduction to Python ‘Number’ & ‘string’ data types
      • Properties of a string
      • String built-in functions
      • Programming with strings
    • String formatting

Lesson 5

Lists and Tuples

      • Introduction to Python ‘list’ data type
      • Properties of a list
      • List built-in functions
      • Programming with lists
      • List comprehension
      • Introduction to Python ‘tuple’ data type
      • Tuples as Read only lists
    • Project: Employee Data Management by using List

Lesson 6

Dictionary and Sets

      • Introduction to Python ‘dictionary’ data type
      • Creating a dictionary
      • Dictionary built-in functions
      • Introduction to Python ‘set’ data type
      • Set and set properties
      • Set built-in functions
    • Project: Banking System project by using Dictionary

Lesson 7

Decision making & Loops

      • Introduction of Decision Making
      • Control Flow and Syntax
      • The if Statement
      • The if..else Statement
      • The if…elif…else Statement
      • Nested if…else Statement
      • The while Loop
      • break and continue  Statement
      • The for Loop
      • Pass statement
    • Exercise

Lesson 8

User defined Functions

      • Introduction of functions
      • Function definition and return
      • Function call and reuse
      • Function parameters
      • Function recipe and docstring
      • Built in functions
      • Scope of variables
      • Recursive functions
      • Lambda Functions / Anonymous Functions
      • Iterators
      • Generators
      • Zip function
      • Closures
      • Decorators
      • Map , Filter & Reduce functions
    • *args and **kwargs

Lesson 9

Modules and Packages

      • Modules
      • Importing module
      • Standard Module – sys
      • Standard Module – OS
      • The dir Function
      • Packages
    • Exercise

Lesson 10

Exception Handling in Python

      • Understanding exceptions
      • Run Time Errors
      • Handling I/O Exceptions
      • try, except, else and finally statement
    • raising exceptions with: raise, assert

Lesson 11

File Handling in Python

      • Working with files
      • File objects and Modes of file operations
      • Reading, writing and use of ‘with’ keyword
      • read(), readline(), readlines(), seek(), tell() methods
      • Handling comma separated value files (CSV file handling)
      • CSV reading and writing with DictWriter
      • Pickling (Pickle file handling)
    • Project: Fruit Store data management

Lesson 12

Email sending Automation

      • Understanding SMTP
      • Sending email with sendmail() function
      • Email sending with attachment and MIME
    • Project: Mass mailer

Lesson 13

Regular expression

      • Pattern matching
      • Meta characters for making patterns
      • re flags
    • Use of match() , sub() , findall(), search(), split() methods

Lesson 14

Object oriented programming with Python

      • OOPs concepts: Classes and objects
      • Making of a class and module namespace
      • Static and instance variables
      • Deep understanding of self and init ()
      • Inheritance and Overriding
      • Overloading functions
      • Operator overloading
      • Encapsulation: Hiding attributes
      • Understanding threads
    • Multithreading

Lesson 15

Database connectivity with Python

    • Working with MySQL database
    • Working with Sqlite3 database

Lesson 16

Socket Programming & Tkinter GUI Application

    • Introduction to Tkinter module
    • Using root window
    • Creating frames
    • Using Labels and Buttons
    • Using Text and Entry widgets
    • KM to M converter application
    • Project: Calculator, Notepad etc.
  • How to create setup file of project.

Project Work (Any one)

    • Restaurant Management System
    • Payroll Management System
    • Simple Quiz GUI APP
    • Student Information System
    • Tic Tac Toe Game
    • Snake Game
  • Blackjack Game

Top 35 Python Interview Questions & Answers

1) What is Python? What are the benefits of using Python?

Python is a programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source.

2) What is pickling and unpickling?

Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

3) How Python is interpreted?

Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.

4) How memory is managed in Python?

  • Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap.
  • The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code.
  • Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.

5) What are the tools that help to find bugs or perform static analysis?

PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.

6) What are Python decorators?

A Python decorator is a specific change that we make in Python syntax to alter functions easily.

7) What is the difference between list and tuple?

The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries.

8) How are arguments passed by value or by reference?

Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result you cannot change the value of the references. However, you can change the objects if it is mutable.

9) What is Dict and List comprehensions are?

They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.

10) What is namespace in Python?

In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object.

11) What is lambda in Python?

It is a single expression anonymous function often used as inline function.

12) Why lambda forms in python does not have statements?

A lambda form in python does not have statements as it is used to make new function object and then return them at runtime.

13) What is pass in Python?

Pass means, no-operation Python statement, or in other words it is a place holder in compound statement, where there should be a blank left and nothing has to be written there.

14) In Python what are iterators?

In Python, iterators are used to iterate a group of elements, containers like list.

15) What is unittest in Python?

A unit testing framework in Python is known as unittest. It supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections etc.

16) In Python what is slicing?

A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known as slicing.

17) What are generators in Python?

The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function.

18) How can you copy an object in Python?

To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general case. You cannot copy all objects but most of them.

19) What is negative index in Python?

Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth.

20) How you can convert a number to a string?

In order to convert a number into a string, use the inbuilt function str(). If you want a octal or hexadecimal representation, use the inbuilt function oct() or hex().

21) What is the difference between Xrange and range?

Xrange returns the xrange object while range returns the list, and uses the same memory and no matter what the range size is.

22) What is module and package in Python?

In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes.

The folder of Python program is a package of modules. A package can have modules or subfolders.

23) Mention what are the rules for local and global variables in Python?

Local variables: If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be local.

Global variables: Those variables that are only referenced inside a function are implicitly global.

24) How can you share global variables across modules?

To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.

25) Explain how to delete a file in Python?

By using a command os.remove (filename) or os.unlink(filename)

26) Explain how can you generate random numbers in Python?

To generate random numbers in Python, you need to import command as

import random

random.random()

This returns a random floating point number in the range [0,1)

27) Explain how can you access a module written in Python from C?

You can access a module written in Python from C by following method,

Module = =PyImport_ImportModule(“<modulename>”);

28) Mention the use of // operator in Python?

It is a Floor Divisionoperator , which is used for dividing two operands with the result as quotient showing only digits before the decimal point. For instance, 10//5 = 2 and 10.0//5.0 = 2.0.

29) Mention five benefits of using Python?

  • Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc.
  • Python does not require explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically
  • Provide easy readability due to use of square brackets
  • Easy-to-learn for beginners
  • Having the built-in data types saves programming time and effort from declaring variables

30) Mention the use of the split function in Python?

The use of the split function in Python is that it breaks a string into shorter strings using the defined separator. It gives a list of all words present in the string.

31) Explain what is Flask & its benefits?

Flask is a web micro framework for Python based on “Werkzeug, Jinja 2 and good intentions” BSD licensed. Werkzeug and jingja are two of its dependencies.

Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries. It makes the framework light while there is little dependency to update and less security bugs.

32) Mention what is the difference between Django, Pyramid, and Flask?

Flask is a “microframework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use.

Pyramid are build for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.

Like Pyramid, Django can also used for larger applications. It includes an ORM.

33) Mention what is Flask-WTF and what are their features?

Flask-WTF offers simple integration with WTForms. Features include for Flask WTF are

  • Integration with wtforms
  • Secure form with csrf token
  • Global csrf protection
  • Internationalization integration
  • Recaptcha supporting
  • File upload that works with Flask Uploads

34) Explain what is the common way for the Flask script to work?

The common way for the flask script to work is

  • Either it should be the import path for your application
  • Or the path to a Python file

35) Explain how you can access sessions in Flask?

A session basically allows you to remember information from one request to another. In a flask, it uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.