Docs
Python
Unit 1

1. What is Python programming language?

Python is a high-level programming language that is known for its simplicity, readability, and versatility.

It was created in the late 1980s by Guido van Rossum and has since become one of the most popular programming languages in the world.

Python can be used for a wide range of applications, including web development, data science, machine learning, game development, and more.

Its ease of use and large library of modules and tools make it a popular choice for both beginners and experienced programmers.


2. Give short history for Python.

Python was created in the late 1980s by Guido van Rossum, a Dutch programmer who wanted to create a programming language that was easy to learn and use.

The first version of Python, Python 0.9.0, was released in 1991. Python 1.0 was released in 1994, and Python 2.0 was released in 2000, introducing a number of new features and improvements.

Python 3.0, which was a major overhaul of the language, was released in 2008.

Since then, Python has continued to grow in popularity and is now one of the most widely used programming languages in the world.


3. Enlist applications for Python programming.

  1. Web development: Python can be used to create web applications, websites, and web services. Popular web frameworks like Django and Flask are built on Python.
  2. Data science and analytics: Python has a variety of libraries and tools for data analysis, machine learning, and scientific computing. Popular libraries include NumPy, Pandas, SciPy, and Scikit-learn.
  3. Artificial intelligence and machine learning: Python has become a popular choice for developing AI and machine learning applications. Libraries like TensorFlow, Keras, and PyTorch make it easy to build and train machine learning models.
  4. Desktop applications: Python can be used to create desktop applications with graphical user interfaces (GUIs). The Tkinter library is a popular choice for creating GUIs with Python.
  5. Game development: Python can be used to create games and interactive applications. Libraries like Pygame and PyOpenGL make it easy to create 2D and 3D games with Python.
  6. Scripting and automation: Python is often used for scripting and automation tasks, such as automating repetitive tasks or system administration.
  7. Education and learning: Python is a popular language for teaching programming and is used in many introductory computer science courses.

4. What are the features of Python?

  1. Easy to learn and use: Python has a simple and intuitive syntax that makes it easy for beginners to learn and use.
  2. Interpreted: Python is an interpreted language, which means that code can be run as soon as it is written without the need for a separate compilation step.
  3. Platform-independent: Python code can be run on a wide range of platforms, including Windows, Mac, and Linux.
  4. Object-oriented: Python is an object-oriented language, which means that it supports the creation and manipulation of objects, making it easier to write complex applications.
  5. Large standard library: Python comes with a large standard library of modules and tools that can be used for a wide range of tasks, from web development to scientific computing.
  6. Third-party libraries: In addition to the standard library, there are many third-party libraries available for Python that can be used for specific tasks, such as data analysis, machine learning, and web development.
  7. Dynamic typing: Python is dynamically typed, which means that variables can change type at runtime.
  8. Garbage collection: Python automatically manages memory allocation and deallocation through a garbage collection mechanism.
  9. Easy integration: Python can be easily integrated with other programming languages, making it a popular choice for scripting and automation tasks.

5. List any four editors used for Python programming.

  • PyCharm is a widely used by JetBrains
  • Visual Studio Code IDE by Microsoft
  • Atom by GitHub
  • PyDev
  • Sublime Text
  • Jupyter

6. Python programming language is interpreted and interactive comment this sentence.

Yes, Python programming language is both interpreted and interactive.

Being an interpreted language means that Python code can be executed line-by-line without the need for a separate compilation step. This makes it easy to write and test code quickly.

Additionally, Python has a built-in interactive shell, which allows developers to execute Python code interactively and see the results immediately. This interactive mode is great for testing code snippets or exploring Python features.


7. How to run python scripts? Explain in detail.

  1. Write your Python code: First, you need to write your Python code using a text editor or an integrated development environment (IDE). You can save the code as a plain text file with a .py extension.
  2. Open a command prompt or terminal: To run the script, you need to open a command prompt or terminal window. On Windows, you can open the Command Prompt by pressing the Windows key + R, typing "cmd" in the Run dialog box, and pressing Enter. On macOS or Linux, you can open the terminal by searching for it in the applications menu.
  3. Navigate to the script directory: Once you have opened the command prompt or terminal, you need to navigate to the directory where the Python script is saved. You can use the "cd" command to change directories. For example, if your script is saved in the "Scripts" folder on your desktop, you can navigate to it by typing:
