KEMBAR78
Py Text | PDF | Method (Computer Programming) | Control Flow
0% found this document useful (0 votes)
6 views38 pages

Py Text

Uploaded by

mamathabudarpu
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)
6 views38 pages

Py Text

Uploaded by

mamathabudarpu
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/ 38

Python Programming Language

Python is a computer language that’s easy to learn and use.


Python is popular because it’s simple and can be used for many different
things, making it a favourite choice for both beginners and experts.

History:

Late 1980s: Python was created by Guido van Rossum, a Dutch programmer, as
a hobby project.
1991: The first official version, Python 0.9.0, was released with features like
functions, exception handling and modules.
Inspiration: Python was designed to be simple and powerful, inspired by
languages like ABC, C, and Modula-3.
2000: Python 2 was released, adding new features and improving the language.
2008: Python 3 was launched, bringing major changes and improvements.
Today: Python is one of the most popular and widely used programming
languages globally.

Features:
Easy to learn: Python has a simple and clear syntax.
Readable Code: Code written in python is easy to read and understand.
Large Libraries: Comes with many built-in libraries and modules.
Cross-Platform: Works on various operating systems like windows, macOS, and
Linux.
Interpreted Language: Executes code line-by-line, which helps in debugging.
Community Support: Large community with plenty of resources and support.
Applications:
Web Development: Building websites and web applications.
Data Analysis: Analysing and visualizing data
Automation: Automating repetitive tasks and processes.
Artificial intelligence: Developing AI models and machine learning algorithms.
Game Development: Creating Games.
Scientific Computing: Performing complex calculations and simulations.
Software Development: Building software applications.

Compiler Interpreter
A compiler translates the entire An Interpreter translates and
source code of a program into executes the source code line by line.
machine code.

The compiled code is executed The source code is interpreted


directly by the computer’s hardware. directly, without producing an
intermediate executable file.

Faster execution. Slower execution.

All errors are reported after the Errors are reported and handled
entire code is analyzed. immediately as they encountered.

C, C++, Java (Compiled to bytecode, Python, JavaScript, Ruby, PHP.


which is then interpreted by JVM).

First Program (Hello World Program):


Comments:
Comments are used to explain the code and make it easier to understand. They
are ignored by the python interpreter and do not affect the flow of execution.
There are two types of comments:
Single-Line Comments: Begin with a # symbol.
Example:

Multi-Line Comments: Enclosed in triple single quotes or triple double quotes.


Example:

Variables:
A variable is like a container that holds data. You can store different types of
information in a variable, like numbers, text, or even more complex data.
Variables are essential because they allow you to store and work with data in
your programs.

Creating a Variable:
You give the variable a name and assign it a value using the = sign.
Example:
Assigning multiple values to multiple variables and assigning single value to
multiple variables in a single line:

Using Variables:
You can use the variable’s name to access its value later in your code.
Example:

Changing Values:
You can change the value of a variable by assigning a new value to it.
Example:

Literals:
Literals are the actual values that you assign to variables in python. They are
the fixed, constant data that you use directly in your code.

Identifier:
An identifier is a name used to identify a variable, function, class, module, or
other objects in a program. Identifiers are used to give meaningful names to
these elements so that you can reference them in your code.
Rules:
• Must start with a letter (a-z, A-Z) or an underscore (_).
• Can include numbers (0-9) after the first letter.
• Cannot use special characters.
• Cannot be a python keyword

Descriptive Names: Use descriptive names for identifiers to make your code
easier to understand. For example, use total_sum instead of just sum.
Consistent Naming Convention: Follow a consistent naming convention, like
using underscores for separating words in an identifier (my_variable) or using
camelCase (myVariable).

