0% found this document useful (0 votes)
2 views51 pages

Module 1 - Introduction To Python Programming

Uploaded by

akashbalraj143
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)
2 views51 pages

Module 1 - Introduction To Python Programming

Uploaded by

akashbalraj143
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

MODULE 1

Introduction to Python Programming

SREEJITH T
ASSISTANT PROFESSOR
DEPARTMENT OF PHYSICS
Programming Languages
Language
 A system of communication.

Computer Language
Means of communication used to communicate
between people and the computer.

Difference between natural language and computer language


 Natural language has a very large vocabulary whereas
computer languages mostly have a very limited vocabulary.
Department of Physics Govt. College Mananthavady
Classification of Computer Languages

Computer
Languages

Machine Assembly High Level


Language Language Language

Department of Physics Govt. College Mananthavady


Classification of Computer Languages
Machine Language Instruction Format
 Fundamental language understood by
computer. Opcode Operand
(Operation Code) (Address)
 Also known as Machine Code.
 Written as strings of binary 0’s and 1’s.
Instruction prepared in machine
 No translation program is required. language has 2 parts
 Not really easy to learn.  Operation Code: Specifies
operation to be performed.
 Operand: specifies address of
operand.

Department of Physics Govt. College Mananthavady


Classification of Computer Languages
Machine Language
Advantages Limitations
 Programs written in machine language  Machine dependent.
are very fast to execute as instructions  Difficult to program
written in Machine language
 Error prone.
Machine languages are directly
understood by CPU and no translation
program is required.

Department of Physics Govt. College Mananthavady


Classification of Computer Languages
Assembly Language
 To simplify the program writing process
used in machine language, the numeric
operation codes of Machine language
were substituted by letter
symbols(Mnemonics). Mnemonics
 Assembly language programs are It is any kind of mental trick we
typically made up of a series of use to help us remember.
instructions written using a combination
of mnemonic codes and operands For example: machine code of
111 can be interpreted as
The syntax of assembly language varies subtract but it is still easier for
depending on the specific machine us to remember it as SUB.
architecture it is being used with.
Department of Physics Govt. College Mananthavady
Classification of Computer Languages
Assembly Language
Assembler
The translator program that translates an assembly
code into machine code is called an Assembler.

Assembly Machine Language


Language Program Assembler Program
(Source Program) (Object Program)

Department of Physics Govt. College Mananthavady


Classification of Computer Languages
Assembly Language
Limitations of Assembly
Advantages of Assembly Language Language
over Machine Language • Machine dependent.
Easier to understand and use. • Knowledge of hardware required.
Easy to locate and correct errors.
Easier to modify. Machine and Assembly Languages
being machine dependent are
No worry about addresses. called as Low Level Languages
(LLL).

Department of Physics Govt. College Mananthavady


Classification of Computer Languages
High Level Language(HLL) Merits of HLL
• HLL are basically symbolic languages
that use English words and/or They are very easy to understand.
mathematical symbols rather than Programmer-friendly.
Mnemonic codes. Debugging is not very difficult.
• HLL are known as Problem Oriented Easy to maintenance and are thus
Languages. simple and manageable.
• Every instruction written in HLL is Easily run them on different
translated into machine language platforms..
instructions with the help of compiler Can port them from one location
or interpreter to another.
Java, C, C++, Python etc. are a
Easily interpret and combine as
few examples of HLL compared to the LLL
Department of Physics Govt. College Mananthavady
Classification of Computer Languages

Department of Physics Govt. College Mananthavady


Compiler and Interpreter
Compiler
The translator program that Machine
High Level
translates the instructions of HLL into Compiler
Language
Language Program
Machine Language is called Compiler. (Source Program)
Program
(Object Program)

Interpreter
An Interpreter is a type of translator
used for translating HLL into Machine Machine
Code. High Level
Language
Language Program Interpreter
It takes one statement of HLL and Program
(Source Program)
translates it into a Machine (Object Program)
instruction which is immediately
executed.
Department of Physics Govt. College Mananthavady
Introduction to Python language

 Python is a versatile, high-level programming language that is


widely used for a variety of applications, including web
development, data analysis, artificial intelligence, machine
learning, automation, and more.
 It was created by Guido van Rossum and first released in 1991.
 Python is known for its readability, simplicity, and an extensive
