python
python
1
Introduction to Computer
A computer is an electronic device, operating under the control of
instructions stored in its own memory that can accept data (input), process
the data according to specified rules, produce information (output), and
store the information for future use.
2
Functionalities Of A Computer
• Any digital computer carries out five functions in gross terms.
3
Introduction
At work, people use computers to analyze data, make presentations, conduct
business transactions, communicate with customers and coworkers, control
machines in manufacturing facilities and do many other things.
At home, people use computers for tasks such as paying bills, shopping
online, communicating with friends and family, and playing computer games.
4
Introduction
5
Relationship between computers
and programs
• A computer is a machine that can perform calculations and execute instructions by
processing data and following a set of instructions or programs.
• A program is a set of instructions written in a programming language that tells the
computer what to do. Programs can be used to construct applications.
• Computers can do such a wide variety of things because they can be programmed. This
means that computers are not designed to do just one job, but to do any job that their
programs tell them to do.
• A computer follows to perform a task.
• For example, Microsoft Word.
• Microsoft Word is a word processing program that allows you to create, edit, and print
documents with your computer.
6
Cont…
• programming languages are sets of instructions that humans use to communicate with computers. These
languages are designed to be easy for humans to read and write, while also being precise enough for
computers to understand and execute.
• Programs are commonly referred to as software.
• Software is set programs.
• Software is essential to a computer because it controls everything the computer does. All of the software
that we use to make our computers useful is created by individuals working as programmers or software
developers.
• A programmer, or software developer, is a person with the training and skills necessary to design, create,
and test computer programs.
• Computer programming is an exciting and rewarding career.
• Today, We will find programmers’ work used in business, medicine, government, law enforcement,
agriculture, academics, entertainment, and many other fields.
7
Components of Computer
8
Computer Components
Any kind of computers consists of
9
Hardware
• Computer hardware is the collection of physical elements that constitutes a computer
system.
• Computer hardware refers to the physical parts or components of a computer such as the
monitor, mouse, keyboard, computer data storage, hard drive disk (HDD), system
unit (graphic cards, sound cards, memory, motherboard and chips), etc. all of which
are physical objects that can be touched.
10
Input unit
• The input unit consists of input devices that are attached to the
computer. These devices take input and convert it into binary language
that the computer understands. Some of the common input devices are
keyboard, mouse, joystick, scanner etc.
• The Input Unit is formed by attaching one or more input devices to a
computer.
• A user input data and instructions through input devices such as a
keyboard, mouse, etc.
• The input unit is used to provide data to the processor for further
processing.
11
• Keyboard
• Mouse
• JoyStick
• Light pen
• Track Ball
• Scanner
• Graphic Tablet
12
Example of Input Devices:-
1. Keyboard 2. Mouse (pointing device) 3. Microphone
Note: The most common use keyboard is the QWERTY keyboard. Generally standard Keyboard has 104
keys.
13
Central Processing Unit (CPU)
• A CPU is brain of a computer. It is responsible for all functions and processes.
• Regarding computing power, the CPU is the most important element of a computer system.
14
Central Processing Unit (CPU)
The CPU is comprised of three main parts :
1. Arithmetic Logic Unit (ALU): Executes all arithmetic and logical operations. Arithmetic
calculations like as addition, subtraction, multiplication and division. Logical operation
like compare numbers, letters, or special characters
3. Registers :Stores the data that is to be executed next, "very fast storage area".
15
Primary Memory
• RAM: Random Access Memory (RAM) is a memory scheme within the computer
system responsible for storing data on a temporary basis, so that it can be promptly
accessed by the processor as and when needed.
• It is volatile in nature, which means that data will be erased once supply to the storage
device is turned off. RAM stores data randomly and the processor accesses these data
randomly from the RAM storage.
• RAM is considered "random access" because you can access any memory cell directly
if you know the row and column that intersect at that cell.
• ROM (Read Only Memory): ROM is a permanent form of storage. ROM stays active
regardless of whether power supply to it is turned on or off. ROM devices do not allow
data stored on them to be modified.
16
Secondary Memory
• Stores data and programs permanently: its retained after the power is turned off
• Hard drive (HD): A hard disk is part of a unit, often called a "disk drive," "hard drive," or "hard disk
drive," that store and provides relatively quick access to large amounts of data on an
electromagnetically charged surface or set of surfaces.
• Optical Disk: an optical disc drive (ODD) is a disk drive that uses laser light as part of the process of
reading or writing data to or from optical discs. Some drives can only read from discs, but recent
drives are commonly both readers and recorders, also called burners or writers. Compact discs,
DVDs, and Blu-ray discs are common types of optical media which can be read and recorded by
such drives. Optical drive is the generic name; drives are usually described as "CD" "DVD", or
"Bluray", followed by "drive", "writer", etc. There are three main types of optical media: CD, DVD,
and Blu-ray disc. CDs can store up to 700 megabytes (MB) of data and DVDs can store up to 8.4
GB of data. Blu-ray discs, which are the newest type of optical media, can store up to 50 GB of
data. This storage capacity is a clear advantage over the floppy disk storage media (a magnetic
media), which only has a capacity of 1.44 MB.
17
Secondary Memory
Flash Disk
A storage module made of flash memory chips. A Flash disks have no mechanical platters or access arms, but
the term "disk" is used because the data are accessed as if they were on a hard drive. The disk storage
structure is emulated.
18
Comparison between RAM and HARD DISK
19
Output Devices
An output device is any piece of computer hardware equipment used to communicate the
results of data processing carried out by an information processing system (such as a
computer) which converts the electronically generated information into human- readable
form.
20
Software
Software is a generic term for organized collections of computer data and
instructions, often broken into two major categories:
1. system software that provides the basic non- task-specific functions of the
computer, and
21
Software Types
System Application
software software
22
System software
System software is responsible for controlling, integrating, and managing the individual hardware
components of a computer system so that other software and the users of the system see it as a
functional unit without having to be concerned with the low-level details such as transferring data
from memory to disk, or rendering text onto a display.
Generally, system software consists of an operating system and some fundamental utilities such as
disk formatters, file managers, display managers, text editors, user authentication (login) and
management tools, and networking and device control software.
23
Application software
Application software is used to accomplish specific tasks other than just running the computer
system.
Application software may consist of a single program, such as an image viewer; a small collection
of programs (often called a software package) that work closely together to accomplish a task, such
as a spreadsheet or text processing system;
a larger collection (often called a software suite) of related but independent programs and packages
that have a common user interface or shared data format, such as Microsoft Office, which consists
of closely integrated word processor, spreadsheet, database, etc.;
24
Comparison Application Software and System Software
System Software Application Software
Interaction: Generally, users do not interact with system Users always interact with application software
software as it works in the background. while doing different activities.
Dependency: System software can run independently of Application software cannot run without the
the application software. presence of the system software.
25
Unit of Measurements
• Measurement refers to the comparison of an unknown quantity with a known quantity. The
result of a measurement is a numeric value with certain units. We can measure the length,
mass, capacity (volume), and temperature of any given object.
Measurement Unit Abbreviated
Centimeters Cm Measurement
Meters m Abbreviated
Unit
Kilometers km
Millimeters mm
Miles mi liters l
Yards yd milliliters ml
Feet/Foot ft kiloliters kl
Inches In fluid ounce fl oz
cup c
Milligrams mg pint pt
Grams g quart qt
Kilograms kg Gallon gal
Centigrams cg
Pounds lbs
Ounces oz Kelvin K
Tonnes t (used in the Metric system) Fahrenheit °F
26
Ton t (used in the Imperial system) Celsius °C
Cont…
• Storage measurements: The basic unit used in computer data storage is called a bit
(binary digit).
• Computers use these little bits, which are composed of ones and zeros, to do things
and talk to other computers.
• All your files, for instance, are kept in the computer as binary files and translated
into words and pictures by the software (which is also ones and zeros).
• This two number system, is called a “binary number system” since it has only two
numbers in it.
• The decimal number system in contrast has ten unique digits, zero through
nine.
27
Cont…
•Bit (1/0) Symbol Prefix SI meaning Binary repurposing
•Nibble (4 Bits) k kilo 103 = 10001 210 = 10241
•Byte (8 Bits) M mega 106 = 10002 220 = 10242
•Kilo Byte G giga 109 = 10003 230 = 10243
•Mega Byte
T tera 1012 = 10004 240 = 10244
•Giga Byte
P peta 1015 = 10005 250 = 10245
•Tera Byte
E exa 1018 = 10006 260 = 10246
•Peta Byte
•EXA Byte Z zetta 1021 = 10007 270 = 10247
•Zetta Byte Y yotta 1024 = 10008 280 = 10248
•Yotta Byte R ronna 1027 = 10009 290 = 10249
Q quetta 1030 = 100010 2100 = 102410
28
Binary Decimal (10) Binary (2) Hexadecimal
Binary Octal (8) (2) 0/1 0-9 0/1 (10)
(2) 0/1 0-7
8421 0-9
421
0000 0 0000 0
000 0
0001 1 0001 1
001 1
0010 2 0010 2
010 2
0011 3 0011 3
011 3 0100 4
0100 4
100 4 0101 5
0101 5
101 5 0110 6
0110 6
110 6 0111 7
0111 7
111 7 1000 8
1000 8
1001 9 1001 9
1010 A
1011 B
1100 C
1101 D
1110 E
29
1111 F
Binary to Octal Conversion
• (101101)2 = (?)8
72 44
31
Binary to Decimal Conversion 25
= 2*2*2*2*2 =32
= 32+0+8+0+2+0
=42
(101010)2 = (42)10
32
Python Programming Lang.
• Python was created by Guido van Rossum (Dutch programmer ) in 1991
(version 0.9.0).
• The language was named after the British comedy series "Monty Python's Flying
Circus".
• File format .py
33
Reasons to use Python / Features of Python
• Easy to use and Learn: Python has a simple and easy-to-understand syntax, unlike traditional languages like C,
C++, Java, etc., making it easy for beginners to learn.
• Expressive Language: It allows programmers to express complex concepts in just a few lines of code or reduces
Developer's Time.
• Interpreted Language: Python does not require compilation, allowing rapid development and testing. It uses
Interpreter instead of Compiler.
• Object-Oriented Language: It supports object-oriented programming, making writing reusable and modular code
easy.
• Open-Source Language: Python is open-source and free to use, distribute and modify.
• Extensible: Python can be extended with modules written in C, C++, or other languages.
• Learn Standard Library: Python's standard library contains many modules and functions that can be used for
various tasks, such as string manipulation, web programming, and more.
• GUI Programming Support: Python provides several GUI frameworks, such as Tkinter and PyQt, allowing
developers to create desktop applications easily.
• Integrated: Python can easily integrate with other languages and technologies, such as C/C++, Java, and . NET.
• Embeddable: Python code can be embedded into other applications as a scripting language.
• Dynamic Memory Allocation: Python automatically manages memory allocation, making it easier for developers
to write complex programs 34
Cont…
• Wide Range of Libraries and Frameworks: Python has a vast collection of libraries and frameworks,
such as NumPy, Pandas, Django, and Flask, that can be used to solve a wide range of problems.
• Versatility: Python is a universal language in various domains such as web development, machine
learning, data analysis, scientific computing, and more.
• Large Community: Python has a vast and active community of developers contributing to its development
and offering support. This makes it easy for beginners to get help and learn from experienced developers.
• Career Opportunities: Python is a highly popular language in the job market. Learning Python can open
up several career opportunities in data science, artificial intelligence, web development, and more.
• High Demand: With the growing demand for automation and digital transformation, the need for Python
developers is rising. Many industries seek skilled Python developers to help build their digital
infrastructure.
• Increased Productivity: Python has a simple syntax and powerful libraries that can help developers write
code faster and more efficiently. This can increase productivity and save time for developers and
organizations.
• Big Data and Machine Learning: Python has become the go-to language for big data and machine
learning. Python has become popular among data scientists and machine learning engineers with libraries
like NumPy, Pandas, Scikit-learn, TensorFlow, and more.
35
Applications of Python / Where is Python used?
• Data Science & Machine Learning,
• Artificial Intelligence,
• Computer Vision or Image Processing Applications,
• Gaming , IoT, Networking
• Desktop Applications, Console-based Applications, Mobile Applications, Software
Development
• Web Applications
• Enterprise Applications
• 3D CAD Applications,
• Speech Recognition, Scientific computing, Education, Testing,
• Finance, Audio and Music, Writing scripts
36
Python Popular Frameworks and Libraries
• Web development (Server-side) - Django Flask, Pyramid, CherryPy
• GUIs based applications - Tkinter, PyGTK, PyQt, PyJs, etc.
• Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
• Mathematics - NumPy, Pandas, etc.
• BeautifulSoup: a library for web scraping and parsing HTML and XML
• Requests: a library for making HTTP requests
• SQLAlchemy: a library for working with SQL databases
• Kivy: a framework for building multi-touch applications
• Pygame: a library for game development
• Pytest: a testing framework for Python Django
• REST framework: a toolkit for building RESTful APIs
• FastAPI: a modern, fast web framework for building APIs
• Streamlit: a library for building interactive web apps for machine learning and data science
• NLTK: a library for natural language processing
37
print() Function
• The print() function is used to display output to the console or terminal.
int main()
{
printf("Hello, World!\n"); // Print "Hello, World!" to the console
return 0; // Return 0 to indicate successful execution
}
39
Variable
• A variable is defined by assigning a value to a name using the = Operator.
• Syntax: variable_name = value
42
Cont…
• Mutable Data Types: Mutable objects can have their values or state modified after creation
• list: Lists are just like arrays, declared in other languages which is an ordered collection of data. It is very
flexible as the items in a list do not need to be of the same type.
• Ordered, Used for storing multiple values in a single variable.
• Lists can be created by just placing the sequence inside the square brackets [ ]
• Ex. my_list = [1, 2, 3]
• my_list.append(4) # Modifies the list
• dict: A dictionary is an unordered collection of data values, used to store data values like a map, unlike other
Data Types that hold only a single value as an element, a Dictionary holds a key: value pair. Key-value is
provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a
colon : , whereas each key is separated by a ‘comma’.
• It can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’. Values in
a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be
immutable. Dictionary keys are case sensitive.
• Ex. my_dict={"name":“Ram", "age":25}
43
Cont…
• set: It is an unordered collection of data types that is iterable, mutable, and has no duplicate elements. The
order of elements in a set is undefined though it may consist of various elements.
• It can be created by using the built-in set() function with an iterable object or a sequence by placing the
sequence inside curly braces {}, separated by a ‘comma’. The type of elements in a set need not be the
same, various mixed-up data type values can also be passed to the set.
• collection of unique elements. Ex. my_set = {1, 2,3}
• float: Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point.
• Numbers with a decimal point, Used for representing real numbers
• Ex. A=1.5
• complex: A complex number is represented by a complex class.
• It is specified as (real part) + (imaginary part)j
• Used for scientific computations.
Ex. my_complex = 2 + 3j # Real part: 2, Imaginary part: 3
45
Cont…
• tuple: it is Just like a list, a tuple is also an ordered collection of Python objects. The only difference
between a tuple and a list is that tuples are immutable i.e. tuples cannot be modified after it is created. It
is represented by a tuple class.
• ordered collection of items, Used for grouping multiple items.
• Tuples are created by placing a sequence of values separated by a ‘comma’ with or without the use of
parentheses for grouping the data sequence. Tuples can contain any number of elements and of any
datatype (like strings, integers, lists, etc.).
• Ex. my_tuple = (1, 2, 3)
• frozenset: version of a set, Used for immutable collections of unique items.
Ex. my_frozenset = frozenset([1, 2, 3])
• bool: Value True or False, Used for logical operations and conditions. Ex. my_bool = True
• bytes: sequence of bytes, Used binary data. Ex. my_bytes = b"Python"
• Nonetype: Represents the absence of a value, Used as a placeholder. Ex. my_none = None
• str: sequence of characters, Used for text data. Ex. my_str = “Ramdas"
• new_str = my_str.upper() # Creates a new string
46
String Operations
• Strings are sequences of characters enclosed in single ( ‘ ’ ) or double (““ ””) quotes, triple quotes (“““ ”””)
• Python provides a variety of operations to manipulate and interact with strings.
• Ex.
• string1 = ‘Ramdas‘
• string2 = “Ramdas”
• string3 = '''Triple
quoted string'''
• string4 = “““ Ramdas
Gore ”””
• String Length (len ( )): Get the length (number of characters) of a string.
Ex. length = len(“Ramdas") # Output: 6
49
String Methods
• lower () or upper(): Convert the string to lowercase or uppercase.
• s = “Ramdas“
• print(s.lower()) # Output: “ramdas”
• print(s.upper()) # Output: “RAMDAS”
50
Cont…
• strip(): Remove leading and trailing whitespaces
• s = " Ramdas Gore "
• print(s.strip()) # Output: "Ramdas Gore"
• find(): Find the index of the first occurrence of a substring. Returns -1 if not found.
• s = “Ramdas Gore“
• print(s.find(“Gore")) # Output: 7 (index where “Gore" starts) print(s.find(“NFSU")) #
Output: -1 (not found)
51
Cont…
• split(): Split the string into a list of substrings based on a delimiter (default is whitespace).
• s = “Ramdas Gore“
• print(s.split()) # Output: [‘Ramdas', ‘Gore']
• print(s.split(" ")) # Output: [‘Ramdas', ‘Gore']
• join(): Join a list of strings into a single string with a specified separator.
• words = [‘Ramdas', ‘Gore', ‘NFSU']
• print(" ".join(words)) # Output: “Ramdas Gore NFSU“
• startswith() and endswith(): Check if the string starts or ends with a specified substring.
• s = “Ramdas Gore“
• print(s.startswith(“Ramdas")) # Output: True
• print(s.endswith(“Gore")) # Output: True 52
Cont…
• isalpha(): Check if all characters in the string are alphabetic.
• s = “NFSU“
• print(s.isalpha()) # Output: True
• s = “NFSU123“
• print(s.isalpha()) # Output: False
• s = "12345“
• print(s.isdigit()) # Output: True
• s = "123a45“
• print(s.isdigit()) # Output: False 53
Cont…
• s = "Hello123“
• print(s.isalnum()) # Output: True
• s = "Hello 123“
• print(s.isalnum()) # Output: False (space is not allowed)
54
String Formatting
• Escape Sequences: Use backslash ( \ ) to include special characters in strings
• s = “Madhu said, \"Python is amazing\"“
• print(s) # Output: Madhu said, "Python is amazing"
55
Cont…
• f-string (formatting string):
• name = “Krrish”
• roll = 20
• print(f"Name: {name},A Roll :{roll}") #Output:"Name: Krrish, Roll : 20”
• format() Method:
• name = " Krrish”
• roll = 20
• print("Name: {}, Roll : {}".format(name, roll)) # Output: "Name: Krrish, Roll: 20”
• % formatting (Old Style):
• name = " Krrish "
• roll = 20
• print("Name: %s, Roll : %d" % (name, roll)) # Output: "Name: Krrish, Roll : 20" 56
Expression
• In mathematics, an expression is a written arrangement
of symbols following the context-dependent, syntactic conventions
of mathematical notation.
• Symbols can denote numbers, variables, operations, and functions.
• Other symbols include punctuation marks and brackets, used
for grouping where there is not a well-defined order of operations.
• Expressions are commonly distinguished from formulas: expressions are a
kind of mathematical object.
• An expression is a combination of operators and operands that is interpreted
to produce some other value.
• Ex.12 + 18
57
Constant Expressions
• These are the expressions that have constant values only.
• # Constant Expressions
• x = 12 + 18
• print(x)
58
Arithmetic Expressions
• An arithmetic expression is a combination of numeric values,
operators, and sometimes parenthesis.
• The result of this type of expression is also a numeric value. The
operators used in these expressions are arithmetic operators like
addition, subtraction, etc.
Operators Syntax Functioning
Operators Syntax Functioning
+ x+y Addition
// x // y Quotient
– x–y Subtraction
% x%y Remainder
* x*y Multiplication
** x ** y Exponentiation
/ x/y Division
59
# Arithmetic Expressions
Output:
A=20
B =10 print("Addition of Two Number =", C)
C=A+B Addition of Two Number = 30
D=A-B
E =A*B
F = A/B print("sub of Two Number =", D)
G = A%B sub of Two Number = 10
print("Addition of Two Number =", C)
print("sub of Two Number =", D) print("mul of Two Number =", E)
print("mul of Two Number =", E) mul of Two Number = 200
print("div of Two Number =", F)
print("mod =", G) print("div of Two Number =", F)
div of Two Number = 2.0
print("mod =", G)
mod = 0
60
Control Structure
• A control structure (or control statement) is a fundamental concept that determines the
flow of execution in a program.
• It enables the program to make decisions, repeat tasks, and control the sequence of
operations based on conditions.
• Control structures allow you to modify the behavior of the program during runtime.
61
62
Sequential
• Sequential statements are a set of statements whose execution process
happens in a sequence.
• The problem with sequential statements is that if the logic has broken in any
one of the lines, then the complete source code execution will break.
• Program:
a, b = 20, 10
c=a+b
print("The result of the subtraction is: ", c)
# Output: he result of the subtraction is: 30
63
Conditional/ Control Statements
• Conditional statements are used to guide a program's flow based on
certain conditions.
• The main conditional statements include "if," "elif" (short for "else
if"), and "else.“
• These statements allow to run different code blocks depending on
whether a specified condition is true or false.
64
if Statement
• The "if" statement stands as the most elementary decision-making construct.
• Its purpose is to determine the execution or omission of specific statements or a block of
statements based on a given condition.
• The "if" statement is employed to assess a condition.
• Should the condition prove to be true, the indented code block beneath the "if" statement is
executed.
• Conversely, if the condition is false, the code block is bypassed.
• Syntax
• if (Conditional expression):
Statement 1. # True
65
Program
x = 88
if x > 78:
print("x is greater than 78")
66
if else Statement
• The "if" statement, in isolation, signifies that upon the condition being true, a
designated block of statements will execute; conversely, if false, it will not.
• However, to introduce an alternative course of action in the event of a false
condition, the "else" statement can be coupled with the "if" statement, enabling
the execution of a distinct code block when the "if" condition is false.
Syntax
67
68
# Taking input from the user
else:
print("You are a minor.")
69
if-elif-else Statement
• The "if" statements are processed in a top-down manner.
• Upon encountering the first true condition, the corresponding "if" statement's associated code is
executed, and the subsequent conditions are disregarded.
• Should none of the conditions prove true, the concluding "else" statement is activated.
• The "elif" statement facilitates the sequential examination of multiple conditions.
• Should the condition following an "if" statement prove false, the subsequent "elif" statement is
appraised.
• In the event that its condition is true, the associated code block is executed, and any subsequent
"elif" or "else" statements are bypassed.
Syntax
if (condition):
Statement
elif (condition):
Statement . .
else:
statement 70
71
# Taking input from the user
score = int(input("Enter your score (0-100): "))
72
favorite_color = input("What's your favorite color? ").lower()
# Using an if statement to check the color
if favorite_color == "blue":
print("Blue is a calm and peaceful color.")
else:
print("That's an interesting choice!")
73
Thank you
74