Keywords:
Keywords are special reserved words that have specific meanings and
purposes. You can’t use them as names for your variables, functions, or any
other identifiers because they are part of the python language syntax.
Fixed Meaning: Keywords have a fixed meaning that can’t be changed.
Case-Sensitive: Keywords must be written in lowercase, as python is case-
sensitive. For example, if is a keyword, but If or IF is not.
False None True and as
assert async await break class
continue def del elif else
except finally for from global
if import in is lambda
nonlocal not or pass raise
return try while with yield
These keywords are reserved, and you can’t use them as identifier in your
programs.

Data Type:
Data type defined the type of value a variable can hold, such as numbers, text,
or more complex structures like lists. Each data type determines the operations
that can be performed on the data and how it is stored in memory.

Python supports several built-in data types:

Numeric Types:

Integer (int): Represents whole numbers without a fractional part.


Examples: 2, -7, 67
Floating Point (float): Represents numbers with a decimal point.
Examples: 3.14, -0.002, 2.0
Complex Number (complex): Represents numbers with a real and an imaginary
part.
Examples: 3+4j,5-2j
Sequence Types:

String (str): Represents a sequence of characters. Strings are immutable.


Immutable means that once string is created, its individual elements
(characters) cannot be changed or modified.
Examples: "Python" or 'Python' (Enclosed in single or double quotes)
List (list): An ordered, mutable (it can be changed) collection of items. Lists can
contain elements of different types.
Examples: [1,2,3], ['a','b','c']
Tuple (tuple): An ordered, immutable collection of items. Tuples can also
contain elements of different types.
Examples: (1,2,3), ('a','b','c')

Boolean Type:

Boolean (bool): Represents Boolean values True and False. Useful for
conditional statements and logical operations.

Mapping Type:

Dictionary (dict): A collection of key-value pairs. Dictionaries are mutable. Keys


must be unique and immutable.
Example: {'name':'Python','rel_year':1991}

Set Types:

Set (set): An unordered collection of unique items. Sets are mutable.


Examples: {1,2,3}, {'a','b','c'}
Frozenset (frozenset): An immutable version of a set.
Examples: frozenset({1,2,3}), frozenset(['a','b','c'])

Type Conversion: Python allows conversion between different data types using
functions like int(), float(), str(), etc.
Example:
Type Checking: Use type() function to check the data type of a variable.
Example:

Expression:
An expression is a combination of operands (which can be values or variables)
and operators that evaluates to produce a result.

Example:
Operators:
Operators are symbols or keywords that you use to create expressions or
implement logic in your code.
Types of Operations in Python:
Arithmetic Operators: Perform Mathematical operations.
Example:

Assignment Operators: Assign values to variables.


Example:
Comparison Operators: Comparison operators are used to write conditions
that compare values. These operators return True or False based on
comparison.
Example:

Logical Operators: Combines multiple conditions.


Example:

Bitwise Operators: Perform operations on the binary representation of


integers.
Example:
Membership Operators: Check if a value is in a sequence.
Example:

Identity Operators: Compare the memory locations of two objects.


is – Returns True if both variables point to the same memory location.
is not – Returns True if both variables do not point to the same memory
location.
Example:

Ternary Operator: Used for conditional expressions.


Example:
Output and Input Functions:
print() function:
print function is used to display output in the console.
It can take multiple arguments, separated by commas, and will print them
separated by spaces.
Example:

F-String Method: Uses curly braces {} to embed expressions inside a string,


prefixed by f.
Example:

input() function:
The input() function is used to take input from the user. When you use this
function, the program pauses and waits for the user to type something and
press Enter. Whatever the user types is returned as a string.
Even if the user types a number, the input() function will still return it as a
string. If you need to work with the input as a different data type, like an
integer, you would need to convert it using functions like int(), float(), etc.
You can pass a string to the input() function, which will be displayed as a
prompt to the user.
Example:
Control Structures:
Control structures are used to make decisions, repeat actions, and manage the
flow of execution in your program.

Conditional Statements:
if statement:
An if statement is used to check a condition, and if the condition is true, it will
execute the associated block of code.