vros.py
cd C:\vros\Desktop\script
  1. Run the script: Once you are in the correct directory, you can run the Python script by typing "python" followed by the name of the script file. For example, if your script is saved as "myscript.py", you can run it by typing:
vros.py
python myscript.py
  1. View the output: Once you have executed the script, any output will be displayed in the command prompt or terminal window. If your script produces a graphical user interface (GUI) or other visual output, it will be displayed in a separate window.

These are the basic steps for running a Python script.


8. What is interpreter? How it works?

An interpreter is a program that executes code written in a high-level programming language, such as Python, line-by-line without the need for a separate compilation step.

When you run a Python script, the Python interpreter reads the code in the file and executes it line by line. The interpreter parses each line of code and converts it into machine code or byte code, which can then be executed by the computer's CPU.

As the interpreter executes each line of code, it also checks for syntax errors or other issues that could cause the code to fail. If an error is detected, the interpreter will stop execution and display an error message indicating the issue.

The interpreter can also execute code interactively, which allows you to enter Python code directly into the interpreter's prompt and see the results immediately. This interactive mode is great for testing code snippets or exploring Python features.


9. Explain the following features of Python programming:

  • Simple: Python is designed to be simple and easy to learn. Its syntax is clear and concise, making it easy for beginners to understand and write code. Python's simplicity also makes it easier to maintain and debug code, as there is less code to read and understand.
  • Platform independent: Python code can run on a wide range of platforms, including Windows, Mac, and Linux, without any changes to the code. This is because Python code is interpreted, rather than compiled, which means that it is executed by the Python interpreter, rather than directly by the computer's CPU.
  • Interactive: Python has an interactive mode, which allows developers to execute Python code line by line and see the results immediately. This interactive mode is great for testing code snippets or exploring Python features. Additionally, Python has a large number of built-in functions and libraries, which makes it easy to perform a wide range of tasks without writing a lot of code.
  • Object Oriented: Python is an object-oriented language, which means that it supports the creation and manipulation of objects. This makes it easier to write complex applications and to reuse code. Python's object-oriented features include classes, objects, inheritance, and polymorphism. These features allow developers to create reusable code that is easier to maintain and modify.

10. Explain about the need for learning Python programming and its importance.

  1. Versatility: Python can be used for a wide range of tasks, including web development, data analysis, artificial intelligence, machine learning, scientific computing, and more. Its versatility makes it a valuable tool for both developers and businesses.
  2. Popularity: Python is one of the most popular programming languages in use today, with a large and active community of developers. This community provides a wealth of resources, including libraries, frameworks, and online courses, making it easy to learn and use Python.
  3. Ease of use: Python's syntax is simple and easy to understand, which makes it a great language for beginners. Its readability and ease of use also make it easier to maintain and debug code.
  4. Job opportunities: Python skills are in high demand in a variety of industries, including finance, healthcare, technology, and more. Learning Python can open up a wide range of job opportunities for developers and other professionals.
  5. Community support: Python has a large and active community of developers who provide support, share knowledge, and collaborate on open source projects. This community provides a wealth of resources, including libraries, frameworks, and online courses, making it easy to learn and use Python.

11. Describe the internal working of Python diagrammatically.

Python is an object-oriented programming language like Java. Python is called an interpreted language. Python uses code modules that are interchangeable instead of a single long list of instructions that was standard for functional programming languages. The standard implementation of python is called “cpython”. It is the default and widely used implementation of Python. Python doesn’t convert its code into machine code, something that hardware can understand. It actually converts it into something called byte code. So within python, compilation happens, but it’s just not into a machine language. It is into byte code (.pyc or .pyo) and this byte code can’t be understood by the CPU. So we need an interpreter called the python virtual machine to execute the byte codes.

Compiler

The Python source code goes through the following to generate an executable code :

  • Step 1: The python compiler reads a python source code or instruction. Then it verifies that the instruction is well-formatted, i.e. it checks the syntax of each line. If it encounters an error, it immediately halts the translation and shows an error message.
  • Step 2: If there is no error, i.e. if the python instruction or source code is well-formatted then the compiler translates it into its equivalent form in an intermediate language called “Byte code”.
  • Step 3: Byte code is then sent to the Python Virtual Machine(PVM) which is the python interpreter. PVM converts the python byte code into machine-executable code. If an error occurs during this interpretation then the conversion is halted with an error message.

