0% found this document useful (0 votes)
4 views

MSC Unit 1 Python Notes

The document provides an overview of Python programming, highlighting its popularity and applications in various fields such as web development and machine learning. It covers fundamental concepts including data types, variables, keywords, functions, and error handling, along with examples and rules for defining and using these elements. Additionally, it discusses the structure and benefits of Python modules, both built-in and user-defined.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

MSC Unit 1 Python Notes

The document provides an overview of Python programming, highlighting its popularity and applications in various fields such as web development and machine learning. It covers fundamental concepts including data types, variables, keywords, functions, and error handling, along with examples and rules for defining and using these elements. Additionally, it discusses the structure and benefits of Python modules, both built-in and user-defined.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

The Yenepoya Institute of Arts, Science, Commerce and Management

A Constituent Unit of Yenepoya (Deemed to be University)


COURSE NAME-PYTHON PROGRAMMING

Python is a high-level, general-purpose, and very popular programming language. Python


programming language (latest Python 3) is being used in web development, Machine Learning
applications, along with all cutting-edge technology in Software Industry.
Python language is being used by almost all tech-giant companies like – Google, Amazon, Facebook,
Instagram, Dropbox, Uber… etc.
The biggest strength of Python is huge collection of standard library which can be used for the
following:
• Machine Learning
• GUI Applications (like Kivy, Tkinter, PyQt etc. )
• Web frameworks like Django (used by YouTube, Instagram, Dropbox)
• Image processing (like OpenCV, Pillow)
• Web scraping (like Scrapy, BeautifulSoup, Selenium)
• Test frameworks
• Multimedia
• Scientific computing
• Text processing and many more..

Python input/Output:
input (): This function first takes the input from the user and converts it into a string.
Syntax:input('STATEMENT')

Print(): print() function prints the message to the screen or any other standard output device.

Components of Python Language


A Components of Python Language is the smallest element in a program that is meaningful tothe
computer.These Components of Python Language define the structure of the language. It is also
known as a token of python language.
The five main components (tokens) of 'Python' language are:
• The character set
• The Data types
• Constants
• Variables
• Keywords

The character set


• Any alphabet, digits, or special symbol used to represent information is denoted bycharacter.
• The characters in Pythons are grouped into four categories.

Third Floor, BCIT, Tower 3-B (NON SEZ), Opposite to Leela Hotel Bhartiya City, Thanisandra Main Road, Kannuru, Bengaluru,
Karnataka-560064, India.
1 Letters A – – – Z or a – z

2 Digits 0,1,—-9

3 Special -.‟@#%'” &*()


Symbol _-+ = I\{}[]:;”‘<
s > , . ? /.

blank space,
4 White
horizontal tab,
spaces
carriage return,
new line,and
form feed.

The Data types


• The power of a programming language depends, among other things, on the range of
different types of data it can handle.
• Data values passed in a program may be of different types.

type() function: using this function get the data type of any object or variable.

Third Floor, BCIT, Tower 3-B (NON SEZ), Opposite to Leela Hotel Bhartiya City, Thanisandra Main Road, Kannuru, Bengaluru,
Karnataka-560064, India.
Python Variables: In programming, a variable is a container (storage area) to hold data.
For example,

number = 10

Here, number is the variable storing the value 10.


Rules for Python variables:
• A Python variable name must start with a letter or the underscore character.
• A Python variable name cannot start with a number.
• A Python variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ ).

Variable in Python names are case-sensitive (name, Name, and NAME are three different
variables).

The reserved words(keywords) in Python cannot be used to name the variable in Python.
Constants: Constants are the fixed values that remain unchanged during the execution of aprogram
and are used in assignment statements.

Keywords:
Every language contains words and a set of rules that would make a sentence meaningful. Similarly,
in Python programming language, there are a set of predefined words, called Keywords which along
with Identifiers will form meaningful sentences when used together. Python keywords cannot be used
as the names of variables, functions, and classes.

List of Keywords in Python


Keyword Description Keyword Description Keyword Description

Represents an
It is a Logical expression that It is a non-local
and False nonlocal
Operator will result in not variable
being true.

It is used to
It is used with It is a Logical
as create an alias finally not
exceptions Operator
name

It is used for It is used to create It is a Logical


assert for or
debugging Loop Operator

pass is used when


