0% found this document useful (0 votes)
0 views18 pages

Python Unit 1 Notes

Python is a widely used general-purpose programming language known for its simplicity and versatility across various applications such as web development, machine learning, and data science. It features dynamic typing, automatic garbage collection, and supports multiple programming paradigms, including object-oriented and functional programming. The document also covers Python's history, characteristics, data types, and common use cases in different fields.

Uploaded by

duttapiyush404
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views18 pages

Python Unit 1 Notes

Python is a widely used general-purpose programming language known for its simplicity and versatility across various applications such as web development, machine learning, and data science. It features dynamic typing, automatic garbage collection, and supports multiple programming paradigms, including object-oriented and functional programming. The document also covers Python's history, characteristics, data types, and common use cases in different fields.

Uploaded by

duttapiyush404
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

1 Python

UNIT - I

Today, Python is one of the most popular programming languages. Although it is a general-
purpose language, it is used in various areas of applications such as Machine Learning, Artificial
Intelligence, web development, IoT, and more.

What is Python?

Python is a very popular general-purpose interpreted, interactive, object-oriented, and high-level


programming language. Python is dynamically-typed and garbage-collected programming
language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code
is also available under the GNU General Public License (GPL).

Python Online Compiler/Interpreter

We have provided Python Online Compiler/Interpreter which helps you


to Edit and Execute the code directly from your browser. Try to click the icon to run the
following Python code to print conventional "Hello, World!".

# This is my first Python program.


# This will print 'Hello, World!' as the output

print ("Hello, World!");

Characteristics of Python

The following are important characteristics of Python Programming −

• 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.
Applications of Python
The latest release of Python is 3.x. As mentioned before, Python is one of the most widely used
languages on the web. I'm going to list a few of them here:

Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.

Prof. Shubhra Chinchmalatpure


2 Python

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 cross-platform
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.

Pythonic Code Style

Python leaves you free to choose to program in an object-oriented, procedural, functional, aspect-
oriented, or even logic-oriented way. These freedoms make Python a great language to write clean
and beautiful code.

Pythonic Code Style is actually more of a design philosophy and suggests to write a code which is
:

• Clean
• Simple
• Beautiful
• Explicit
• Readable
The Zen of Python
The Zen of Python is about code that not only works, but is Pythonic. Pythonic code is readable,
concise, and maintainable.
Python - History

Guido Van Rossum, a Dutch programmer, created Python programming language. In the late
80's, he had been working on the development of ABC language in a computer science research
institute named Centrum Wiskunde & Informatica (CWI) in the Netherlands. In 1991, Van
Rossum conceived and published Python as a successor of ABC language.

Prof. Shubhra Chinchmalatpure


3 Python

For many uninitiated people, the word Python is related to a species of snake. Rossum though
attributes the choice of the name Python to a popular comedy series Monty Python's Flying
Circus on BBC.

Being the principal architect of Python, the developer community conferred upon him the title
of Benevolent Dictator for Life (BDFL). However, in 2018, Rossum relinquished the title.
Thereafter, the development and distribution of the reference implementation of Python is handled
by a nonprofit organization Python Software Foundation.

Print Hello, World in Python

This tutorial will teach you how to write a simple Hello World program using Python
Programming language. This program will make use of Python built-in print() function to print
the string Hello, world! on our screen.

The Hello World program is a basic computer code written in a general purpose programming
language, used as a test program. It doesn't ask for any input and displays a Hello World message
on the output console. It is used to test if the software needed to compile and run the program has
been installed correctly.

Hello World Program at Command Prompt

It is very easy to display the Hello World message using the Python interpreter. Launch the Python
interpreter from a command terminal of your Windows Operating System and issue the print
statement from the Python prompt as follows −

PS C:\> python
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.

>>> print ("Hello World")


Hello World
For Windows OS, open the command prompt terminal (CMD) and run the program as shown
below –
C:\>python hello.py

Where is Python used?

Python is a general-purpose, popular programming language, and it is used in almost every


technical field. The various areas of Python use are given below.

Prof. Shubhra Chinchmalatpure


4 Python