Indentation:
Before understanding the next statement, it's important to know about
indentation. Indentation is used to define a block of code in programming, such
as within loops, functions, and conditionals etc. It involves adding spaces or
tabs at the beginning of lines to group statements together. Indentation helps
to structure the code and indicate which statements belong to which block. If
there is no indentation in front of a statement, it signifies the end of the
current block and the beginning of a new one.
Indentation is not just for readability; it is a part of syntax. Incorrect
indentation will result in errors. Use the same number of spaces or tab spaces
for each level of indentation. It is common to use 4 spaces per indentation
level.

Example: if block

Indentation
if-else statement:
In this statement, when the condition related to the if block is false, the else
block will be executed.
Example:

elif Statement:
When we have two or more conditions to check, the elif statement is used to
handle additional conditions.
Example:
Nested if statement:
A nested if statement is an if statement inside another if statement. This allows
for more complex conditions to be evaluated in a hierarchical manner.
Example:

Loop Statements:
Loop statements allow you to execute a block of code multiple times.

for loop: Repeats a block of code a specific number of times.


Used for iterating over a sequence (like a list, tuple, dictionary, set, or string) or
other iterable objects.
Example:
range() Function:
The range() function is used to generate a sequence of numbers.
• range(stop)
• range(start, stop)
• range(start, stop, step)

while loop:
A while loop is used to repeat a block of code as long as a condition is true. It
checks the condition before each iteration and stops when the condition
becomes false.
Example:

Loop Control Statements:


Loop control statements are used to change the normal flow of loops. They
allow you to skip certain iterations or stop the loop early.
Python provides three loop control statements:
• break
• continue
• pass

break Statement:
The break statement is used to exit the loop immediately, even if the condition
is still true. It is commonly used to stop the loop when a certain condition is
met.
Example:

The loop stops when i becomes 3 due to the break statement.


continue Statement:
The continue statement is used to skip the current iteration and move to the
next one.
Example:

When i is 3, the continue statement skips that iteration, and the loop continues
with 4 and 5.

pass Statement:
The pass statement is a placeholder. It does nothing and is used when a
statement is syntactically required but you don’t want any code to run.
Example:

This loop runs 3 times but does nothing inside the loop.
pass is useful when you are planning to write the code later.

Functions:
Functions are blocks of code that are used to perform a specific task. Instead of
writing the same code multiple times, we can define a function once and call it
whenever needed.
Functions help to organize code, make it reusable, and improve readability.
There are two types of functions in Python:
• Built-in Functions: These are pre-defined functions provided by Python,
like print(), len(), type(), input() etc.
• User-defined Functions: These are functions created by the programmer
using the def keyword.

Defining a Function:
To create a function, use the def keyword, followed by the function name and
parentheses ().
Example:

Calling a Function:
To use the function, just call it by its name followed by parentheses.
Example:
Function with Parameters:
You can pass values (called arguments) to a function.
Example:

Function with Return Value:


A function can return a value using the return keyword.
Example:

Default Parameters:
You can provide default values for function parameters.
Example:
Lambda Function:
A lambda function is a small, anonymous function with no name. It can take
any number of arguments but only one expression.
Example:

Modules, Packages, and Libraries:


Python supports modular programming – breaking code into separate files
(modules), organizing them into packages, and collecting useful ones into
libraries.

Module:
A module is a single python file .py that contains functions, variables, classes,
or runnable code. Modules help you organize and reuse code.

Package:
A package is a folder (directory) that contains multiple python modules and a
special file called __init__.py.
The __init__.py file makes python treat the folder as a package.
It can also contain initialization code for the package.

Library:
A library is a collection of useful packages and modules grouped for a specific
purpose, like:
• Math operations
• Data science
• Web development
• Machine learning
You install a library (e.g., NumPy, Pandas) and use its modules in your code.