To import
Break out a the user doesn’t
break from specific parts of a pass
Loop want any code to
module
execute

Third Floor, BCIT, Tower 3-B (NON SEZ), Opposite to Leela Hotel Bhartiya City, Thanisandra Main Road, Kannuru, Bengaluru,
Karnataka-560064, India.
Keyword Description Keyword Description Keyword Description

It is used to raise is used to


It is used to
class global declare a global raise raise exceptions
define a class
variable or errors.

Skip the next To create a


return is used to
continue iteration of a if Conditional return
end the execution
loop Statement

It is used to Represents an
It is used to
def define the import True expression that
import a module
Function will result in true.

It is used to test if
It is used to Try is used to
del is two variables are try
delete an object handle errors
equal

While Loop is
Conditional To check if a
used to execute a
elif statements, same in value is present in while
block of
as else-if a Tuple, List, etc.
statements

It is used in a Used to create an with statement is


else conditional lambda anonymous with used in exception
statement function handling

try-except is yield keyword is


It represents a
except used to handle None yield used to create a
null value
these errors generator function

Sequence Data types


List: Lists are used to store multiple items in a single variable.
List Items
• List items are ordered, changeable, and allow duplicate values.
• List items are indexed, the first item has index [0], the second item has index
[1] etc.
Ordered:
• When we say that lists are ordered, it means that the items have a defined
order, and that orderwill not change.
• If you add new items to a list, the new items will be placed at the end of the
list.

Third Floor, BCIT, Tower 3-B (NON SEZ), Opposite to Leela Hotel Bhartiya City, Thanisandra Main Road, Kannuru, Bengaluru,
Karnataka-560064, India.
Changeable:
• The list is changeable, meaning that we can change, add, and remove items in
a list after it hasbeen created.
Allow Duplicates: Since lists are indexed, lists can have items with the same value.

List Length:
• To determine how many items a list has, use the len() function:
• A single list may contain DataTypes like Integers, Strings, as well as Objects.
Lists are mutable,and hence, they can be altered even after their creation.

Creating a List in Python:

Third Floor, BCIT, Tower 3-B (NON SEZ), Opposite to Leela Hotel Bhartiya City, Thanisandra Main Road, Kannuru, Bengaluru,
Karnataka-560064, India.
Positive and Negative indexing:

Python Tuple: A tuple in Python is similar to a list. The difference between the two is that we
cannot change the elements of a tuple once it is assigned whereas we can change the elements of a
list.

Third Floor, BCIT, Tower 3-B (NON SEZ), Opposite to Leela Hotel Bhartiya City, Thanisandra Main Road, Kannuru, Bengaluru,
Karnataka-560064, India.
Tuple methods:

Dictionary:

A Python dictionary is a collection of items that allows us to store data in key: value pairs.

Third Floor, BCIT, Tower 3-B (NON SEZ), Opposite to Leela Hotel Bhartiya City, Thanisandra Main Road, Kannuru, Bengaluru,
Karnataka-560064, India.
Third Floor, BCIT, Tower 3-B (NON SEZ), Opposite to Leela Hotel Bhartiya City, Thanisandra Main Road, Kannuru, Bengaluru,
Karnataka-560064, India.
Set: A Set in Python programming is an unordered collection data type that is iterable, mutable and
has no duplicate elements.
Set are represented by { } (values enclosed in curly braces)

Third Floor, BCIT, Tower 3-B (NON SEZ), Opposite to Leela Hotel Bhartiya City, Thanisandra Main Road, Kannuru, Bengaluru,
Karnataka-560064, India.
Python functions:
Python Functions is a block of statements that return the specific task. The idea is to
put somecommonly or repeatedly done tasks together and make a function so that
instead of writing the same code again and again for different inputs, we can do the
function calls to reuse code contained in it over and over again.
Some Benefits of Using Functions
• Increase Code Readability
• Increase Code Reusability

Third Floor, BCIT, Tower 3-B (NON SEZ), Opposite to Leela Hotel Bhartiya City, Thanisandra Main Road, Kannuru, Bengaluru,
Karnataka-560064, India.
Defining a Function in Python

Here are simple rules to define a function in Python.

o Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
o Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
o The first statement of a function can be an optional statement; the documentation string
ofthe function or docstring.
o The code block within every function starts with a colon (:) and is indented.
o The statement return [expression] exits a function, optionally passing back an
expressionto the caller. A return statement with no arguments is the same as return
None.