o Data Science: Data Science is a vast field, and Python is an important language for this
field because of its simplicity, ease of use, and availability of powerful data analysis and
visualization libraries like NumPy, Pandas, and Matplotlib.
o Desktop Applications: PyQt and Tkinter are useful libraries that can be used in GUI -
Graphical User Interface-based Desktop Applications. There are better languages for this
field, but it can be used with other languages for making Applications.
o Console-based Applications: Python is also commonly used to create command-line or
console-based applications because of its ease of use and support for advanced features
such as input/output redirection and piping.
o Mobile Applications: While Python is not commonly used for creating mobile
applications, it can still be combined with frameworks like Kivy or BeeWare to create
cross-platform mobile applications.
o Software Development: Python is considered one of the best software-making languages.
Python is easily compatible with both from Small Scale to Large Scale software.
o Artificial Intelligence: AI is an emerging Technology, and Python is a perfect language
for artificial intelligence and machine learning because of the availability of powerful
libraries such as TensorFlow, Keras, and PyTorch.
o Web Applications: Python is commonly used in web development on the backend with
frameworks like Django and Flask and on the front end with tools like JavaScript and
HTML.
o Enterprise Applications: Python can be used to develop large-scale enterprise
applications with features such as distributed computing, networking, and parallel
processing.
o 3D CAD Applications: Python can be used for 3D computer-aided design (CAD)
applications through libraries such as Blender.
o Machine Learning: Python is widely used for machine learning due to its simplicity, ease
of use, and availability of powerful machine learning libraries.
o Computer Vision or Image Processing Applications: Python can be used for computer
vision and image processing applications through powerful libraries such as OpenCV and
Scikit-image.
o Speech Recognition: Python can be used for speech recognition applications through
libraries such as SpeechRecognition and PyAudio.

Prof. Shubhra Chinchmalatpure


5 Python

o Scientific computing: Libraries like NumPy, SciPy, and Pandas provide advanced
numerical computing capabilities for tasks like data analysis, machine learning, and more.
o Education: Python's easy-to-learn syntax and availability of many resources make it an
ideal language for teaching programming to beginners.
o Testing: Python is used for writing automated tests, providing frameworks like unit tests
and pytest that help write test cases and generate reports.
o Gaming: Python has libraries like Pygame, which provide a platform for developing
games using Python.
o IoT: Python is used in IoT for developing scripts and applications for devices like
Raspberry Pi, Arduino, and others.
o Networking: Python is used in networking for developing scripts and applications for
network automation, monitoring, and management.
o DevOps: Python is widely used in DevOps for automation and scripting of infrastructure
management, configuration management, and deployment processes.
o Finance: Python has libraries like Pandas, Scikit-learn, and Statsmodels for financial
modeling and analysis.
o Audio and Music: Python has libraries like Pyaudio, which is used for audio processing,
synthesis, and analysis, and Music21, which is used for music analysis and generation.
o Writing scripts: Python is used for writing utility scripts to automate tasks like file
operations, web scraping, and data processing.

Python Data Types:


Data types are the classification or categorization of data items. It represents the kind of value
that tells what operations can be performed on a particular data. Since everything is an object in
Python programming, data types are classes and variables are instances (objects) of these classes.
The following are the standard or built-in data types in Python:

Numeric
Sequence Type
Boolean
Set
Dictionary
Binary Types

Prof. Shubhra Chinchmalatpure


6 Python

What is Python type() Function?


To define the values of various data types and check their data types we use the type() function.
Consider the following examples.

This code assigns variable ‘x’ different values of various data types in Python. It covers string,
integer, float, complex, list, tuple, range, dictionary, set, frozenset, boolean, bytes, bytearray,
memoryview, and the special value ‘None’ successively. Each assignment replaces the previous
value, making ‘x’ take on the data type and value of the most recent assignment.

Sequence Data Type in Python


The sequence Data Type in Python is the ordered collection of similar or different data types.
Sequences allow storing of multiple values in an organized and efficient fashion. There are
several sequence types in Python –

Python String
Python List
Python Tuple
String Data Type
Strings in Python are arrays of bytes representing Unicode characters. A string is a collection of
one or more characters put in a single quote, double-quote, or triple-quote. In Python there is no
character data type, a character is a string of length one. It is represented by str class.

Creating String
Strings in Python can be created using single quotes, double quotes, or even triple quotes.

Example: This Python code showcases various string creation methods. It uses single quotes,
double quotes, and triple quotes to create strings with different content and includes a multiline
string. The code also demonstrates printing the strings and checking their data types.
Difference between List, Tuple, Set, and Dictionary
The following table shows the difference between various Python built-in
data structures.
List Tuple Set Dictionary