12. Write in brief about characters set of Python.

A character set is a set of valid characters acceptable by a programming language in scripting. In this case, we are talking about the Python programming language. So, the Python character set is a valid set of characters recognized by the Python language. These are the characters we can use during writing a script in Python. Python supports all ASCII / Unicode characters that include:

  • Alphabets: All capital (A-Z) and small (a-z) alphabets.
  • Digits: All digits 0-9.
  • Special Symbols: Python supports all kind of special symbols like, ” ‘ l ; : ! ~ @ # $ % ^ ` & * ( ) _ + – = \ .
  • White Spaces: White spaces like tab space, blank space, newline, and carriage return.
  • Other: All ASCII and UNICODE characters are supported by Python that constitutes the Python character set.

13. Write in brief about any five keywords in Python.

  1. if: The if keyword is used to specify a condition in an if statement. If the condition is true, the code block following the if statement is executed.
  2. for: The for keyword is used to specify a loop in Python. It is used to iterate over a sequence of values, such as a list or a string.
  3. def: The def keyword is used to define a function in Python. Functions are reusable blocks of code that can be called multiple times from different parts of a program.
  4. return: The return keyword is used to specify the return value of a function. When a function is called, it may return a value to the calling code using the return keyword.
  5. try: The try keyword is used to specify a block of code that may raise an exception. The code block following the try statement is executed, and if an exception is raised, the code block following the except statement is executed instead.