Ex:

Python module
A Python module is a Python file containing a set of functions and variables to be used in an
application. The variables can be of any type (arrays, dictionaries, objects, etc.)
Modules can be either:
1. Built in
2. User-defined.

1) User-defined Modules
Create a Module
To create a module, create a Python file with a .py extension.
Call a Module
Modules created with a .py extension can be used in another Python source file, using
the import statement.

Here’s an example of a simple module, myModule.py:


#myModule.py
def myFunction( parameter ): #define a function in myModule.py
print "Course : ", parameter
return

Third Floor, BCIT, Tower 3-B (NON SEZ), Opposite to Leela Hotel Bhartiya City, Thanisandra Main Road, Kannuru, Bengaluru,
Karnataka-560064, India.
To call this Python module myModule.py, create another Python file callModule.py file and use the
import statement.
import myModule.py:
myModule.myFunction(“Python Programming”)
When the Python interpreter encounters an import statement, it imports the module if it is present in
the search path.

A search path is a list of directories that the interpreter searches for importing a module.

2) Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.

Call a built-in Module


To call a built-in Module and use the function of that module write:
import moduleName #call a module
moduleName.function()#use module function

Ex:
import math
print("The value of cosine is", math.cos(3))
print("The value of sine is", math.sin(3))
print("The value of tangent is", math.tan(3))
print("The value of pi is", math.pi)

Benefits of modules in Python


There are a couple of key benefits of creating and using a module in Python:
Structured Code
• Code is logically organized by being grouped into one Python file which makes development
easier and less error-prone.
• Code is easier to understand and use.

Third Floor, BCIT, Tower 3-B (NON SEZ), Opposite to Leela Hotel Bhartiya City, Thanisandra Main Road, Kannuru, Bengaluru,
Karnataka-560064, India.
UNIT 2: EXCEPTION IN PYTHON
Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are problems in a
program due to which the program will stop the execution. On the other hand, exceptions are raised
when some internal events occur which change the normal flow of the program.

Different types of exceptions in python:


In Python, there are several built-in Python exceptions that can be raised when an error occurs
during the execution of a program. Here are some of the most common types of exceptions in
Python:

Built-in Python Exceptions

Here is the list of default Python exceptions with descriptions:

1. AssertionError: raised when the assert statement fails.


2. EOFError: raised when the input() function meets the end-of-file condition.

3. AttributeError: raised when the attribute assignment or reference fails.

4. TabError: raised when the indentations consist of inconsistent tabs or spaces.

5. ImportError: raised when importing the module fails.

6. IndexError: occurs when the index of a sequence is out of range

7. KeyboardInterrupt: raised when the user inputs interrupt keys (Ctrl + C or Delete).

8. RuntimeError: occurs when an error does not fall into any category.

9. NameError: raised when a variable is not found in the local or global scope.

10. MemoryError: raised when programs run out of memory.

11. ValueError: occurs when the operation or function receives an argument with the right
type but the wrong value.

12. ZeroDivisionError: raised when you divide a value or variable with zero.

13. SyntaxError: raised by the parser when the Python syntax is wrong.

14. IndentationError: occurs when there is a wrong indentation.

15. SystemError: raised when the interpreter detects an internal error.

Third Floor, BCIT, Tower 3-B (NON SEZ), Opposite to Leela Hotel Bhartiya City, Thanisandra Main Road, Kannuru, Bengaluru,
Karnataka-560064, India.
Table difference between errors and exceptions in python:
Errors Exceptions

Errors refer to syntax and logical Exceptions refer to runtime errors


errors in code that prevent it from that occur during program
running. execution.

Errors can be identified during the Exceptions are identified only


compilation phase or before the during the program execution
programexecution. phase when a specificstatement is
executed.

Examples of exceptions include


Examples of errors include syntax
IndexError,ValueError, KeyError,
errors, type errors or missing
andNameError etc.
dependencies.

Errors are typically fatal and prevent Exceptions allow the program to
the program from running whereas continue to run and provide an
exceptionscan be caught and handled opportunity for the programmer to
within the program. handle and recover from the error.

Third Floor, BCIT, Tower 3-B (NON SEZ), Opposite to Leela Hotel Bhartiya City, Thanisandra Main Road, Kannuru, Bengaluru,
Karnataka-560064, India.

You might also like