Math Module:
The math module provides built-in functions to perform mathematical
operations such as square roots, powers, trigonometry, logarithms, rounding,
and constants like π (pi) and e.
Before using any function from the math module, you must import it.
Example:

Strings:
A string is a sequence of characters enclosed in quotes. It is immutable, which
means once created, it cannot be changed.
You can use either single quotes, double quotes, or triple single quotes or triple
double quotes for multi-line strings.
Example:

Accessing Characters:
You can access individual characters using indexing.
Indexing starts at 0.
Example:

String Slicing:
You can extract parts of a string using slicing: string[start:end]

Method Description
lower() Converts string to lowercase
upper() Converts string to uppercase
title() Capitalizes first letter of each word
capitalize() Capitalizes only the first character
strip() Removes spaces from beginning and end
replace(old, new) Replaces part of string with another
find(sub) Returns index of first occurrence of substring
count(sub) Counts number of occurrences of a substring
startswith(sub) Returns True if string starts with the substring
endswith(sub) Returns True if string ends with the substring
split() Splits the string into a list
join() Joins list of strings into one string
isalpha() Returns True if all characters are alphabets
isdigit() Returns True if all characters are digits
isalnum() Returns True if all characters are alphanumeric
islower() Returns True if all characters are lowercase
isupper() Returns True if all characters are uppercase

Lists:
A list is an ordered, mutable (changeable) collection of items. It can hold
elements of different types like integers, strings, or even other lists.
Lists are defined using square brackets [ ].
Example:

Method Description
append() Adds an item to the end
insert() Inserts an item at a given position
remove() Removes the first occurrence of an item
pop() Removes item at the given index (default last)
sort() Sorts the list in ascending order
reverse() Reverses the list
clear() Removes all items
len() Returns the number of items in the list

Tuples:
A tuple is an ordered, immutable (unchangeable) collection of items.
Tuples are defined using parentheses ( ).
Example:

You cannot change values in a tuple once it is created.

Method Description
count() Returns the number of times a value appears
index() Returns the index of the first match

Dictionaries:
A dictionary is an unordered collection of key-value pairs. It is mutable and
allows quick access using keys.
Dictionaries are defined using curly braces {} with key-value pairs separated by
a colon : .
Example:
Method Description
keys() Returns a list of all keys
values() Returns a list of all values
items() Returns a list of key-value pairs
get() Returns the value for the given key
update() Updates the dictionary with key-value pairs
pop() Removes the item with the given key
clear() Removes all items

Arrays:
An array is a data structure that stores a collection of items of the same data
type. Arrays are similar to lists, but they are more efficient when working with
large amounts of numerical data.
Unlike lists, python does not have a built-in array data type, but it provides the
array module to work with arrays.
Use less memory than lists.
Faster in numerical operations.
All elements must be of the same data type.

Importing Array Module:


To use arrays, you most first import the array module.

Creating an Array:
Use the array.array() function with two arguments:
1. A type code (data type)
2. A list of elements
Example:

Method Description
append(x) Adds an item at the end
insert(i, x) Inserts x at position i
remove(x) Removes first occurrence of x
pop() Removes the last element
index(x) Returns the index of first occurrence of x
reverse() Reverses the array

NumPy (Numerical Python):


Numpy is a Python library used for high-performance numerical and scientific
computing. It adds support for large, multi-dimensional arrays and matrices,
along with many mathematical functions to operate on them.
Supports n-dimensional arrays.
Performs fast mathematical operations.
Uses less memory and executes faster than Python lists.
Backbone for other libraries like Pandas, Matplotlib, Scikit-learn, etc.

Installing NumPy:
pip install numpy (run this command in terminal or cmd).

Example:
Exception Handling:
An exception is an error that occurs during program execution. When an error
occurs, Python stops the program and shows an error message unless the error
is properly handled.
Exception handling allows your program to catch and handle errors gracefully
without crashing.