ecosystem of libraries and frameworks
Department of Physics Govt. College Mananthavady
Introduction to Python language
Key Features of Python:
[Link] to Learn and Use: Python's syntax is
straightforward, making it an excellent choice for beginners and
professionals alike.
[Link] Language: Python code is executed line by
line, making debugging easier.
[Link]-Platform: It runs on multiple operating systems
such as Windows, macOS, Linux, and more.
[Link] Libraries: Python has a vast standard library,
and there are numerous third-party libraries for specialized
tasks.
[Link] Source: Python is free to use, distribute, and modify,
with an active community supporting its development.
[Link] Typing: You don’t need to declare variable types
explicitly; they are inferred at runtime.
Department of Physics Govt. College Mananthavady
Introduction to Python language

Common Uses of Python:


•Web Development: Frameworks like
Django, Flask, and FastAPI.
•Data Science: Libraries like Pandas, NumPy,
and Matplotlib.
•Machine Learning and AI: Libraries like
TensorFlow, PyTorch, and Scikit-learn.
•Automation: Tools like Selenium and
automation scripts.
•Game Development: Libraries like
Pygame.
•Networking and Cybersecurity: Tools for
protocol analysis and penetration testing.

Department of Physics Govt. College Mananthavady


Python interpreter
Python is an interpreted language developed by Guido van Rossum in the year of 1991.
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 How interpreters function in Python?
programming terminology.
 It is an interpreted language because Python interpreter is written in C programming
it executes line-by-line instructions. language as we all know that C is considered as
This process is called Interpretation. mother of all programming languages, Python
interpreter called "CPython".
 For example Python, PHP, Ruby, and
JavaScript are interpreted languages.
Department of Physics Govt. College Mananthavady
Python interpreter
Difference between Compilers and Interpreters
Compiler Interpreter
It translates a program on a single run It executes a program line by line.

It is an Fast Process It is an Slow Process

It generates output in the form of .(exe) It does not generate any form of outputs.

It utilizes CPU more. It takes less utilization of CPU

It is maximum used in Programming and


It is used in Production environment
development environment.

C, C++, C# are the compiled languages Python, Ruby, PHP are the interpreted languages.

It takes lot of time to analyze the code structure It takes less time compared to compilers.

Department of Physics Govt. College Mananthavady


Script Mode And Interactive Mode
Python has two basic modes: script mode and interactive mode
Script Mode Interactive Mode
It is usually edited in a text editor and then run It can be edited in the same way as commands
as a batch process are typed in, which makes it more user-friendly.
The output that can be saved and reused The output that is displayed on the screen and
then disappears
It can be saved in a text file It cannot be saved, but the user can type
commands in an editor and save it as a script file
It is more suitable when there is a need to It is more suitable for one-time tasks or for
automate tasks or when the same task needs to exploring data.
be carried out several times.
It is a defined set of steps that need to be In this mode user can type in commands and see
followed in order for the computer to the results straight away.
understand and carry out the instructions
Department of Physics Govt. College Mananthavady
Python Variables and Data Types
Python Variables: Python Variables:
 Python variables are the reserved memory locations used to 1. Local variables - Python
store values with in a Python Program. Local Variables are defined
 A Python variable is created automatically when you assign a inside a function. We can
value to it. not access variable outside
 The equal sign (=) is used to assign values to variables. the function.
2. Global variables - Any
counter = 100 # Creates an integer variable
variable created outside a
miles = 1000.0 # Creates a floating point variable
function can be accessed
name = "Zara Ali“ # Creates a string variable
within any function and so
There are a certain rules while declaring a variable they have global scope
1. The variable name cannot start with a number. It can only start with a counter = 100
character or an underscore. _count = 100
2. Variables in python are case sensitive. name1 = "Zara"
3. They can only contain alpha-numeric characters and underscores. Name2 = "Nuha"
4. No special characters are allowed. Age = 20
5. Python reserved keywords cannot be used naming the variable. zara_salary = 100000
Python Data Types
The standard or built-in data types in Python:

 In Python, data types define the


kind of value a variable can hold.
They specify the type of data,
such as numbers, text, or more
complex structures, and
determine what operations can be
performed on that data.
 Python data types are classes and
variables are instances (objects) of
these classes
 A variables can store data of
different types.

Department of Physics Govt. College Mananthavady