A list is a non-
A Tuple is a non-
homogeneous The set data A dictionary is
homogeneous data
data structure structure is non- also a non-
structure that
that stores the homogeneous homogeneous
stores elements in
elements in but stores the data structure
columns of a single
columns of a elements in a that stores key-
row or multiple
single row or single row. value pairs.
rows.
multiple rows.

Prof. Shubhra Chinchmalatpure


7 Python

List Tuple Set Dictionary

The list can be The set can be The dictionary


A tuple can be
represented by [ represented by { can be
represented by ( )
] } represented by { }

The list allows The Set will not The dictionary


Tuple allows
duplicate allow duplicate doesn’t allow
duplicate elements
elements elements duplicate keys.

The list can be The set can be The dictionary


A tuple can be
nested among nested among can be nested
nested among all
all all among all

Example: {1: “a”,


Example: [1, 2, Example: (1, 2, 3, Example: {1, 2,
2: “b”, 3: “c”, 4:
3, 4, 5] 4, 5) 3, 4, 5}
“d”, 5: “e”}

A list can be Tuple can be A set can be A dictionary can


created using created using created using be created using
the list() functio the tuple() function the set() functio the dict() function
n . n .

A set is mutable
A tuple is
A list is mutable i.e we can make A dictionary is
immutable i.e we
i.e we can make any changes in mutable, its Keys
can not make any
any changes in the set, its are not
changes in the
the list. elements are not duplicated.
tuple.
duplicated.

List is ordered

What is a Variable in Python?

Prof. Shubhra Chinchmalatpure


8 Python

A Python variable is a reserved memory location to store values. In other words, a variable in a
Python program gives data to the computer for processing. Every value in Python has a datatype.
Different data types in Python are Numbers, List, Tuple, Strings, Dictionary, etc. Variables can
be declared by any name or even alphabets like a, aa, abc, etc Variable Naming Rules in Python
1. Variable names should start with a letter(a-zA-Z) or underscore (_). Valid: age , _age , Age
Invalid : 1age
2. In variable names, no special characters are allowed other than underscore (_). Valid : age_ ,
_age Invalid : age_*
3. Variables are case-sensitive. age and Age are different since variable names are case-
sensitive.
4. Variable names can have numbers but not at the beginning. Example: Age1
5. The variable name should not be a Python keyword. Keywords are also called as reserved
words. Example pass, break, continue. etc are reserved for special meaning in Python. So, we
should not declare keyword as a variable name.
mutable and immutable objects:
As a Python developer, you’ll have to deal with mutable and immutable objects sooner or later.
Mutable objects are those that allow you to change their value or data in place without affecting
the object’s identity. In contrast, immutable objects don’t allow this kind of operation. You’ll
just have the option of creating new objects of the same type with different values.

In Python, mutability is a characteristic that may profoundly influence your decision when
choosing which data type to use in solving a given programming problem. Therefore, you need
to know how mutable and immutable objects work in Python.

Variables and Objects

In Python, variables don’t have an associated type or size, as they’re labels attached to objects in
memory. They point to the memory position where concrete objects live. In other words, a
Python variable is a name that refers to or holds a reference to a concrete object. In contrast,
Python objects are concrete pieces of information that live in specific memory positions on your
computer.

The main takeaway here is that variables and objects are two different animals in Python:

• Variables hold references to objects.

Prof. Shubhra Chinchmalatpure


9 Python

• Objects live in concrete memory positions.

Both concepts are independent of each other. However, they’re closely related. Once you’ve
created a variable with an assignment statement, then you can access the referenced object
throughout your code by using the variable name. If the referenced object is mutable, then you
can also perform mutations on it through the variable. Mutability or immutability is intrinsic to
objects rather than to variables.

However, if the referenced object is immutable, then you won’t be able to change its internal
state or contained data. You’ll just be able to make your variable reference a different object that,
in Python, may or may not be of the same type as your original object.

If you don’t have a reference (variable) to an object, then you can’t access that object in your
code. If you lose or remove all the references to a given object, then Python will garbage-
collect that object, freeing the memory for later use.

Now that you know that there are differences between variables and objects, you need to learn
that all Python objects have three core properties: identity, type, and value.

Objects, Value, Identity, and Type

In Python, everything is an object. For example, numbers, strings, functions, classes,


and modules are all objects. Every Python object has three core characteristics that define it at a
foundational level. These characteristics are:

1. Value
2. Identity
3. Type