14. Write the steps to install Python and to run Python code.

  1. Download Python: Go to the official Python website (https://www.python.org/downloads/ (opens in a new tab)) and download the latest version of Python for your operating system (Windows, macOS, or Linux). Follow the instructions provided by the installer to install Python on your computer.
  2. Check Python installation: After installing Python, open a command prompt or terminal window and type python --version to check that Python is installed correctly and to see the version number.
  3. Choose a code editor or IDE: To write and run Python code, you will need a code editor or an Integrated Development Environment (IDE). There are many options available, including PyCharm, Visual Studio Code, Sublime Text, and IDLE (which comes bundled with Python). Choose an editor that you are comfortable with and install it on your computer.
  4. Write your Python code: Open your code editor or IDE and create a new Python file (with a .py extension). Write your Python code in the file and save it to a directory on your computer.
  5. Run your Python code: To run your Python code, open a command prompt or terminal window and navigate to the directory where you saved the Python file. Type python filename.py (replace filename with the name of your Python file) and press Enter. Your Python code will be executed, and the output will be displayed in the terminal window.

Alternatively, you can also run your Python code within your code editor or IDE by selecting the "Run" or "Execute" option in the menu or by using a keyboard shortcut.

That's it! You now have Python installed on your computer and can start writing and running Python code.


15. What is the role of indentation in Python?

In Python, indentation is used to indicate the level of nesting or hierarchy of blocks of code. Unlike other programming languages that use curly braces or other symbols to define blocks of code, Python uses indentation as a way to structure and organize code.

The amount of indentation used in a Python program is significant because it determines which statements are part of which block of code. Blocks of code that have the same level of indentation are considered to be part of the same block.

For example, here is a simple Python program that uses indentation to define two blocks of code:

vros.py
if x > 0:
    print("x is positive")
    if x > 10:
        print("x is greater than 10")
else:
    print("x is not positive")

In this example, the if statement and the else statement are two blocks of code, and the nested if statement is a block of code within the first if statement. The code within each block is indented by four spaces, which tells Python that it belongs to that block.

It is important to use consistent and correct indentation in your Python code to avoid syntax errors and make your code more readable. Conventionally, four spaces are used for indentation in Python, but you can also use a tab character or a combination of tabs and spaces. However, you should avoid mixing tabs and spaces in your code, as this can lead to errors.


16. How to comment specific line(s) in Python program?

In Python, you can add comments to your code using the # symbol. To comment out a specific line in your Python program, simply add a # symbol at the beginning of the line. This will tell Python to ignore that line when it runs your program.

Here is an example:

vros.py
# This is a comment
print("Hello, world!")  # This line prints a message
# print("This line is commented out")

In this example, the first and third lines are comments, so they will not be executed when you run the program. The second line is a print statement, and the fourth line is a commented-out print statement.

You can also use the """ symbols to add a multi-line comment in Python. Anything between the """ symbols will be treated as a comment and will not be executed by Python.

Here is an example:

vros.py
"""
This is a multi-line comment.
You can use it to document your code
and explain what it does.
"""
print("Hello, world!")

In this example, the first three lines are a multi-line comment, and the fourth line is a print statement.


17. What is variable? What are the rules and conventions for declaring a variables?

In programming, a variable is a name given to a value that can be stored in the computer's memory. It is a way to assign a label to a specific value or data structure that can be accessed and modified throughout the program.

In Python, variables are declared using the assignment operator =. The name of the variable can be any combination of letters, digits, and underscores, but cannot start with a digit. The rules and conventions for declaring a variable in Python are as follows:

  1. The name of the variable should be meaningful and descriptive, and should start with a lowercase letter. If the variable name consists of multiple words, it should be written in snake_case (with underscores between words).
  2. Python is case sensitive, so myVar and myvar are two different variables.
  3. The name of the variable should not be a keyword or a built-in function in Python, such as if, else, for, while, print, int, float, str, list, tuple, dict, etc.
  4. A variable should be declared before it is used. In Python, you do not need to specify the data type of the variable when you declare it, because Python is dynamically typed. The data type of the variable is inferred from the value it is assigned.

Here are some examples of valid variable names in Python:

vros.py
age = 25
name = "John"
is_student = True
my_list = [1, 2, 3]

It is important to follow the rules and conventions for declaring variables to make your code more readable and maintainable.


18. What are the various data types available in Python programming.

  1. Numeric: Numeric data types are used to represent numbers in Python. The main numeric types are int (integer), float (floating-point number), and complex (complex number).
  2. String: Strings are used to represent textual data in Python. They are sequences of characters and are enclosed in single quotes or double quotes.
  3. Boolean: Boolean data types represent logical values. There are only two possible Boolean values in Python: True and False.
  4. List: Lists are used to represent a collection of values in Python. They are ordered and mutable, which means that you can add, remove, or modify elements in a list.
  5. Tuple: Tuples are similar to lists, but they are immutable, which means that you cannot modify the elements of a tuple once it is created.
  6. Set: Sets are used to represent a collection of unique values in Python. They are unordered and mutable, and you can perform set operations such as union, intersection, and difference on them.
  7. Dictionary: Dictionaries are used to represent key-value pairs in Python. They are unordered and mutable, and you can use the keys to access the corresponding values.

19. What are four built-in numeric data types in Python? Explain.

Python has four built-in numeric data types:

  1. Integer: Integers are whole numbers without a fractional component. They can be positive, negative, or zero. In Python, integers are represented using the int type. For example:
vros.py
x = 5
  1. Floating-point: Floating-point numbers have a fractional component and can represent both very large and very small numbers with high precision. In Python, floating-point numbers are represented using the float type. For example:
vros.py
a = 3.14159
  1. Complex: Complex numbers are numbers with a real and an imaginary part. They are represented as x + yj, where x and y are both floating-point numbers and j represents the imaginary unit. In Python, complex numbers are represented using the complex type. For example:
vros.py
c1 = 2 + 3j
  1. Boolean: Booleans are a special data type that can have only two possible values: True or False. They are often used in conditional statements and logical operations. In Python, Booleans are represented using the bool type. For example:
vros.py
a = True
b = False

These four built-in numeric data types in Python are used extensively in programming and can be combined with operators and functions to perform various calculations and operations.


20. What is the difference between interactive mode and script mode of Python.

The main difference between interactive mode and script mode in Python is the way code is executed.

Interactive mode refers to a way of working with Python where code is entered one line at a time and executed immediately after it is entered. This is done using the Python shell, which allows you to type in code and see the results immediately. Interactive mode is great for testing out ideas, exploring the language, and experimenting with code.

On the other hand, script mode refers to writing code in a file, saved with a .py extension, which is then executed using the Python interpreter. In script mode, you write your code in a file and then run the entire file at once. This mode is useful for writing longer programs, creating reusable code, and automating tasks.

Another important difference between interactive mode and script mode is the way errors are handled. In interactive mode, errors are displayed immediately after the code is executed, while in script mode, errors are displayed when the interpreter encounters them while running the script.


21. Python has developed as an open source project. Justify this statement.

Here are some key reasons why Python is considered an open source project:

  1. License: Python is released under an open source license, the Python Software Foundation License, which grants users the right to use, modify, and distribute the software without any restrictions.
  2. Source Code: The source code for Python is freely available to the public, which allows developers to study it, modify it, and add new features to the language.
  3. Community Involvement: Python has a large and active community of users, developers, and contributors who work together to improve the language. This community is open to anyone who wants to contribute, regardless of their level of expertise or experience.
  4. Collaborative Development: Python's development process is open and collaborative. Changes and improvements to the language are proposed, discussed, and reviewed by the community before they are accepted into the official codebase.
  5. Transparency: Python's development process is transparent, meaning that anyone can view the language's development history, track changes to the source code, and follow discussions among the community.

22. Define the following terms:

  • Identifier: A name given to a variable, function, class, or object in Python.
  • Literal: A value that appears directly in the code, such as a string, number, or Boolean value.
  • Data type: A classification of data in programming that defines the type of values that can be stored in a variable.
  • Tuple: An ordered, immutable sequence of elements in Python.
  • List: An ordered, mutable sequence of elements in Python.

23. Explain dictionary data type in detail.

In Python, a dictionary is a collection of key-value pairs. It is an unordered, mutable collection of items that are accessed using keys instead of indices. A dictionary is sometimes called an associative array or a map in other programming languages.

A dictionary is defined using curly braces with each key-value pair separated by a colon :. The keys are unique and can be of any immutable data type such as strings, numbers, or tuples. The values can be of any data type including other dictionaries, lists, or tuples.

Here is an example of how to create a dictionary in Python:

vros.py
my_dict = {'name': 'Vros', 'age': 25, 'city': 'New York'}

In this example, 'name', 'age', and 'city' are the keys, while 'Vros', 25, and 'New York' are the corresponding values. We can access the value associated with a particular key by using square brackets []:

vros.py
print(my_dict['name'])  # Output: 'Vros'

We can also modify or add new key-value pairs to a dictionary by assigning a value to a new or existing key:

vros.py
my_dict['age'] = 30  # Modify value for key 'age'
my_dict['country'] = 'USA'  # Add new key-value pair to the dictionary

Dictionaries support a number of built-in methods to manipulate and access the data within them, such as keys(), values(), items(), get(), pop(), and clear().


24. Explain dictionary data type in detail.

A dictionary is a built-in data type in Python used to store data in key-value pairs. It is created using curly braces or the dict() constructor. You can access, add, update, or remove key-value pairs in a dictionary. Dictionaries can contain values of any data type, and can be nested to create complex data structures.

For example, below we have a dictionary named ‘dict’. It contains two keys, Country and Capital, along with their corresponding values, India and New Delhi.

Syntax:

vros.py
dict={‘Country’:’India’,’Capital’:’New Delhi’, }

Here's an example of how to create, access, and modify a dictionary in Python using syntax:

vros.py
# create a dictionary with key-value pairs
my_dict = {"name": "John", "age": 30, "city": "New York"}
 
# access values using keys
print(my_dict["name"])  # output: John
print(my_dict["age"])  # output: 30
print(my_dict["city"])  # output: New York
 
# add a new key-value pair
my_dict["gender"] = "male"
print(my_dict)
# output: {'name': 'John', 'age': 30, 'city': 'New York', 'gender': 'male'}
 
# update an existing value
my_dict["age"] = 35
print(my_dict)
# output: {'name': 'John', 'age': 35, 'city': 'New York', 'gender': 'male'}
 
# remove a key-value pair
del my_dict["city"]
print(my_dict)
# output: {'name': 'John', 'age': 35, 'gender': 'male'}

In this example, a dictionary my_dict is created with three key-value pairs: "name": "John", "age": 30, and "city": "New York". Then, the values of the keys are accessed using the square bracket notation. A new key-value pair "gender": "male" is added using the square bracket notation. An existing value of the key "age" is updated. Finally, the key-value pair "city": "New York" is removed using the del keyword.