Python Data Types
Why Are Data Types Important?
i. Data Representation: They help represent
various kinds of data, like numbers, text, or
logical values.
ii. Operations: Certain operations are only
valid for specific data types (e.g., addition
works on numbers but not on strings
without conversion).
iii. Error Prevention: Knowing the data type
helps avoid programming errors.
iv. Memory Management: Different types use
memory differently, and Python manages
memory efficiently based on the data type.

For example:
•A number can be added, subtracted, or multiplied.
•A string can be concatenated or sliced.
•A list can be iterated over or modified.
Python Data Types
Characteristics of Python Data Types
1. Dynamic Typing: Python is dynamically
typed, which means you don’t need to
declare the data type of a variable
explicitly. The interpreter infers it
automatically based on the assigned
value.
2. Strong Typing: Python is strongly typed,
meaning it doesn’t allow operations
between incompatible data types
without explicit conversion.

x = "10“
x = 10 # x is of type int
y=5
x = "Hello" # Now x is of type str
print(x + y) # Type Error: can only concatenate str (not "int") to str
Python Data Types
1. Primitive (Basic) Data Types
Primitive data types are the building blocks of
data in Python. They are simple and immutable
in nature.

a. Numeric Types
 int: Represents integers (whole numbers).
 Example: x=10
 float: Represents floating-point numbers
(numbers with decimal points).
 Example: y= 3.5
 complex: Represents complex numbers with a
real and imaginary part.
 Example: z= 2+3j

Department of Physics Govt. College Mananthavady


Python Data Types
1. Primitive (Basic) Data Types

b. Text Type
 str: Represents a sequence of characters
(strings)
 Example: name = “ Alice”
c. Boolean Type
 bool: Represents logical values: True or False.
•Example: is_active = True

d. Special Type
 NoneType: Represents the absence of a value
or a null value.
•Example: value = None
Department of Physics Govt. College Mananthavady
Python Data Types
2. Non-Primitive (Complex) Data Types
Non-primitive data types are more complex and
can store multiple values or structured data.

a. Sequence Types
 list: An ordered, mutable collection of items.
•Example: fruits = ["apple", "banana",
"cherry"]
 tuple: An ordered, immutable collection of items.
•Example: coordinates = (10, 20, 30)
 range: Represents an immutable sequence of
numbers.
•Example: numbers = range(5) # Produces
0, 1, 2, 3, 4
Department of Physics Govt. College Mananthavady
Python Data Types
2. Non-Primitive (Complex) Data Types
b. Set Types
 set: An unordered collection of unique items.
•Example: unique_numbers = {1, 2, 3}
 frozenset: An immutable version of a set.
•Example: immutable_set = frozenset
({1, 2, 3})

c. Mapping Type
 dict: A collection of key-value pairs.
Example: person = {"name": "Alice", "age": 25}

Department of Physics Govt. College Mananthavady


Python Data Types
2. Non-Primitive (Complex) Data Types

d. Binary Types
 bytes: An immutable sequence of bytes.
 Example: data = b"hello"
 bytearray: A mutable sequence of bytes.
 Example: mutable_data = bytearray
(b"hello")
 memoryview: A view object that exposes the
memory of a byte-oriented object without
copying it.
 Example: mv = memoryview(b"hello")

Department of Physics Govt. College Mananthavady


Python Data Types
2. Classification Based on Mutability

a. Mutable Data Types (can be changed


after creation):
 list, dict, set and bytearray
b. Immutable Data Types (cannot be
changed after creation):

 int, float, complex, str, nontype, tuple,


frozenset and bytes

Department of Physics Govt. College Mananthavady


Python Data Types
a. Mutable Data Types (can be changed
after creation):
 list, dict, set and btyearray
b. Immutable Data Types (cannot be
changed after creation):

 int, float, complex, str, nontype, tuple,


frozenset and bytes

Department of Physics Govt. College Mananthavady


Python Operators and Operands
 In Python, operators are special symbols or
keywords that perform operations on
operands (the values or variables they act Types of Operators in Python
upon) 1) Arithmetic Operators
 Operands are the data or variables that the 2) Comparison Operators
operators act upon. For example, in 5 + 3, 3) Assignment Operators
the numbers 5 and 3 are operands, and + is 4) Logical Operators
the operator. 5) bitwise Operators
6) Identity Operators
7) Membership Operator

Department of Physics Govt. College Mananthavady


Python Operators
Python Arithmetic operators
are used to perform basic
mathematical operations like
addition, subtraction,
multiplication, division etc.

Department of Physics Govt. College Mananthavady


