Introduction to Python Programming PDF
Document Details
Uploaded by FastGrowingCouplet
FYCS VSC
Prof.Ajay Pashankar
Tags
Summary
This document provides an introduction to Python programming for first-year computer science students. It covers the core features of Python, how to execute Python programs, different flavors of Python interpreters, and fundamental concepts like variables, operators, and control statements.
Full Transcript
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR www.profajaypashankar.com Page 1 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR Overview and Basic Elements of Python Programming: Features of Python, Execution of...
FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR www.profajaypashankar.com Page 1 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR Overview and Basic Elements of Python Programming: Features of Python, Execution of a Python Program, Flavours of Python, Innards of Python, Python Interpreter, Comments, Docstrings, IDLE, Data types, Dictionary, Sets, Mapping, Basic Elements of Python, Variables, Input Function, Output Statements, Command Line Arguments. Operators, Precedence of Operators, Associativity of Operators Control Statements: The if statement, The if … else Statement, The if … elif … else Statement, Loop Statement- while loop, for loop, Infinite loop, Nested loop, The else suite, break statement, continue statement, pass statement, assert statement, return statement. Arrays: Creating Arrays, Indexing and Slicing of Arrays, Basic Array Operations, Arrays Processing, Mathematical Operations on Array, Aliasing Arrays, Slicing and Indexing in NumPy Arrays, Basic slicing, Advanced Indexing, Dimensions and Attributes of an Array Functions: Function definition and call, Returning Results, Returning Multiple Values from a Function, Built-in Functions, Difference between a Function and a Method, Pass Value by Object Reference, Parameters and Arguments, Recursive Functions, Anonymous or Lambda Functions. Modules in Python. Strings: Creating Strings, Functions of Strings, Working with Strings, Formatting Strings, Finding the Number of Characters and Words, Inserting Substrings into a String. Module (30 hours): Exploring List, Tuples and Dictionaries: Lists, List Functions and Methods, List Operations, List Slices, Nested Lists, Tuples, Functions in Tuple. Working with Dictionaries: Creating a Dictionary, Operators in Dictionary, Dictionary Methods, Using for Loop with Dictionaries, Operations on Dictionaries Files in Python: Opening and Closing a File, Working with Text Files, , Working with Binary Files, The ‘with’ statement, Pickle in Python, The seek() and tell() Methods, Random Accessing of Binary Files, Zipping and Unzipping Files, Working with Directories Regular Expressions: Introduction, Sequence Characters in Regular Expressions, Special Characters in Regular Expressions, Using Regular Expression on Files, Retrieving Information from an HTML File Date And Time in Python: Time, Date, Date and Time Now, combining date and times, formatting date and time, Finding and comparing dates, Sorting dates, Knowing the Time taken by a Program, Working with Calendar Module www.profajaypashankar.com Page 2 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR CHAPTER I: OVERVIEW AND BASIC ELEMENTS OF PYTHON PROGRAMMING Topics Covered: Features of Python, Execution of a Python Program, Flavours of Python, Innards of Python, Python Interpreter, Comments, Docstrings, IDLE, Data types, Dictionary, Sets, Mapping, Basic Elements of Python, Variables, Input Function, Output Statements, and Command Line Arguments. Operators, Precedence of Operators, Associativity of Operators. --------------------------------------------------------------------------------------------------------------- The programming language you will be learning is Python. Python is an example of a high-level language; other high-level languages you might have heard of are C++, PHP, and Java. As you might infer from the name high-level language, there are also low-level languages, sometimes referred to as machine languages or assembly languages. Loosely speaking, computers can only execute programs written in low-level languages. Thus, programs written in a high-level language have to be processed before they can run. This extra processing takes some time, which is a small disadvantage of high-level languages. But the advantages are enormous. First, it is much easier to program in a high-level language. Programs written in a high-level language take less time to write, they are shorter and easier to read, and they are more likely to be correct. Second, high-level languages are portable, meaning that they can run on different kinds of computers with few or no modifications. Low-level programs can run on only one kind of computer and have to be rewritten to run on another. Due to these advantages, almost all programs are written in high-level languages. Low-level languages are used only for a few specialized applications. Two kinds of applications process high-level languages into low-level languages: interpreters and compilers. An interpreter reads a high-level program and executes it, meaning that it does what the program says. It processes the program a little at a time, alternately reading lines and performing computations. A compiler reads the program and translates it into a low-level program, which can then be run. In this case, the high-level program is called the source code, and the translated program is called the object code or the executable. Once a program is compiled, you can execute it repeatedly without further translation. Many modern languages use both processes. They are first compiled into a lower level language, called byte code, and then interpreted by a program called a virtual machine. Python uses both processes, but because of the way programmers interact with it, it is usually considered an interpreted language. There are two ways to use the Python interpreter: shell mode and script mode. In shell mode, you type Python statements into the Python shell and the interpreter --------------------------------------------------------------------------------------------------------------- Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands. Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages. Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL). Python is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing its progress. Python 1.0 was released in November 1994. In 2000, Python 2.0 was released. Python 2.7.11 is the latest edition of Python 2. Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward compatible with Python 2. The emphasis in Python 3 had been on the removal of duplicate programming constructs and modules so that "There should be one -- and preferably only one -- obvious way to do it." Python 3.5.1 is the latest version of Python 3. www.profajaypashankar.com Page 3 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR --------------------------------------------------------------------------------------------------------------- Features of python: Python's features include- Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This allows a student to pick up the language quickly. Easy-to-read: Python code is more clearly defined and visible to the eyes. Easy-to-maintain: Python's source code is fairly easy-to-maintain. A broad standard library: Python's bulk of the library is very portable and crossplatform compatible on UNIX, Windows, and Macintosh. Interactive Mode: Python has support for an interactive mode, which allows interactive testing and debugging of snippets of code. Portable: Python can run on a wide variety of hardware platforms and has the same interface on all platforms. Extendable: You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient. Databases: Python provides interfaces to all major commercial databases. GUI Programming: Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix. Scalable: Python provides a better structure and support for large programs than shell scripting. Apart from the above-mentioned features, Python has a big list of good features. A few are listed below- It supports functional and structured programming methods as well as OOP. It can be used as a scripting language or can be compiled to byte-code for building large applications. It provides very high-level dynamic data types and supports dynamic type checking. It supports automatic garbage collection. It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java. --------------------------------------------------------------------------------------------------------------- Execution of a Python Program: a = 10 b = 10 print("Sum ", (a+b)) Output: Sum 20 Suppose the above python program is saved as first.py. Here first is the name and.py is the extension. The execution of the Python program involves 2 Steps: Compilation Interpreter Compilation The program is converted into byte code. Byte code is a fixed set of instructions that represent arithmetic, comparison, memory operations, etc. It can run on any operating system and hardware. The byte code instructions are created in the.pyc file. The.pyc file is not explicitly created as Python handles it internally but it can be viewed with the following command: -m and py_compile represent module and module name respectively. This module is responsible to generate.pyc file. The compiler creates a directory named __pycache__ where it stores the first.cpython-38.pyc file. Interpreter The next step involves converting the byte code (.pyc file) into machine code. This step is necessary as the computer can understand only machine code (binary code). Python Virtual Machine (PVM) first understands the operating system and processor in the computer and then converts it into machine code. Further, these machine code instructions are executed by processor and the results are displayed. www.profajaypashankar.com Page 4 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR Execution of Python Program However, the interpreter inside the PVM translates the program line by line thereby consuming a lot of time. To overcome this, a compiler known as Just In Time (JIT) is added to PVM. JIT compiler improves the execution speed of the Python program. This compiler is not used in all Python environments like CPython which is standard Python software. To execute the first.cpython-38.pyc we can use the following command: To view the byte code of the file – first.py we can type the following command as : The dis command is known as “disassembler” that displays the byte code in an understandable format. The code represents 5 columns: 1. Line Number 2. offset position of byte code 3. name of byte code instruction 4. instruction’s argument 5. constants or names (in brackets) --------------------------------------------------------------------------------------------------------------- Flavors of Python Flavors of Python refer to the different types of Python compilers. These flavors are useful to integrate various programming languages into Python. The following are some of them: CPython: This is the standard Python compiler implemented in C language. This is the Python software being downloaded and used by programmers directly from CPython. In this, any Python program is internally converted into byte code using C language functions. This byte code is run on the interpreter available in Python Virtual Machine (PVM) created in C language. The advantage is that it is possible to execute C and C++ functions and programs in CPython. --------------------------------------------------------------------------------------------------------------- Jython: This is earlier known as JPython. This is the implementation of Python programming language which is designed to run on Java platform. Jython compiler first compiles the Python program into Java byte code. This byte code is executed by Java Virtual Machine (JVM) to produce the output. Jython contains libraries which are useful for both Python and Java programmers. This can be downloaded from Jython. --------------------------------------------------------------------------------------------------------------- IronPython: This is another implementation of Python language for.NET framework. This is written in C# (C Sharp) language. The Python program when compiled gives an intermediate language (IL) which runs on Common Language Runtime (CLR) to produce the output. This flavor of Python gives www.profajaypashankar.com Page 5 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR flexibility of using both the.NET and Python libraries. IronPython can be downloaded from IronPython. --------------------------------------------------------------------------------------------------------------- PyPy: This is Python implementation using Python language. Actually, PyPy is written in a language called RPython which was created in Python language. RPython is suitable for creating language interpreters. PyPy programs run very fast since there is a JIT (Just In Time) compiler added to the PVM. PyPy can be downloaded by visiting the page: PyPy. Since the original Python uses only an interpreter in the Python Virtual Machine (PVM), the Python programs run slowly. To improve the speed of execution, a compiler called JIT (Just In Time) is introduced into the PVM of PyPy. Hence, PyPy programs run faster than those of Python. We can download PyPy from PyPy. --------------------------------------------------------------------------------------------------------------- RubyPython: This is a bridge between the Ruby and Python interpreters. It encloses a Python interpreter inside Ruby applications. This flavor of Python can be downloaded from RubyPython. --------------------------------------------------------------------------------------------------------------- StacklessPython: Small tasks which should run individually are called tasklets. Tasklets run independently on CPU and can communicate with others via channels. A channel is a manager that takes care of scheduling the tasklets, controlling them and suspending them. A thread is a process which runs hundreds of such tasklets. We can create threads and tasklets in StacklessPython which is reimplementation of original Python language. This can be downloaded from StacklessPython --------------------------------------------------------------------------------------------------------------- Pythonxy: This is pronounced as Python xy and written as Python(X,Y). This is the Python implementation that we get after adding scientific and engineering related packages. We can download Pythonxy from Pythonxy. --------------------------------------------------------------------------------------------------------------- AnacondaPython: When Python is redeveloped for handling large-scale data processing, predictive analytics and scientific computing, it is called Anaconda Python. This implementation mainly focuses on large scale of data. This can be downloaded from AnacondaPython. --------------------------------------------------------------------------------------------------------------- Innards of Python : 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. Internal working of Python Python doesn’t convert its code into machine code, something that hardware can understand. It converts it into something called byte code. So within Python, compilation happens, but it’s just not in 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. Internal Working of Python How is Python Source Code Converted into Executable Code 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 in the code editor. In this first stage, the execution of the code starts. Step 2: After writing Python code it is then saved as a.py file in our system. In this, there are instructions written by a Python script for the system. Step 3: In this the compilation stage comes in which source code is converted into a byte code. Python compiler also checks the syntax error in this step and generates a.pyc file. Step 4: Byte code that is.pyc file is then sent to the Python Virtual Machine(PVM) which is the Python interpreter. PVM converts the Python byte code into machine- executable code and in this interpreter reads and executes the given file line by line. www.profajaypashankar.com Page 6 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR If an error occurs during this interpretation then the conversion is halted with an error message. Step 5: Within the PVM the bytecode is converted into machine code that is the binary language consisting of 0’s and 1’s. This binary language is only understandable by the CPU of the system as it is highly optimized for the machine code. Step 6: In the last step, the final execution occurs where the CPU executes the machine code and the final desired output will come as according to your program. How Python Internally Works? Code Editor: Code Editor is the first stage of programs where we write our source code. This is human-readable code written according to Python’s syntax rules. It is where the execution of the program starts first. Source code: The code written by a programmer in the code editor is then saved as a.py file in a system. This file of Python is written in human-readable language that contains the instructions for the computer. Compilation Stage: The compilation stage of Python is different from any other programming language. Rather than compiling a source code directly into machine code. python compiles a source code into a byte code. In the compilation stage python compiler also checks for syntax errors. after checking all the syntax errors, if no such error is found then it generates a.pyc file that contains bytecode. Python Virtual Machine(PVM): The bytecode then goes into the main part of the conversion is the Python Virtual Machine(PVM). The PVM is the main runtime engine of Python. It is an interpreter that reads and executes the bytecode file, line by line. Here In the Python Virtual Machine translate the byte code into machine code which is the binary language consisting of 0s and 1s. The machine code is highly optimized for the machine it is running on. This binary language is only understandable by the CPU of a system. Running Program: At last, the CPU executes the given machine code and the main outcome of the program comes as performing task and computation you scripted at the beginning of the stage in your code editor. Python Libraries/Modules When you import libraries or modules in your Python program. Firstly python checks if the given module is built-in, and executes the corresponding C code. If the module is not built-in then the list of directories is defined in sys. path. the directory of the input script, and directories listed in the PYTHONPATH. if a.py file corresponds to the modules imported, Python creates a new module object, On executing the code in the.py file within the object’s namespace. Then Python compiles source code into byte code( the.pyc file), allowing for quicker execution Compiler Vs Interpreter In the system both the compiler and interpreter are the same they convert high-level code to machine code. The interpreter converts source code into the machine when the program runs in a system while a compiler converts the source code into machine code before the program runs in our system. Compiler Interpreter The compiler is faster, as The interpreter runs slower as the conversion occurs before the program execution occurs simultaneously. executes. Errors are detected during the Errors are identified and reported compilation phase and displayed before during the given actual runtime. the execution of a program. Interpreted code is more portable Compile code needs to be as it can run on any machine with recompiled to run on different machines. the appropriate interpreter. It requires more memory to It requires less memory than translate the whole source code at once. compiled ones. www.profajaypashankar.com Page 7 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR Compiler Interpreter Debugging is more complex Debugging is easier due to the due to batch processing of the code. line-by-line execution of a code. --------------------------------------------------------------------------------------------------------------- What is Python Interpreter: Well if you are new to Python you have come across the word interpreters but before knowing about Python interpreters, we need to what is an interpreter, what it will do, the advantages and disadvantages of the interpreter, and so on. Well in this handy article, we will cover the Importance of Interpreters and the pros and cons of using interpreters in Python. --------------------------------------------------------------------------------------------------------------- Python Interpreter Python is an interpreted language developed by Guido van Rossum in the year of 1991. As we all know Python is one of the most high-level languages used today because of its massive versatility and portable library & framework features. It is an interpreted language because it executes line-by- line instructions. There are actually two way to execute python code one is in Interactive mode and another thing is having Python prompts which is also called script mode. Python does not convert high level code into low level code as many other programming languages do rather it will scan the entire code into something called bytecode. every time when Python developer runs the code and start to execute the compilation part execute first and then it generate an byte code which get converted by PVM Python Virtual machine that understand the analogy and give the desired output. --------------------------------------------------------------------------------------------------------------- Interpreted Languages: Perl, BASIC, Python, JavaScript, Ruby, PHP. Compiled Languages: C, C++, C#, COBOL and CLEO. --------------------------------------------------------------------------------------------------------------- What are Interpreters? Interpreters are the computer program that will convert the source code or an high level language into intermediate code (machine level language). It is also called translator in programming terminology. Interpreters executes each line of statements slowly. This process is called Interpretation. For example Python is an interpreted language, PHP, Ruby, and JavaScript. Working of Interpreter Example: Here is the simple Python program that takes two inputs as a and b and prints the sum in the third variable which is c. It follows sequential as well as functional execution of programs Python3 a=3 b=7 c=a+b print(c) # output 10 Output 10 --------------------------------------------------------------------------------------------------------------- ---- www.profajaypashankar.com Page 8 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR How interpreters function in Python? Python interpreter is written in C programming language as we all know that C is considered as mother of all programming languages, Python interpreter called “CPython”. Initially in source code analysis, Python get source and check for some Indentation rule and check for errors. if there are any errors Python stops its execution and make to modify to prevent errors. This process is called Lexical analysis in python which states that dividing the source code into list of individual tokens. In Byte code generation, once the python interpreter receives the tokens, it generates AST (Abstract Structure tree) which coverts to byte code and then byte code can be saved in (.py) extension. At last, by using Python Virtual Machine, interpreter loads the machine language and PVM converts in into 0s and 1 s which prints the results. Advantages of using Interpreter It is flexible and error localization is easier. It is smaller in size. It executes line by line execution. Disadvantages of using Interpreters It takes lot of time to translate. It is slower. It uses lot of storage. Applications of Interpreters They are used to execute common languages by using editor or an compiler. Easy implementation of self modifying code. Virtualization. Sandboxing. Emulators. Interpreters of different programming language. Python – PyPy, Stackless Python, Pyston, CPython, Micro Python, and Rust Python. Java – JRocklt, Hotspot. Ruby – CRuby, MRI. ------------------------------------------------------------------------------------------------------------------ ---- Comments in python In Python, comments are used to explain the code and make it more readable. Comments are ignored by the Python interpreter and are not executed as part of the program. There are two main types of comments in Python: single-line comments and multi-line comments. Single-line Comments Single-line comments start with the hash character (#) and extend to the end of the line. They are used for brief explanations or notes. python Copy code # This is a single-line comment print("Hello, World!") # This is an inline comment Multi-line Comments Python does not have a distinct syntax for multi-line comments like some other languages. Instead, you can use a series of single-line comments or use multi-line strings (triple quotes) as comments. While the latter method is not technically a comment, it is often used as such. Using Single-line Comments: python Copy code # This is a comment # that spans multiple lines # using single-line comments Using Multi-line Strings: You can use triple quotes (''' or """) to create a multi-line string that can act as a comment. This is commonly used for docstrings but can also serve as a multi-line comment. python """ This is a multi-line string that spans multiple lines. It can be used as a multi-line comment. www.profajaypashankar.com Page 9 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR """ print("Hello, World!") ------------------------------------------------------------------------------------------------------------------ ---- Docstrings Docstrings are a special kind of comment used to describe the purpose of a function, class, or module. They are written using triple quotes and are placed right after the definition of a function, class, or module. python def example_function(): """ This is a docstring. It describes what the function does. """ print("Hello, World!") class ExampleClass: """ This is a docstring for the class. It describes what the class does. """ pass Docstrings can be accessed using the __doc__ ------------------------------------------------------------------------------------------------------------------ ---- Python Docstrings When it comes to writing clean, well-documented code, Python developers have a secret weapon at their disposal – docstrings. Docstrings, short for documentation strings, are vital in conveying the purpose and functionality of Python functions, modules, and classes. What are the docstrings in Python? Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. It’s specified in source code that is used, like a comment, to document a specific segment of code. Unlike conventional source code comments, the docstring should describe what the function does, not how. Declaring Docstrings: The docstrings are declared using ”’triple single quotes”’ or “”” triple double quotes “”” just below the class, method, or function declaration. All functions should have a docstring. Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or using the help function. The below examples demonstrate how to declare and access a docstring. What should a docstring look like? The doc string line should begin with a capital letter and end with a period. The first line should be a short description. If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description. The following lines should be one or more paragraphs describing the object’s calling conventions, side effects, etc. Docstrings in Python Below are the topics that we will cover in this article: Triple-Quoted Strings Google Style Docstrings Numpydoc Style Docstrings One-line Docstrings Multi-line Docstrings Indentation in Docstrings Docstrings in Classes Difference between Python comments and docstrings Triple-Quoted Strings This is the most common docstring format in Python. It involves using triple quotes (either single or double) to enclose the documentation text. Triple-quoted strings can span multiple lines and are often placed immediately below the function, class, or module definition Example 1: Using triple single quotes Python3 www.profajaypashankar.com Page 10 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR def my_function(): '''Demonstrates triple double quotes docstrings and does nothing really.''' return None print("Using __doc__:") print(my_function.__doc__) print("Using help:") help(my_function) Output: Using __doc__: Demonstrates triple double quotes docstrings and does nothing really. Using help: Help on function my_function in module __main__: my_function() Demonstrates triple double quotes docstrings and does nothing really. Example 2: Using triple-double quotes Python3 def my_function(): ' ' 'Demonstrates triple double quotes docstrings and does nothing really' ' ' return None print("Using __doc__:") print(my_function.__doc__) print("Using help:") help(my_function) Output: Using __doc__: Demonstrates triple double quotes docstrings and does nothing really. Using help: Help on function my_function in module __main__: my_function() Demonstrates triple double quotes docstrings and does nothing really. Google Style Docstrings Google style docstrings follow a specific format and are inspired by Google’s documentation style guide. They provide a structured way to document Python code, including parameters, return values, and descriptions. Python3 def multiply_numbers(a, b): """ Multiplies two numbers and returns the result. Args: a (int): The first number. b (int): The second number. Returns: int: The product of a and b. """ return a * b print(multiply_numbers(3,5)) Output www.profajaypashankar.com Page 11 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR 15 Numpydoc Style Docstrings Numpydoc-style docstrings are widely used in the scientific and data analysis community, particularly for documenting functions and classes related to numerical computations and data manipulation. It is an extension of Google-style docstrings, with some additional conventions for documenting parameters and return values. Python3 def divide_numbers(a, b): """ Divide two numbers. Parameters ---------- a : float The dividend. b : float The divisor. Returns ------- float The quotient of the division. """ if b == 0: raise ValueError("Division by zero is not allowed.") return a / b print(divide_numbers(3,6)) Output 0.5 One-line Docstrings As the name suggests, one-line docstrings fit in one line. They are used in obvious cases. The closing quotes are on the same line as the opening quotes. This looks better for one-liners. For example: Python3 def power(a, b): ' ' 'Returns arg1 raised to power arg2.' ' ' return a**b print(power.__doc__) Output: Returns arg1 raised to power arg2. Multi-line Docstrings Multi-line docstrings consist of a summary line just like a one-line docstring, followed by a blank line, followed by a more elaborate description. The summary line may be on the same line as the opening quotes or on the next line. The example below shows a multi-line docstring. Python3 def add_numbers(a, b): """ This function takes two numbers as input and returns their sum. Parameters: a (int): The first number. b (int): The second number. Returns: int: The sum of a and b. www.profajaypashankar.com Page 12 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR """ return a + b print(add_numbers(3, 5)) Output: 8 Indentation in Docstrings The entire docstring is indented the same as the quotes in its first line. Docstring processing tools will strip a uniform amount of indentation from the second and further lines of the docstring, equal to the minimum indentation of all non-blank lines after the first line. Any indentation in the first line of the docstring (i.e., up to the first new line) is insignificant and removed. Relative indentation of later lines in the docstring is retained. Python3 class Employee: """ A class representing an employee. Attributes: name (str): The name of the employee. age (int): The age of the employee. department (str): The department the employee works in. salary (float): The salary of the employee. """ def __init__(self, name, age, department, salary): """ Initializes an Employee object. Parameters: name (str): The name of the employee. age (int): The age of the employee. department (str): The department the employee works in. salary (float): The salary of the employee. """ self.name = name self.age = age self.department = department self.salary = salary def promote(self, raise_amount): """ Promotes the employee and increases their salary. Parameters: raise_amount (float): The raise amount to increase the salary. Returns: str: A message indicating the promotion and new salary. """ self.salary += raise_amount return f"{self.name} has been promoted! New salary: ${self.salary:.2f}" def retire(self): """ Marks the employee as retired. Returns: str: A message indicating the retirement status. """ # Some implementation for retiring an employee return f"{self.name} has retired. Thank you for your service!" www.profajaypashankar.com Page 13 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR # Access the Class docstring using help() help(Employee) Output: class Employee | A class representing an employee. | | Attributes: | name (str): The name of the employee. | age (int): The age of the employee. | department (str): The department the employee works in. | salary (float): The salary of the employee. | | Methods defined here: | | __init__(self, name, age, department, salary) | Initializes an Employee object. | | Parameters: | name (str): The name of the employee. | age (int): The age of the employee. | department (str): The department the employee works in. | salary (float): The salary of the employee. | | promote(self, raise_amount) | Promotes the employee and increases their salary. | | Parameters: | raise_amount (float): The raise amount to increase the salary. | | Returns: | str: A message indicating the promotion and new salary. | | retire(self) | Marks the employee as retired. | | Returns: | str: A message indicating the retirement status. ------------------------------------------------------------------------------------------------------------------ --- Docstrings in Classes Let us take an example to show how to write docstrings for a class and the method ‘help’ is used to access the docstring. Python3 class ComplexNumber: """ This is a class for mathematical operations on complex numbers. Attributes: real (int): The real part of the complex number. imag (int): The imaginary part of the complex number. """ def __init__(self, real, imag): """ The constructor for ComplexNumber class. Parameters: real (int): The real part of the complex number. imag (int): The imaginary part of the complex number. """ self.real = real www.profajaypashankar.com Page 14 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR self.imag = imag def add(self, num): """ The function to add two Complex Numbers. Parameters: num (ComplexNumber): The complex number to be added. Returns: ComplexNumber: A complex number which contains the sum. """ re = self.real + num.real im = self.imag + num.imag return ComplexNumber(re, im) # Access the Class docstring using help() help(ComplexNumber) # Access the method docstring using help() help(ComplexNumber.add) Output: Help on class ComplexNumber in module __main__: class ComplexNumber(builtins.objects) | This is a class for mathematical operations on complex numbers. | | Attributes: | real (int): The real part of complex number. | imag (int): The imaginary part of complex number. | | Methods defined here: | | __init__(self, real, imag) | The constructor for ComplexNumber class. | | Parameters: | real (int): The real part of complex number. | imag (int): The imaginary part of complex number. | | add(self, num) | The function to add two Complex Numbers. | | Parameters: | num (ComplexNumber): The complex number to be added. | | Returns: | ComplexNumber: A complex number which contains the sum. Help on method add in module __main__: add(self, num) unbound __main__.ComplexNumber method The function to add two Complex Numbers. Parameters: num (ComplexNumber): The complex number to be added. Returns: ComplexNumber: A complex number which contains the sum. Difference between Python comments, String, and Docstrings String: In Python, a string is a sequence of characters enclosed within single quotes (‘ ‘) or double quotes (” “). Strings are used to represent text data and can contain letters, numbers, symbols, and whitespace. They are one of the fundamental data types in Python and can be manipulated using various string methods. www.profajaypashankar.com Page 15 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR You all must have got an idea about Python docstrings but have you ever wondered what is the difference between Python comments and docstrings? Let’s have a look at them. They are useful information that the developers provide to make the reader understand the source code. It explains the logic or a part of it used in the code. It is written using # symbols. ------------------------------------------------------------------------------------------------------------------ ---- IDLE stands for Integrated Development and Learning Environment. The lightweight and user-friendly Python IDLE (Integrated Development and Learning Environment) is a tool for Python programming. Since version 1.5.2b1, the standard Python implementation has included IDLE, an integrated development environment. Many Linux distributions include it in the Python packaging as an optional component. The Tkinter GUI toolkit and Python are used throughout. IDLE is meant to be a basic IDE and suited for novices, particularly in an educational context. It is cross-platform and reduces feature clutter as a result. ------------------------------------------------------------------------------------------------------------ --- What is meant by Python IDLE? An Integrated Development and Learning Environment, sometimes known as IDLE or even IDE, is included with every Python setup. These are a group of programmes that make it easier to write code. Although there are several IDEs available, Python IDLE is fairly basic, making it the ideal tool for a beginner coder. Python installs for Windows and Mac include Python IDLE. Python IDLE should be easy to locate and download if you run Linux thanks to the package management. After installation, you may use Python IDLE as a file editor or an interactive interpreter. ------------------------------------------------------------------------------------------------------------ --- What are the primary features of Python IDLE? The principal functions of the Python IDLE are given below - o Made entirely of Python code and the tkinter GUI toolkit. o Search across numerous files (grep), alter text within editor windows, and search across any window. o Cross-platform, largely same behaviour on Windows, Unix, and macOS o The interactive Python shell window has coloured input, output, and messages of error. o Debugging tool featuring stepping, permanent breakpoints, and namespace viewing. o Very powerful debugger, dialogs, browsers, and configuration. www.profajaypashankar.com Page 16 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR o Multi undo, Python colorizing, sensible indent, call hints, auto finish, and more features are included in this multi-window text editor. ------------------------------------------------------------------------------------------------------------ -- Advantages of Python IDLE: The following are some benefits of utilising Python IDLE: o Python IDLE is an interactive shell that enables users to easily test and run short bits of Python code without needing to create a whole programme. o Python IDLE's code editor has features like syntax highlighting and code completion that make it simpler and faster to write Python programmes. o Python IDLE has a built-in debugger that enables programmers to walk through their code and find faults and problems. o Python IDLE may be used on Linux, macOS, and Windows thanks to its cross-platform nature. o Python IDLE is included with the Python installation, thus users don't need to install any more programmes in order to begin coding in Python. o Python IDLE is open-source, free software, which entitles users to use it with no any limitations for both business and non-commercial uses. --------------------------------------------------------------------------------------------------------------- Disadvantages of Python IDLE: Using Python IDLE has certain drawbacks in addition to its numerous benefits, including: o The Python IDLE IDE is a rudimentary one that lacks many of the more sophisticated capabilities found in other IDEs. For instance, it lacks tools for project management, version control, and code refactoring. o When working with big codebases, Python IDLE is not as quick as other IDEs. When processing a lot of data, it could become sluggish and unresponsive. o Python IDLE lacks the sophisticated capabilities and tools necessary for handling larger codebases, making it unsuitable for the development of large, complicated projects. o Compared to other IDEs, Python IDLE has fewer customization possibilities and is less flexible. It could be challenging for users to alter the UI to suit their tastes. o Python IDLE's capability and extensibility are constrained by the lack of numerous third-party plugins. o Python IDLE's user interface is not particularly contemporary or aesthetically pleasing. For seasoned developers, this might not be an issue, but for new developers, it might be a roadblock ------------------------------------------------------------------------------------------------------------ --- What is meant by the Interactive Interpreter? The first-class area to test with Python code is the interactive interpreter, additionally known as the shell. The shell is a basic study-eval-print (REPL) loop. Reads a Python assertion, evaluates the result of that declaration, and prints the result to the display screen. Then leap to examine the subsequent statement. The Python shell is a first-rate vicinity to attempt small snippets of code. You can get the right of entry to it from your laptop's terminal or command line app. Simplify your workflow with Python IDLE, which launches a Python shell as quickly as you open i ------------------------------------------------------------------------------------------------------------------ ---- Python Data Types Every value has a datatype, and variables can hold values. Python is a powerfully composed language; consequently, we don't have to characterize the sort of variable while announcing it. The interpreter binds the value implicitly to its type. 1. a = 5 We did not specify the type of the variable a, which has the value five from an integer. The Python interpreter will automatically interpret the variable as an integer. We can verify the type of the program-used variable thanks to Python. The type() function in Python returns the type of the passed variable. Consider the following illustration when defining and verifying the values of various data types. 1. a=10 2. b="Hi Python" 3. c = 10.5 4. print(type(a)) 5. print(type(b)) 6. print(type(c)) www.profajaypashankar.com Page 17 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR Output: -------------------------------------------------------------------------------------------------------------------- ---- Standard data types A variable can contain a variety of values. On the other hand, a person's id must be stored as an integer, while their name must be stored as a string. The storage method for each of the standard data types that Python provides is specified by Python. The following is a list of the Python-defined data types. 1. Numbers 2. Sequence Type 3. Boolean 4. Set 5. Dictionary The data types will be briefly discussed in this tutorial section. We will talk about every single one of them exhaustively later in this instructional exercise. -------------------------------------------------------------------------------------------------------------------- ---- Numbers Numeric values are stored in numbers. The whole number, float, and complex qualities have a place with a Python Numbers datatype. Python offers the type() function to determine a variable's data type. The instance () capability is utilized to check whether an item has a place with a specific class. When a number is assigned to a variable, Python generates Number objects. For instance, 1. a = 5 2. print("The type of a", type(a)) 3. 4. b = 40.5 5. print("The type of b", type(b)) 6. 7. c = 1+3j 8. print("The type of c", type(c)) 9. print(" c is a complex number", isinstance(1+3j,complex)) Output: The type of a The type of b The type of c c is complex number: True Python supports three kinds of numerical data. www.profajaypashankar.com Page 18 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and so on. An integer can be any length you want in Python. Its worth has a place with int. o Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to within 15 decimal places. o Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y signify the genuine and non-existent parts separately. The complex numbers like 2.14j, 2.0 + 2.3j, etc. --------------------------------------------------------------------------------------------------------------------- --- Sequence Type String The sequence of characters in the quotation marks can be used to describe the string. A string can be defined in Python using single, double, or triple quotes. String dealing with Python is a direct undertaking since Python gives worked-in capabilities and administrators to perform tasks in the string. When dealing with strings, the operation "hello"+" python" returns "hello python," and the operator + is used to combine two strings. Because the operation "Python" *2 returns "Python," the operator * is referred to as a repetition operator. The Python string is demonstrated in the following example. Example - 1 1. str = "string using double quotes" 2. print(str) 3. s = '''''A multiline 4. string''' 5. print(s) Output: string using double quotes A multiline string Look at the following illustration of string handling. Example - 2 1. str1 = 'hello javatpoint' #string str1 2. str2 = ' how are you' #string str2 3. print (str1[0:2]) #printing first two character using slice operator 4. print (str1) #printing 4th character of the string 5. print (str1*2) #printing the string twice 6. print (str1 + str2) #printing the concatenation of str1 and str2 Output: he o hello javatpointhello javatpoint hello javatpoint how are you -------------------------------------------------------------------------------------------------------------------- ---- List Lists in Python are like arrays in C, but lists can contain data of different types. The things put away in the rundown are isolated with a comma (,) and encased inside square sections []. To gain access to the list's data, we can use slice [:] operators. Like how they worked with strings, the list is handled by the concatenation operator (+) and the repetition operator (*). Look at the following example. Example: 1. list1 = [1, "hi", "Python", 2] 2. #Checking type of given list 3. print(type(list1)) 4. 5. #Printing the list1 6. print (list1) 7. 8. # List slicing 9. print (list1[3:]) 10. www.profajaypashankar.com Page 19 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR 11. # List slicing 12. print (list1[0:2]) 13. 14. # List Concatenation using + operator 15. print (list1 + list1) 16. 17. # List repetation using * operator 18. print (list1 * 3) Output: [1, 'hi', 'Python', 2] [1, 'hi'] [1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2] [1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2] Tuple In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from various data types. A parenthetical space () separates the tuple's components from one another. Because we cannot alter the size or value of the items in a tuple, it is a read-only data structure. Let's look at a straightforward tuple in action. Example: 1. tup = ("hi", "Python", 2) 2. # Checking type of tup 3. print (type(tup)) 4. 5. #Printing the tuple 6. print (tup) 7. 8. # Tuple slicing 9. print (tup[1:]) 10. print (tup[0:1]) 11. 12. # Tuple concatenation using + operator 13. print (tup + tup) 14. 15. # Tuple repatation using * operator 16. print (tup * 3) 17. 18. # Adding value to tup. It will throw an error. 19. t = "hi" Output: ('hi', 'Python', 2) ('Python', 2) ('hi',) ('hi', 'Python', 2, 'hi', 'Python', 2) ('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2) Traceback (most recent call last): File "main.py", line 14, in t = "hi"; TypeError: 'tuple' object does not support item assignment -------------------------------------------------------------------------------------------------------------------- ---- Dictionary A dictionary is a key-value pair set arranged in any order. It stores a specific value for each key, like an associative array or a hash table. Value is any Python object, while the key can hold any primitive data type. The comma (,) and the curly braces are used to separate the items in the dictionary. Look at the following example. 1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'} 2. 3. # Printing dictionary 4. print (d) 5. www.profajaypashankar.com Page 20 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR 6. # Accesing value using keys 7. print("1st name is "+d) 8. print("2nd name is "+ d) 9. 10. print (d.keys()) 11. print (d.values()) Output: 1st name is Jimmy 2nd name is mike {1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'} dict_keys([1, 2, 3, 4]) dict_values(['Jimmy', 'Alex', 'john', 'mike']) Boolean True and False are the two default values for the Boolean type. These qualities are utilized to decide the given assertion valid or misleading. The class book indicates this. False can be represented by the 0 or the letter "F," while true can be represented by any value that is not zero. Look at the following example. 1. # Python program to check the boolean type 2. print(type(True)) 3. print(type(False)) 4. print(false) Output: NameError: name 'false' is not defined -------------------------------------------------------------------------------------------------------------------- --- Set The data type's unordered collection is Python Set. It is iterable, mutable(can change after creation), and has remarkable components. The elements of a set have no set order; It might return the element's altered sequence. Either a sequence of elements is passed through the curly braces and separated by a comma to create the set or the built-in function set() is used to create the set. It can contain different kinds of values. Look at the following example. 1. # Creating Empty set 2. set1 = set() 3. 4. set2 = {'James', 2, 3,'Python'} 5. 6. #Printing Set value 7. print(set2) 8. 9. # Adding element to the set 10. 11. set2.add(10) 12. print(set2) 13. 14. #Removing element from the set 15. set2.remove(2) 16. print(set2) Output: {3, 'Python', 'James', 2} {'Python', 'James', 3, 2, 10} {'Python', 'James', 3, 10} -------------------------------------------------------------------------------------------------------------------- ---- Python Mapping Types: The mapping objects are used to map hash table values to arbitrary objects. In python there is mapping type called dictionary. It is mutable. The keys of the dictionary are arbitrary. As the value, we can use different kind of elements like lists, integers or any other mutable type objects. Some dictionary related methods and operations are − www.profajaypashankar.com Page 21 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR Method len(d) The len() method returns the number of elements in the dictionary. Operation d[k] It will return the item of d with the key ‘k’. It may raise KeyError if the key is not mapped. Method iter(d) This method will return an iterator over the keys of dictionary. We can also perform this taks by using iter(d.keys()). Method get(key[, default]) The get() method will return the value from the key. The second argument is optional. If the key is not present, it will return the default value. Method items() It will return the items using (key, value) pairs format. Method keys() Return the list of different keys in the dictionary. Method values() Return the list of different values from the dictionary. Method update(elem) Modify the element elem in the dictionary. Example Code myDict = {'ten' : 10, 'twenty' : 20, 'thirty' : 30, 'forty' : 40} print(myDict) print(list(myDict.keys())) print(list(myDict.values())) #create items from the key-value pairs print(list(myDict.items())) myDict.update({'fifty' : 50}) print(myDict) Output {'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40} ['ten', 'twenty', 'thirty', 'forty'] [10, 20, 30, 40] [('ten', 10), ('twenty', 20), ('thirty', 30), ('forty', 40)] {'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50} -------------------------------------------------------------------------------------------------------------------- ---- Basic Elements of Python Python is a versatile and widely-used programming language known for its readability and ease of use. Here are some of the basic elements of Python: 1. Variables and Data Types Variables Variables are used to store data values. In Python, you don't need to declare a variable with a specific type. The type is inferred from the value assigned to it. python Copy code x=5 y = "Hello" Data Types Numbers: int, float, complex String: str Boolean: bool List: list Tuple: tuple Set: set Dictionary: dict python Copy code a = 10 # int b = 3.14 # float c = 1 + 2j # complex d = "Python" # str e = True # bool www.profajaypashankar.com Page 22 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR f = [1, 2, 3] # list g = (4, 5, 6) # tuple h = {1, 2, 3} # set i = {"key": "value"} # dict -------------------------------------------------------------------------------------------------------------------- ---- 2. Operators Arithmetic Operators: +, -, *, /, %, **, // Comparison Operators: ==, !=, >, =, y) # True print(x and y) # 2 (non-zero value is True) -------------------------------------------------------------------------------------------------------------------- ---- 3. Control Flow Statements Conditional Statements python Copy code if x > y: print("x is greater than y") elif x == y: print("x is equal to y") else: print("x is less than y") -------------------------------------------------------------------------------------------------------------------- ---- Loops For Loop: Iterates over a sequence (like a list, tuple, dictionary, set, or string) While Loop: Repeats as long as a condition is true python Copy code # For loop for i in range(5): print(i) # While loop i=0 while i < 5: print(i) i += 1 -------------------------------------------------------------------------------------------------------------------- ---- 4. Functions Functions are blocks of code that perform a specific task and can be reused. python Copy code def greet(name): return "Hello, " + name print(greet("Alice")) -------------------------------------------------------------------------------------------------------------------- ---- 5. Modules and Packages Modules are files containing Python code (e.g., mymodule.py), and packages are directories containing multiple modules. python Copy code www.profajaypashankar.com Page 23 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR # mymodule.py def greet(name): return "Hello, " + name # main.py import mymodule print(mymodule.greet("Alice")) -------------------------------------------------------------------------------------------------------------------- ---- 6. Exception Handling Python uses try, except, finally blocks to handle exceptions (errors). python Copy code try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero") finally: print("This block is always executed") -------------------------------------------------------------------------------------------------------------------- ---- 7. Classes and Objects Python is an object-oriented programming language. You can define your own classes to create objects. python Copy code class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): return "Hello, my name is " + self.name p1 = Person("Alice", 30) print(p1.greet()) -------------------------------------------------------------------------------------------------------------------- ---- 8. File I/O Python can read from and write to files. python Copy code # Writing to a file with open("example.txt", "w") as file: file.write("Hello, World!") # Reading from a file with open("example.txt", "r") as file: content = file.read() print(content) -------------------------------------------------------------------------------------------------------------------- ---- 9. Libraries Python has a rich standard library and numerous third-party libraries. You can install third-party libraries using pip. python Copy code # Example using the math library import math print(math.sqrt(16)) These are the basic elements of Python that provide a foundation for writing and understanding Python code. www.profajaypashankar.com Page 24 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR -------------------------------------------------------------------------------------------------------------------------- ---- Variables, Input Function, Output Statements, and Command Line Arguments: Variables Variables in Python are used to store data that can be referenced and manipulated later in the program. Python is dynamically typed, meaning you don't need to declare the type of a variable explicitly. The type is inferred from the value assigned to it. Example: python Copy code # Assigning values to variables x=5 y = "Hello, World!" z = 3.14 # Printing variable values print(x) # Output: 5 print(y) # Output: Hello, World! print(z) # Output: 3.14 Input Function The input() function is used to take input from the user. It reads a line from the input, converts it to a string (unless a different type conversion is performed), and returns it. Example: python Copy code # Taking input from the user name = input("Enter your name: ") age = int(input("Enter your age: ")) # Printing the input values print("Name:", name) print("Age:", age) Output Statements The print() function is used to display output in Python. It can output strings, numbers, and other data types. Example: python Copy code # Outputting strings and variables name = "Alice" age = 30 print("Name:", name) print("Age:", age) # Outputting formatted strings print(f"Name: {name}, Age: {age}") print("Name: {}, Age: {}".format(name, age)) Command Line Arguments Command line arguments are parameters passed to the script when it is executed. These can be accessed using the sys module. Example: Create a Python script named script.py with the following content: python Copy code import sys # Check if arguments are provided if len(sys.argv) > 1: # Print the script name print("Script Name:", sys.argv) # Print all arguments for i in range(1, len(sys.argv)): print(f"Argument {i}: {sys.argv[i]}") www.profajaypashankar.com Page 25 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR else: print("No command line arguments provided.") To run the script with command line arguments, use the terminal: sh Copy code python script.py arg1 arg2 arg3 Expected Output: yaml Copy code Script Name: script.py Argument 1: arg1 Argument 2: arg2 Argument 3: arg3 Summary Variables: Used to store data values. Input Function: input() is used to get input from the user. Output Statements: print() is used to display output. Command Line Arguments: Accessed via the sys.argv list, allowing parameters to be passed to a script at execution time. -------------------------------------------------------------------------------------------------------------------------- -- Operators in Python Operators are special symbols used to perform operations on variables and values. Python supports several types of operators: 1. Arithmetic Operators + (Addition): Adds two operands. - (Subtraction): Subtracts the second operand from the first. * (Multiplication): Multiplies two operands. / (Division): Divides the first operand by the second. % (Modulus): Returns the remainder of the division. ** (Exponentiation): Raises the first operand to the power of the second. // (Floor Division): Divides the first operand by the second and rounds down to the nearest whole number. Example: python Copy code a = 10 b=3 print(a + b) # 13 print(a - b) # 7 print(a * b) # 30 print(a / b) # 3.3333333333333335 print(a % b) # 1 print(a ** b) # 1000 print(a // b) # 3 -------------------------------------------------------------------------------------------------------------------------- -- 2. Comparison Operators == (Equal): Checks if two operands are equal. != (Not equal): Checks if two operands are not equal. > (Greater than): Checks if the first operand is greater than the second. < (Less than): Checks if the first operand is less than the second. >= (Greater than or equal to): Checks if the first operand is greater than or equal to the second. www.profajaypashankar.com Page 26 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR b) # False print(a < b) # True print(a >= b) # False print(a (Signed right shift): Shifts the bits of the first operand right by the number of positions specified by the second operand. Example: python Copy code a = 60 # 60 = 0011 1100 b = 13 # 13 = 0000 1101 print(a & b) # 12 = 0000 1100 print(a | b) # 61 = 0011 1101 print(a ^ b) # 49 = 0011 0001 print(~a) # -61 = 1100 0011 print(a > 2) # 15 = 0000 1111 -------------------------------------------------------------------------------------------------------------------------- -- Precedence of Operators Operator precedence determines the order in which operations are evaluated. Operators with higher precedence are evaluated before operators with lower precedence. Here is the order of precedence in Python from highest to lowest: 1. ** 2. ~, + (unary plus), - (unary minus) 3. *, /, //, % 4. +, - 5. >>, , =, = b These conditions can be used in several ways, most commonly in "if statements" and loops. An "if statement" is written by using the if keyword. Example If statement: a = 33 b = 200 if b > a: print("b is greater than a") In this example we use two variables, a and b, which are used as part of the if statement to test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to screen that "b is greater than a". Indentation Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose. Example If statement, without indentation (will raise an error): a = 33 b = 200 if b > a: print("b is greater than a") # you will get an error Elif The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition". Example a = 33 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print to screen that "a and b are equal". Else www.profajaypashankar.com Page 29 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR The else keyword catches anything which isn't caught by the preceding conditions. Example a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b") In this example a is greater than b, so the first condition is not true, also the elif condition is not true, so we go to the else condition and print to screen that "a is greater than b". You can also have an else without the elif: Example a = 200 b = 33 if b > a: print("b is greater than a") else: print("b is not greater than a") Short Hand If If you have only one statement to execute, you can put it on the same line as the if statement. Example One line if statement: if a > b: print("a is greater than b") Short Hand If... Else If you have only one statement to execute, one for if, and one for else, you can put it all on the same line: Example One line if else statement: a=2 b = 330 print("A") if a > b else print("B") This technique is known as Ternary Operators, or Conditional Expressions. You can also have multiple else statements on the same line: Example One line if else statement, with 3 conditions: a = 330 b = 330 print("A") if a > b else print("=") if a == b else print("B") And The and keyword is a logical operator, and is used to combine conditional statements: Example Test if a is greater than b, AND if c is greater than a: a = 200 b = 33 c = 500 if a > b and c > a: print("Both conditions are True") Or The or keyword is a logical operator, and is used to combine conditional statements: Example Test if a is greater than b, OR if a is greater than c: a = 200 b = 33 c = 500 if a > b or a > c: www.profajaypashankar.com Page 30 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR print("At least one of the conditions is True") ------------------------------------------------------------------------------------------------------------------------- ---- Not The not keyword is a logical operator, and is used to reverse the result of the conditional statement: Example Test if a is NOT greater than b: a = 33 b = 200 if not a > b: print("a is NOT greater than b") Nested If You can have if statements inside if statements, this is called nested if statements. Example x = 41 if x > 10: print("Above ten,") if x > 20: print("and also above 20!") else: print("but not above 20.") The pass Statement if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error. Example a = 33 b = 200 if b > a: pass Python assert keyword Python Assertions in any programming language are the debugging tools that help in the smooth flow of code. Assertions are mainly assumptions that a programmer knows or always wants to be true and hence puts them in code so that failure of these doesn’t allow the code to execute further. Assert Keyword in Python In simpler terms, we can say that assertion is the boolean expression that checks if the statement is True or False. If the statement is true then it does nothing and continues the execution, but if the statement is False then it stops the execution of the program and throws an error. Flowchart of Python Assert Statement www.profajaypashankar.com Page 31 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR Flowchart of Python Assert Statement Python assert keyword Syntax In Python, the assert keyword helps in achieving this task. This statement takes as input a boolean condition, which when returns true doesn’t do anything and continues the normal flow of execution, but if it is computed to be false, then it raises an AssertionError along with the optional message provided. Syntax : assert condition, error_message(optional) Parameters: condition : The boolean condition returning true or false. error_message : The optional argument to be printed in console in case of AssertionError Returns: Returns AssertionError, in case the condition evaluates to false along with the error message which when provided. Python assert keyword without error message This code is trying to demonstrate the use of assert in Python by checking whether the value of b is 0 before performing a division operation. a is initialized to the value 4, and b is initialized to the value 0. The program prints the message “The value of a / b is: “.The assert statement checks whether b is not equal to 0. Since b is 0, the assert statement fails and raises an AssertionError. Since an exception is raised by the failed assert statement, the program terminates and does not continue to execute the print statement on the next line. Python3 # initializing number a=4 b=0 # using assert to check for 0 print("The value of a / b is : ") assert b != 0 print(a / b) Output: The value of a / b is : --------------------------------------------------------------------------- AssertionError Traceback (most recent call last) Input In , in () 8 # using assert to check for 0 9 print("The value of a / b is : ") ---> 10 assert b != 0 11 print(a / b) AssertionError: Python assert keyword with an error message This code is trying to demonstrate the use of assert in Python by checking whether the value of b is 0 before performing a division operation. a is initialized to the value 4, and b is initialized to the value 0. The www.profajaypashankar.com Page 32 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR program prints the message “The value of a / b is: “.The assert statement checks whether b is not equal to 0. Since b is 0, the assert statement fails and raises an AssertionError with the message “Zero Division Error”. Since an exception is raised by the failed assert statement, the program terminates and does not continue to execute the print statement on the next line. Assert Inside a Function The assert statement is used inside a function in this example to verify that a rectangle’s length and width are positive before computing its area. The assertion raises an AssertionError with the message “Length and width must be positive” if it is false. If the assertion is true, the function returns the rectangle’s area; if it is false, it exits with an error. To show how to utilize assert in various situations, the function is called twice, once with positive inputs and once with negative inputs. Python3 # Function to calculate the area of a rectangle def calculate_rectangle_area(length, width): # Assertion to check that the length and width are positive assert length > 0 and width > 0, "Length and width"+ \ "must be positive" # Calculation of the area area = length * width # Return statement return area # Calling the function with positive inputs area1 = calculate_rectangle_area(5, 6) print("Area of rectangle with length 5 and width 6 is", area1) # Calling the function with negative inputs area2 = calculate_rectangle_area(-5, 6) print("Area of rectangle with length -5 and width 6 is", area2) Output: AssertionError: Length and widthmust be positive Assert with boolean Condition In this example, the assert statement checks whether the boolean condition x < y is true. If the assertion fails, it raises an AssertionError. If the assertion passes, the program continues and prints the values of x and y. Python3 # Initializing variables x = 10 y = 20 # Asserting a boolean condition assert x < y # Printing the values of x and y print("x =", x) print("y =", y) Output: x = 10 y = 20 Assert Type of Variable in Python In this example, the assert statements check whether the types of the variables a and b are str and int, respectively. If any of the assertions fail, it raises an AssertionError. If both assertions pass, the program continues and prints the values of a and b. Python3 www.profajaypashankar.com Page 33 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR # Initializing variables a = "hello" b = 42 # Asserting the type of a variable assert type(a) == str assert type(b) == int # Printing the values of a and b print("a =", a) print("b =", b) Output: a = hello b = 42 Asserting dictionary values In this example, the assert statements check whether the values associated with the keys “apple”, “banana”, and “cherry” in the dictionary my_dict are 1, 2, and 3, respectively. If any of the assertions fail, it raises an AssertionError. If all assertions pass, the program continues and prints the contents of the dictionary. Python3 # Initializing a dictionary my_dict = {"apple": 1, "banana": 2, "cherry": 3} # Asserting the contents of the dictionary assert my_dict["apple"] == 1 assert my_dict["banana"] == 2 assert my_dict["cherry"] == 3 # Printing the dictionary print("My dictionary contains the following key-value pairs:", my_dict) Output: My dictionary contains the following key-value pairs: {'apple': 1, 'banana': 2, 'cherry': 3} Practical Application This has a much greater utility in the Testing and Quality Assurance roles in any development domain. Different types of assertions are used depending on the application. Below is a simpler demonstration of a program that only allows only the batch with all hot food to be dispatched, else rejects the whole batch. Python3 # Python 3 code to demonstrate # working of assert # Application # initializing list of foods temperatures batch = [ 40, 26, 39, 30, 25, 21] # initializing cut temperature cut = 26 # using assert to check for temperature greater than cut for i in batch: assert i >= 26, "Batch is Rejected" print (str(i) + " is O.K" ) Output: 40 is O.K 26 is O.K 39 is O.K 30 is O.K Runtime Exception: AssertionError: Batch is Rejected www.profajaypashankar.com Page 34 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR Why Use Python Assert Statement? In Python, the assert statement is a potent debugging tool that can assist in identifying mistakes and ensuring that your code is operating as intended. Here are several justifications for using assert: 1. Debugging: Assumptions made by your code can be verified with the assert statement. You may rapidly find mistakes and debug your program by placing assert statements throughout your code. 2. Documentation: The use of assert statements in your code might act as documentation. Assert statements make it simpler for others to understand and work with your code since they explicitly describe the assumptions that your code is making. 3. Testing: In order to ensure that certain requirements are met, assert statements are frequently used in unit testing. You can make sure that your code is working properly and that any changes you make don’t damage current functionality by incorporating assert statements in your tests. 4. Security: You can use assert to check that program inputs comply with requirements and validate them. By doing so, security flaws like buffer overflows and SQL injection attacks may be avoided. CHAPTER III: ARRAYS Topics covered: Creating Arrays, Indexing and Slicing of Arrays, Basic Array Operations, Arrays Processing, Mathematical Operations on Array, Aliasing Arrays, Slicing and Indexing in NumPy Arrays, Basic slicing, Advanced Indexing, Dimensions and Attributes of an Array ----------------------------------------------------------------------------------------------------------------------- Python Arrays For simplicity, we can think of a Python array as a fleet of stairs where on each step is placed a value (let’s say one of your friends). Here, you can identify the location of any of your friends by simply knowing the count of the steps they are on. The array can be handled in Python by a module named array. They can be useful when we have to manipulate only specific data type values. A user can treat lists as arrays. However, the user cannot constrain the type of elements stored in a list. If you create Python arrays using the array module, all elements of the array in Python must be of the same type. In this article, we will see how to use an array in Python with examples. What is an Array in Python? An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). www.profajaypashankar.com Page 35 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR Create an Array in Python Array in Python can be created by importing an array module. array(data_type, value_list) is used to create array in Python with data type and value list specified in its arguments. In below code Python create array : one of integers and one of doubles. It then prints the contents of each array to the console. Python import array as arr a = arr.array('i', [1, 2, 3]) print("The new created array is : ", end=" ") for i in range(0, 3): print(a[i], end=" ") print() b = arr.array('d', [2.5, 3.2, 3.3]) print("\nThe new created array is : ", end=" ") for i in range(0, 3): print(b[i], end=" ") Output The new created array is : 1 2 3 The new created array is : 2.5 3.2 3.3 Complexities for Creation of Arrays: Time Complexity: O(1) Auxiliary Space: O(n) Some of the data types are mentioned below which will help in create array in Python 3.8 of different data types. www.profajaypashankar.com Page 36 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR Now we will see how to use array in Python 3.8 with example. Adding Elements to a Array Elements can be added to the Python Array by using built-in insert() function. Insert is used to insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of array. append() is also used to add the value mentioned in its arguments at the end of the Python array. Below, code first imports the array module as Python import array as arr. Then, it creates an array of integers named a with elements [1, 2, 3]. In below code Python print array as array is printed before and after inserting the integer 4 at index 1. Similarly, an array of doubles named b with elements [2.5, 3.2, 3.3] is created and printed before and after appending the double 4.4 to the array. Python import array as arr a = arr.array('i', [1, 2, 3]) print("Array before insertion : ", end=" ") for i in range(0, 3): print(a[i], end=" ") print() a.insert(1, 4) print("Array after insertion : ", end=" ") for i in (a): print(i, end=" ") print() b = arr.array('d', [2.5, 3.2, 3.3]) print("Array before insertion : ", end=" ") for i in range(0, 3): print(b[i], end=" ") print() b.append(4.4) print("Array after insertion : ", end=" ") for i in (b): print(i, end=" ") print() www.profajaypashankar.com Page 37 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR Output Array before insertion : 1 2 3 Array after insertion : 1 4 2 3 Array before insertion : 2.5 3.2 3.3 Array after insertion : 2.5 3.2 3.3 4.4 Complexities for Adding elements to the Arrays Time Complexity: O(1)/O(n) ( O(1) – for inserting elements at the end of the array, O(n) – for inserting elements at the beginning of the array and to the full array Auxiliary Space: O(1) Accessing Elements from the Array In order to access the array items refer to the index number. Use the index operator [ ] to access an item in a array in Python. The index must be an integer. Below, code shows first how to Python import array and use of indexing to access elements in arrays. The a expression accesses the first element of the array a, which is 1. The a expression accesses the fourth element of the array a, which is 4. Similarly, the b expression accesses the second element of the array b, which is 3.2, and the b expression accesses the third element of the array b, which is 3.3. Python import array as arr a = arr.array('i', [1, 2, 3, 4, 5, 6]) print("Access element is: ", a) print("Access element is: ", a) b = arr.array('d', [2.5, 3.2, 3.3]) print("Access element is: ", b) print("Access element is: ", b) Output Access element is: 1 Access element is: 4 Access element is: 3.2 Access element is: 3.3 Complexities for accessing elements in the Arrays Time Complexity: O(1) Auxiliary Space: O(1) Removing Elements from the Array Elements can be removed from the Python array by using built-in remove() function but an Error arises if element doesn’t exist in the set. Remove() method only removes one element at a time, to remove range of elements, iterator is used. pop() function can also be used to remove and return an element from the array, but by default it removes only the last element of the array, to remove element from a specific position of the array, index of the element is passed as an argument to the pop() method. Note – Remove method in List will only remove the first occurrence of the searched element. Below, code shows how to Python import array, how to create, print, remove elements from, and access elements of an array in Python. It imports the array module, which is used to work with arrays. It creates an array of integers in and Python print arrays or prints the original array. It then removes an element from the array and prints the modified array. Finally, it removes all occurrences of a specific element from the array and prints the updated array Python import array arr = array.array('i', [1, 2, 3, 1, 5]) print("The new created array is : ", end="") for i in range(0, 5): print(arr[i], end=" ") print("\r") print("The popped element is : ", end="") print(arr.pop(2)) print("The array after popping is : ", end="") for i in range(0, 4): print(arr[i], end=" ") print("\r") www.profajaypashankar.com Page 38 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR arr.remove(1) print("The array after removing is : ", end="") for i in range(0, 3): print(arr[i], end=" ") Output The new created array is : 1 2 3 1 5 The popped element is : 3 The array after popping is : 1 2 1 5 The array after removing is : 2 1 5 Complexities for Removing elements in the Arrays Time Complexity: O(1)/O(n) ( O(1) – for removing elements at the end of the array, O(n) – for removing elements at the beginning of the Python create array and to the full array Auxiliary Space: O(1) Slicing of an Array In Python array, there are multiple ways to print the whole array with all the elements, but to print a specific range of elements from the array, we use Slice operation. Slice operation is performed on array with the use of colon(:). To print elements from beginning to a range use [:Index], to print elements from end use [:-Index], to print elements from specific Index till the end use [Index:], to print elements within a range, use [Start Index:End Index] and to print whole List with the use of slicing operation, use [:]. Further, to print whole array in reverse order, use [::-1]. This code employs slicing to extract elements or subarrays from an array. It starts with an initial array of integers and creates an array from the list. The code slices the array to extract elements from index 3 to 8, from index 5 to the end, and the entire array and In below code Python print array as The sliced arrays are then printed to demonstrate the slicing operations. Python import array as arr l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a = arr.array('i', l) print("Initial Array: ") for i in (a): print(i, end=" ") Sliced_array = a[3:8] print("\nSlicing elements in a range 3-8: ") print(Sliced_array) Sliced_array = a[5:] print("\nElements sliced from 5th " "element till the end: ") print(Sliced_array) Sliced_array = a[:] print("\nPrinting all elements using slice operation: ") print(Sliced_array) Output Initial Array: 1 2 3 4 5 6 7 8 9 10 Slicing elements in a range 3-8: array('i', [4, 5, 6, 7, 8]) www.profajaypashankar.com Page 39 of 68 FYCS VSC SEM I INTRODUCTION TO PYTHON PROGRAMMING BY: PROF.AJAY PASHANKAR Elements sliced from 5th element till the end: array('i', [6, 7, 8, 9, 10]) Printing all elements... Searching Element in an Array In order to search an element in the array we use a python in-built index() method. This function returns the index of the first occurrence of value mentioned in arguments. Example: The code demonstrates how to create array in Python, print its elements, and find the indices of specific elements. It imports the array module, creates an array of integers, prints the array using a for loop, and then uses the index() method to find the indices of the first occurrences of the integers 2 and 1. Python import array arr = array.array('i', [1, 2, 3, 1, 2, 5]) print("The new created array is : ", end="") for i in range(0, 6): print(arr[i], end=" ") print("\r") print("The index of 1st occurrence of 2 is : ", end="") print(arr.index(2)) print("The index of 1st occurrence of 1 is : ", end="") print(arr.index(1)) Output The new created array is : 1 2 3 1 2 5 The index of 1st occurrence of 2 is : 1 The index of 1st occurrence of 1 is : 0 Complexities for searching elements in the Arrays Time Complexity: O(n) Auxiliary Space: O(1) Updating Elements in a Array In order to update an element in the array we simply reassign a new value to the desired index we want to update. Example: This code illustrates the functionality of modifying elements within an array using indexing. It imports the array module, creates an array of integers, and prints the initial array. Then, it modifies two elements of the array at specific indexes and prints the updated array. This serves to demonstrate how indexing allows for dynamic manipulation of array contents. Python import array arr = array.array('i', [1, 2, 3, 1, 2, 5]) print("Array before updation : ", end="") for i in range(0, 6): print(arr[i], end=" ") print("\r") arr = 6 print("Array after updation : ", end="") for i in range(0, 6): print(arr[i], end=" ") print() arr = 8 print("Array after updation : ", end="") for i in range(0, 6): print(arr[i], end=" ") Output Array before updation : 1 2 3 1 2 5 Array after updation : 1 2 6 1 2 5 Array after updation : 1 2 6 1 8 5 Complexities for updating elements in the Arrays Time Complexity: O(1) Auxiliary Space: O(1) Different Operations on Python Arrays