Exception Description
ZeroDivisionError Dividing by zero
TypeError Invalid type operation
ValueError Wrong value type
IndexError Invalid list/tuple index
KeyError Key not found in dictionary
FileNotFoundError File not found
Example:

Multiple except Blocks:


You can handle different errors separately.
Example:

else Block:
Code inside else run only if there is no exception.
Example:

finally Block:
The finally block always runs, whether an exception occurred or not. It is useful
for cleanup actions like closing a file.
Example:
raise Statement:
Use raise to create custom exceptions.
Example:

File Handling:
File handling is used to store and retrieve data from files on the disk. Python
provides built-in functions to open, read, write, and close files.
To permanently save data from a program.
To read data from existing files.

Operation Function / Method


Create a file open() with mode 'x', 'w', or 'a'
Read a file read(), readline(), readlines()
Write a file write(), writelines()
Append content write() in 'a' mode
Delete a file os.remove()
Close a file close() or use with statement

Create a File:
Method 1:

Method 2:

Write to a File:
Use ‘w’ mode to write new content (this will overwrite the file it exists).

Read from a File:


read() – Reads the full content
Example:

readline() – Reads one line at a time


Example:
readlines() – Reads all lines into a list
Example:

Append to a File:
Use ‘a’ mode to add content to the end of an existing file.
Example:

Delete a File:
Use the os module to delete a file safely.
Example:

Using with Statement:


The with statement automatically closes the file, even if an error occurs.
No need to call file.close() manually.
Example:

OOPS (Object Oriented Programming System):

Classes and Objects in Python


In Python, classes are blueprints for creating objects. They contain variables
(data) and methods (functions) that describe the behavior of objects.

1. Class Variables
Definition:
Class variables are shared across all objects of a class. They are defined inside
the class but outside all methods.
Example:

2. Instance Variables
Definition:
Instance variables are unique to each object. They are defined inside the
constructor (__init__) or other instance methods using self.
Example:

3. Constructor (__init__ method)


Definition:
The constructor is a special method named __init__. It runs automatically
when a new object is created and is used to initialize instance variables.
Example:

4. Instance Methods
Definition:
Instance methods work with instance variables. The first parameter is always
self.
Example:
5. Class Methods
Definition:
Class methods work with class variables. They use the decorator @classmethod
and the first parameter cls.
Example:

6. Static Methods
Definition:
Static methods do not use instance or class variables. They are independent
functions placed inside a class for logical grouping. Use the decorator
@staticmethod.
Example:
1. Encapsulation
Definition:
Encapsulation means wrapping the data (variables) and the methods
(functions) that work on the data into a single unit called a class.
It also provides control over how data is accessed and modified.
• Public members → Accessible everywhere.
• Protected members → Indicated by a single underscore (_variable).
Accessible but should not be modified directly.
• Private members → Indicated by double underscore (__variable). Not
directly accessible outside the class.

Example:

2. Inheritance
Definition:
Inheritance allows a class (child) to acquire the properties and behaviors of
another class (parent).
It creates a hierarchy where the child class can reuse, extend, or modify
features of the parent class.
Types in Python:
• Single inheritance → One child inherits from one parent
• Multiple inheritance → Child inherits from more than one parent
• Multilevel inheritance → A chain of inheritance
• Hierarchical inheritance → Multiple children from one parent
• Hybrid inheritance → Combination of the above

Example:

3. Polymorphism
Definition:
Polymorphism means “many forms.” It allows the same function or method
name to perform different tasks depending on the object that calls it.
Types:
• Method Overriding (Runtime polymorphism): Child class redefines a
method from parent class
• Built-in Polymorphism: Functions like len() work for strings, lists, and
tuples
Example:

4. Abstraction
Definition:
Abstraction means hiding implementation details and showing only the
necessary features of an object.
In Python, abstraction is implemented using abstract classes from the abc
module.
Example:

You might also like