Python Operators
Comparison operators are
used for comparing the
values. It either returns True
or False according to the
condition. These operators
are also known as Relation
Operators.

Department of Physics Govt. College Mananthavady


Python Data Types
3. Assignment Operators
Used to assign values to variables.

In Python, assignment
operators are used to assign
values to variables. They
include basic assignment (=) as
well as compound operators
for performing an operation
and assignment in a single step
( +=.*=, **=)

Department of Physics Govt. College Mananthavady


Python Operators

 In Python, logical operators


are used to combine
conditional statements.
 They evaluate expressions
and return a Boolean value
(True or False). Python has
three logical operators:

Department of Physics Govt. College Mananthavady


Python Data Types
5. Bitwise Operators  In Python, bitwise operators are
used to perform bitwise
Operate on binary representations of numbers.
calculations on integers.
 The integers are first converted
into binary and then operations
are performed on each bit or
corresponding pair of bits, hence
the name bitwise operators.
 The result is then returned in
decimal format.

Department of Physics Govt. College Mananthavady


Python Data Types
6. Identity Operators
Test if two objects share the same memory location.  Identity operators in Python are
used to compare the memory
locations of two objects.
 The two identity operators are is
and is not.
 The is operator returns True if both
objects are the same object in
memory, while the is not operator
returns True if both objects are not
the same object in memory

Department of Physics Govt. College Mananthavady


Python Operators
7. Membership Operators
 Python offers two membership
Test if a value is in a sequence (e.g., list, tuple, string). operators to check or validate
the membership of a value.
 It tests for membership in a
sequence, such as strings, lists,
or tuples.
 in operator: The ‘in’ operator is
used to check if a character/
substring/ element exists in a
sequence or not.
 Evaluate to True if it finds the
specified element in a sequence
otherwise False.

Department of Physics Govt. College Mananthavady


Expressions and Statements in Python
Expression:
An expression is any piece of code that produces a
value. It can consist of values, variables, operators, and
function calls. Expressions are evaluated to compute a result.

Statement:
A statement is a unit of code that performs an action.
It may include expressions, but its main purpose is to execute
something. Statements do not produce a value directly.

Department of Physics Govt. College Mananthavady


c = a / b
Expressions and Statements in Python
Expression:
Constant expression
Arithmetic expression.
Integral expression
Floating expression
Relational expression
Logical expression
Bitwise expression
Combinational expression

Department of Physics Govt. College Mananthavady


Expressions and Statements in Python
Expressions in Python :
1. Constant expression: An expression that contains
only constant values
2. Arithmetic expression: An expression that
contains a combination of operators, operands, and
sometimes parenthesis
3. Integral expression: This is used for
computations and type conversion (integer to float,
a string to integer, etc.). It always produces a
integer number as a resultant. .
4. Floating expression: An expression is used for
computations and type conversion (integer to float,
a string to integer, etc.). A floating expression
always produces a floating-point number as a
resultant.

Department of Physics Govt. College Mananthavady


Expressions and Statements in Python
Expressions in Python:
5. Relational expression: An expression can be
considered as a combination of two or more
arithmetic expressions joined using relational
operators.
6. Logical expression: It performs the logical
computation and the overall expression results
in either True or False (Boolean result).
7. Bitwise expression: The expression in which
the operation or computation is performed at .
the bit level.
8. Combination expression: This can contain
a single or multiple expressions which
result in an integer or Boolean value
depending upon the expressions involved
Department of Physics Govt. College Mananthavady
Expressions and Statements in Python
Types of Statements:
1. Assignment statement: Assigns a value to a variable.

2. Control statements: Control the flow of execution.

3. Function definition: Defines a reusable block of code.

4. Import statement: Imports modules.

Department of Physics Govt. College Mananthavady


Precedence of Operators in Python
In Python, operator precedence determines the order in which operations are evaluated in
an expression. Operators with higher precedence are evaluated before those with lower
precedence.

Department of Physics Govt. College Mananthavady


Output and Input in Python
In Python, input and output are handled using built-in functions, and you can include comments
in your code to explain your logic or document its purpose.
Output: print()
The print() function is used to display output to the console.
We can use the print() function to print single and multiple. We can print multiple
variables by separating them with commas and using operator + sign.

Syntax print(*objects, sep=' ', end='\n', file=[Link], flush=False)