Arguably, the value is probably the most familiar object characteristic that you’ve dealt with. An
object’s value consists of the concrete piece or pieces of data contained in the object itself. A
classic example is a numeric value like an integer or floating-point number:

Python
>>> 42
42
>>> isinstance(42, int)
True

>>> 3.14
3.14
>>> isinstance(3.14, float)
True

Prof. Shubhra Chinchmalatpure


10 Python

These numeric values, 42 and 3.14, are both objects. The first number is an instance of the built-
in int class, while the second is an instance of float. In both examples, you confirm the object’s
type using the built-in isinstance() function.

Command Line Arguments in Python:


The arguments that are given after the name of the program in the command line shell of the
operating system are known as Command Line Arguments. Python provides various ways of
dealing with these types of arguments. The three most common are:

• Using sys.argv
• Using getopt module
• Using argparse module
Using sys.argv
The sys module provides functions and variables used to manipulate different parts of the Python
runtime environment. This module provides access to some variables used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
One such variable is sys.argv which is a simple list structure. It’s main purpose are:

It is a list of command line arguments.


len(sys.argv) provides the number of command line arguments.
sys.argv[0] is the name of the current Python script.

Example: Let’s suppose there is a Python script for adding two numbers and the numbers are
passed as command-line arguments.
# Python program to demonstrate
# command line arguments

import sys

# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)

# Arguments passed
print("\nName of Python script:", sys.argv[0])

Prof. Shubhra Chinchmalatpure


11 Python

print("\nArguments passed:", end = " ")


for i in range(1, n):
print(sys.argv[i], end = " ")

# Addition of numbers
Sum = 0
# Using argparse module
for i in range(1, n):
Sum += int(sys.argv[i])

print("\n\nResult:", Sum)

Using getopt module


Python getopt module is similar to the getopt() function of C. Unlike sys module getopt module
extends the separation of the input string by parameter validation. It allows both short, and long
options including a value assignment. However, this module requires the use of the sys module
to process input data properly. To use getopt module, it is required to remove the first element
from the list of command-line arguments.

Syntax: getopt.getopt(args, options, [long_options])


Parameters:
args: List of arguments to be passed.
options: String of option letters that the script want to recognize. Options that require an
argument should be followed by a colon (:).
long_options: List of string with the name of long options. Options that require arguments should
be followed by an equal sign (=).

Prof. Shubhra Chinchmalatpure


12 Python

Return Type: Returns value consisting of two elements: the first is a list of (option, value) pairs.
The second is the list of program arguments left after the option list was stripped.
Using argparse module:
Using the argparse module is a better option than the above two options as it provides a lot of
options such as positional arguments, the default value for arguments, help message, specifying
the data type of argument, etc.

Note: As a default optional argument, it includes -h, along with its long version –help.
Python Operators:
Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:
Python divides the operators in the following groups:

Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators

Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example


+ Addition x+y
- Subtraction x - y
* Multiplication x * y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y

Python Operators

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Prof. Shubhra Chinchmalatpure


13 Python

Python divides the operators in the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical
operations:

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

Prof. Shubhra Chinchmalatpure


14 Python

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

Prof. Shubhra Chinchmalatpure


15 Python

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

Prof. Shubhra Chinchmalatpure


16 Python

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are true x < 5 and x < 10

or Returns True if one of the statements is true x < 5 or x < 4

not Reverse the result, returns False if the result is not(x < 5 and x < 10)
true

Prof. Shubhra Chinchmalatpure


17 Python

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location:

Operator Description Example

is Returns True if both variables are the same object x is y

is not Returns True if both variables are not the same x is not y
object

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the specified value is x in y


present in the object

not in Returns True if a sequence with the specified value is not x not in y
present in the object

Python Bitwise Operators

Prof. Shubhra Chinchmalatpure


18 Python

Bitwise operators are used to compare (binary) numbers:

Operator Name Description Example

& AND Sets each bit to 1 if both bits are 1 x&y

| OR Sets each bit to 1 if one of two bits is 1 x|y

^ XOR Sets each bit to 1 if only one of two bits is 1 x^y

~ NOT Inverts all the bits ~x

<< Zero fill left Shift left by pushing zeros in from the right and let the x << 2
shift leftmost bits fall off

>> Signed right Shift right by pushing copies of the leftmost bit in from x >> 2
shift the left, and let the rightmost bits fall off

Prof. Shubhra Chinchmalatpure

You might also like