Parameters:
 *objects: Values to be printed, separated by commas.
 sep: Separator between objects (default is a space) - optional.
 end: What to print at the end (default is a newline) - optional.
 file: Output stream (default is [Link] or screen) - optional.
 flush: Whether to forcibly flush the stream (default is False)- optional.
Department of Physics Govt. College Mananthavady
Output and Input in Python
Examples Concatenated Strings:
We can also join two strings together inside
# Basic print
the print() statement.
print("Hello, World!")
For example: print('Program is ' + 'awesome.')
# Printing multiple objects
print("Name:", "Alice", "Age:", 25)

# Customizing separators and ending


print("Python", "is", "fun", sep="-", end="!\n")

# Using formatted strings


name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

Department of Physics Govt. College Mananthavady


Output and Input in Python
Input: input()
Python's input() function is used to take input from the user. The data entered by the user is
always stored as a string, so it may need conversion if another data type is required.

Syntax:

variable = input (prompt)

 The prompt is a string that displays a message to the user.


 The input is returned as a string, so you may need to convert it to another type.

Department of Physics Govt. College Mananthavady


Output and Input in Python
Input: input()
Examples
# Taking a string input
name = input("Enter your name: ")
print("Hello, " + name)

# Taking an integer input


age = int(input("Enter your age: "))
print(f"You are {age} years old.")

# Taking multiple inputs


x, y = map(int, input("Enter two numbers separated by space: ").split())
print(f"Sum of the numbers is {x + y}")

Department of Physics Govt. College Mananthavady


Comments in python
Comments in Python are the lines in the code that are
ignored by the interpreter during the execution of the
program.
 Comments can be used to explain Python code.
 Comments enhance the readability of the code.
 Single-line comments start with a # and extend to the
#This is a comment
end of the line print("Hello, World!")

 Comments can be placed at the end of a line, and


Python will ignore the rest of the line print("Hello, World!") #This is a comment

 It can also be used to prevent Python from executing #print("Hello, World!")


print("Cheers, Mate!")
code:
Department of Physics Govt. College Mananthavady
Comments in python
Multi-Line Comments
Python does not provide the option for multiline
comment However, there are different ways through
which we can write multiline comments.
(i) Multiline comments using multiple hashtags (#)
#This is a comment
We can multiple hashtags (#) to write multiline #written in
comments in Python. Each and every line will be #more than just one line
considered as a single-line comment. print("Hello, World!")

(ii) Using String Literals as Comment


Python ignores the string literals that are not assigned """ Python program to demonstrate
to a variable. So, we can use these string literals as multiline comments"""
print("Multiline comments")
Python Comments

Department of Physics Govt. College Mananthavady


File Handling in Python:
File input/output (I/O) in Python is done using the built-in open() function, which
allows you to work with files in different modes such as reading, writing, or
appending.

Open a file:
 Open() function will open a file ( No need to import anything)
 Open function return an object which is used to work files.
 The types of operations we can perform in file are controlled by access modes. These
modes also specify where the files handler

Syntax: file = open("file_name.txt", “mode”)

Department of Physics Govt. College Mananthavady


File input/ output in Python
Access Modes for using files: Access modes here are used to open a file in that
particular mode and then access with the specified mode
[Link] Only (‘r): Opening a file for only reading, and a file pointer positioned at the beginning of the file.
If the file selected does not exist, it returns an error.
[Link] and Write (‘r+’): Opening a file for reading and writing, the file pointer is positioned at the
beginning of the file. If the file selected does not exist, it returns an error.
[Link] Only (‘w’): Opening the file for writing content to the file, the file pointer position at the beginning
of the file. If the file selected does not exist, it returns an error.
[Link] and Read (‘w+’): Opening a file for reading and writing, the file pointer is positioned at the
beginning of the file.
[Link] Only (‘a’): Opening the file for writing, the file pointer is positioned at the end of the file. If the
file selected does not exist, it creates a file and uses it.
[Link] and Read(‘a+’): Opening the file for reading and writing, the file pointer is positioned at the
end of the file. If the file selected does not exist, it creates a file and uses it.
[Link] (‘b’): Opening the file in binary mode.
Department of Physics Govt. College Mananthavady
File input/ output in Python
read() method
f=open('[Link]','r')
[Link](9)
[Link]()

write() method:
f=open("[Link]","w")
[Link](("Monty Python's Flying Circus”)
[Link]()

Department of Physics Govt. College Mananthavady

You might also like