0% found this document useful (0 votes)
6 views30 pages

Unit-3 Python Theory

A program is a set of instructions for a computer to perform specific tasks, communicated through programming languages that vary in abstraction levels. Python is highlighted for its versatility in applications, data types, and control structures, including conditionals and loops. The document also covers functions, operators, and the installation and usage of Python, providing a comprehensive overview for beginners.

Uploaded by

rushiln3391
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 views30 pages

Unit-3 Python Theory

A program is a set of instructions for a computer to perform specific tasks, communicated through programming languages that vary in abstraction levels. Python is highlighted for its versatility in applications, data types, and control structures, including conditionals and loops. The document also covers functions, operators, and the installation and usage of Python, providing a comprehensive overview for beginners.

Uploaded by

rushiln3391
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

Unit-3

What is a program
A program is a set of instructions that a computer follow to perform a specific task.
For Example:
 Adding two numbers
 Computing mean and variance of a distribution
 Recommending movies to watch that you might be interested in.
 Coming up with best route on a map between two locations.
 programming language is used to communicate instructions to a computer.

Languages:
 Low level: Machine code, Assembly
 Middle level: C
 High level: C++, Python, Java, etc
 Low level languages are closer to hardware and we have more control over
them, but they are less human readable.

Compiler Vs Interpreter:
A compiler translates an entire high-level program into machine code before execution,
producing an executable file. Ex, C, C++, Java etc.
An interpreter translates and executes the code line by line during runtime, without
generating an executable file. Ex, Python, JavaScript etc.

Installing python
Visit [Link]/downloads and download the version you want to use. For example,
python 3.13.5 (major, minor, patch)
Install the executable file and be sure to tick “Add python to PATH”.
To check installation, write “python --version” in terminal.

Where to write python program


In a text editor like Visual Studio Code, Atom, Sublime, etc
In an Integrated development environment (IDE) like pycharm, spyder, etc
In Jupyter Notebook (pip install jupyter notebook)
On online services like google colab or Kaggle notebooks.
Introduction of computer application By: Manisha Pandya, Harsh Sharma
Note that python file has “.py” as extension, but python notebooks has “.ipynb” as
extension.

Applications of python
Python can do almost anything that you can think of.
AI, Machine Learning, Deep Learning,Game Development (pygame),
Visualization (Matplotlib, seaborn),Web Development (Flask, Django, pyscript)
Dashboards for data visualization (plotly),GUI application (Tkinter)
And much more.

Constants
A constant is a named value that is intended to remain unchanged throughout the
execution of a program.
Constants are typically defined using all uppercase letters, with words separated by
underscores, For Example, PI, MAX_LIMIT, etc.
Note that python does not enforce immutability for constants!

Variables
A variable is a named place in the memory where a programmer can store data and later
retrieve the data using the variable’s name.
You get to choose a variable’s name, For Example, speed, x_position, model, etc.
As the name suggests, the value of a variable can change throughout the execution of the
program
Variable name must start with letter or underscore. It can contain numbers after 1st letter
or underscore. Variable names are case sensitive.
Reserved Words
If we use reserved words, we must use them to mean the thing python expects them to
mean.

Introduction of computer application By: Manisha Pandya, Harsh Sharma


Python Data Types
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:

Introduction of computer application By: Manisha Pandya, Harsh Sharma


Numeric Types

Numeric types are used to store numerical values.

 int (Integers): Represents whole numbers, positive or negative, without a fractional part. Examples
include 5, -10, and 1000.
 float (Floating-Point Numbers): Represents numbers with a decimal point or in exponential form.
Examples include 3.14, -0.01, and 2.5e2.
 complex (Complex Numbers): Represents numbers with a real and an imaginary part, written as x
+ yj, where x is the real part and y is the imaginary part. For example, 3 + 5j.

Text Type

 str (Strings): Used to store sequences of characters. Strings are immutable, meaning they cannot be
changed after creation. They are defined using single quotes ('...'), double quotes ("..."), or
triple quotes ('''...''' or """...""") for multi-line strings. Examples include 'hello world'
and "Python is fun".

Sequence Types

Sequence types are ordered collections of items.

 list (Lists): An ordered and mutable collection of items. Lists can contain items of different data
types. They are defined using square brackets [ ]. Examples include [1, 2, 3] and ['apple',
'banana', 'cherry'].
 range (Ranges): An immutable sequence of numbers, often used in loops. It's an efficient way to
represent a sequence of integers. For example, range(5) represents the sequence 0, 1, 2, 3, 4.

Introduction of computer application By: Manisha Pandya, Harsh Sharma


Mapping Type

 dict (Dictionaries): An unordered and mutable collection of key-value pairs. Dictionaries are
defined using curly braces { } and are highly optimized for retrieving values based on their
associated keys. Example: {'name': 'Alice', 'age': 30}.

Boolean Type

 bool (Booleans): Represents one of two values: True or False. Booleans are used for logical
operations and conditional statements.

I cannot directly process or interact with PDF files, as I am a text-based AI. Therefore, I cannot provide an
example of "operators in Python" in a PDF format. However, I can still provide a comprehensive
explanation of Python operators with clear code examples.

Operators in Python

Arithmetic Operators

These operators perform basic mathematical operations.

 + (Addition): Adds two operands.

Python
a = 10
b=5
result = a + b
print(result) # Output: 15

 - (Subtraction): Subtracts the right operand from the left.

Python
result = a - b
print(result) # Output: 5

 * (Multiplication): Multiplies two operands.

Python
result = a * b
print(result) # Output: 50

 / (Division): Divides the left operand by the right, always returning a float.

Python
result = a / b
print(result) # Output: 2.0

 // (Floor Division): Divides and rounds down to the nearest whole number.
Introduction of computer application By: Manisha Pandya, Harsh Sharma
Python
result = 11 // 3
print(result) # Output: 3

 % (Modulus): Returns the remainder of the division.

Python
result = 11 % 3
print(result) # Output: 2

 ** (Exponentiation): Raises the left operand to the power of the right.

Python
result = 2 ** 3
print(result) # Output: 8

Comparison Operators

These operators compare two values and return a Boolean value (True or False).

 == (Equal to): Checks if two operands are equal.

Python
print(5 == 5) # Output: True

 != (Not equal to): Checks if two operands are not equal.

Python
print(5 != 3) # Output: True

 > (Greater than): Checks if the left operand is greater than the right.

Python
print(7 > 5) # Output: True

 < (Less than): Checks if the left operand is less than the right.

Python
print(7 < 5) # Output: False

Logical Operators

These operators combine conditional statements and return a Boolean result.

 and: Returns True if both statements are True.

Introduction of computer application By: Manisha Pandya, Harsh Sharma


Python
x = 15
print(x > 10 and x < 20) # Output: True

 or: Returns True if at least one of the statements is True.

Python
x=5
print(x > 10 or x < 7) # Output: True

 not: Reverses the logical state of the operand.

Python
is_sunny = False
print(not is_sunny) # Output: True

Membership Operators

These operators test if a value is a member of a sequence (like a string, list, or tuple).

 in: Returns True if the value is found in the sequence.

Python
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # Output: True

 not in: Returns True if the value is not found in the sequence.

Python
print("grape" not in fruits) # Output: True
Comments in python:

# This is a comment, python will ignore it.

# You comment a code line by adding "#" in front of it.

"""

This is a

multiline [Link] will ignore it too.

Whatever you write inside Triple quotes


will become a comment.

"""
x = 5 # creating a variable 'x' with value 5 print(x)

# OUTPUT:
Introduction
>>> 5 of computer application By: Manisha Pandya, Harsh Sharma
Data Types:

You can use typefunction to know the type of any variable.

a = 4

b = 3.1

c = "43"

d = True

e = None

print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))

#OUTPUT

>>> <class 'int'>

<class 'float'>

Ignore classfrom output, just focus on whatever is after class.

Type conversions:

You can use str, int, float, boolfunctions to convert some input datatype to another
datatype.
a = "45"

b = 32

# we can't add them directly, since it'll give


error # so we first need to convert "45" to 45.

integer_a = int(a)
addition = integer_a + b
print(addition)

# OUTPUT

>>> 77

But remember that these functions need appropriate input, else they'll give error.

Introduction of computer application By: Manisha Pandya, Harsh Sharma


integer_a = int(a) # can't convert "rohit" to some number

addition = integer_a + b

print(addition)
# OUTPUT

>>> ERROR

Input function:

Input function makes it possible for the program to receive user input and store it
into a variable. Note that irrespective of what you input, the value stored in variable
is a string.
You can give any prompt/text to the function and it'll be displayed to the user, like in
the below example, Enter your name:will be displayed to the user, so the user will
know they need to enter their name and not something else.

name = input("Enter your name:")


print(name, type(name))

# OUTPUT

>>> {whatever name you gave} <class 'str'>

Conditionals with if:

You can use ifkeyword to let python know that we are going to provide a condition
that python needs to check. if the condition is True, then python will execute
whatever is written under the if block, else it'll skip it.
ifblock is defined by an indentation (space in front of the code, usually 4 space width
wide). if you don't provide indentation, python will throw an error.

Introduction of computer application By: Manisha Pandya, Harsh Sharma


x = 5

if x == 5:

print("x is 5")
if x > 3:

print("x is greater than 3")


if x <= 7:

print("x is less than or equal to 7")


if x != 17:

print("x is not 17")


if x < 0:

print("x is negative")
print("continuing")

if x > 0:
print("x is positive")

print("x is greater than 0")

# OUTPUT : >>> x is 5

x is greater than 3

x is less than or equal to 7


x is not 17

continuing
x is positive

Introduction of computer application By: Manisha Pandya, Harsh Sharma


Nested decisions:

We can nest decisions with arbitrary depth which gives the program ability to make
complex decisions. Nested decisions is basically if conditions within if conditions.
x = -32

if x < 0:

print("x is negative")
if x < -20:

print("x is less than -20")


print("Done")

# OUTPUT

>>> x is negative

x is less than -20 Done

Two way conditions:

You can use if-elseto make a two way conditional statement. python will execute one of
the block which is True for it and it'll skip the other.
x = -50

if x > 0:

print("positive")
else:

print("negative")
# OUTPUT

>>> negative

Multi way conditions:

You can use elifto introduce multiple in between conditions. Remember python will
execute only one of these blocks and skip rest.
Python will start evaluating conditions from top and go on till bottom and whichever
block condition is True, python will execute it and rest will be skipped.

Introduction of computer application By: Manisha Pandya, Harsh Sharma


x = -40

if x > 0:

print("positive")

elif x < 0: # you can have more than one elif block if you want
print("negative")

else: # you can skip else if you want


print("0")

# OUTPUT
Multiple conditions with logical operators:

We can use logical operators to combine multiple conditions and make it complex. For
example, if passing score in maths is 60 and in economics it's 65, we can check if a
student passed, partially passed or failed in both subjects like this using and operator:

subject1 = "Maths"

subject2 = "economics" marks =


62

if marks < 60:

print("failed in both")

elif (marks >= 60) and (marks < 65):

print("failed in economics but passed in maths")


else:

print("passed in both")

# OUTPUT

>>> failed in economics but passed in maths

Here is the table for when the combination will be True:

condition 1 condition 2 andresult orresult


False False False False
False True False True
True False False True

Introduction of computer application By: Manisha Pandya, Harsh Sharma


True True True True

Loops

range function in python:

range function is usually used with for loops to provide a sequence of numbers.

rangefunction takes three inputs, but in our case, we will provide only one input, which
is the sequence ending number.

for i in range(5): print(i)

# OUTPUT:

>>> 0

Notice that the sequence always starts with 0 and ends with whatever number you input
- 1. so in this case, the sequence ends with 5-1 = 4.
While Loop
A while loop in Python is used to repeatedly execute a block of code as long as a condition is true.

Example:

count = 1
while count <= 5:
print("Count is:", count)
count += 1

Match Case
The match-case statement (introduced in Python 3.10) is similar to a switch-case in other languages. It allows
pattern matching and makes code more readable.

Example:

choice = 2

match choice:
case 1:
print("You selected option 1")
case 2:
print("You selected option 2")
case 3:
Introduction of computer application By: Manisha Pandya, Harsh Sharma
print("You selected option 3")
case _:
print("Invalid choice")

Introduction of computer application By: Manisha Pandya, Harsh Sharma


Functions

What are functions?

A functionis a piece of code that can be stored, just like we can store some value in
a variable. This means that whenever required, we can use this stored piece of code
and that too however many times we want.
Let's say you write same piece of code (For Example, to sum 5 numbers) at 10 places
in your file. Since you need to write the same code 10 times, there is a high chance
that you'll introduce some bug in one of them by spelling mistake or some other way.
Contrary to this, you can store the piece of code in a function and write it only once,
and use it 10 times.
There are two types of functions in python:
Built-in functions: These are already defined in python and are ready to use,
like print, input, type, int, float, etc.
user defined functions: These needs to be defined by the user before they can
use them.

Making a function:

def print_something(): print("Something")

print_something()
print("hello")

print_something()

# OUTPUT:

>>> Something
hello

Something

Introduction of computer application By: Manisha Pandya, Harsh Sharma


Functions with inputs:

You can define a function that can take inputs and use them.

def print_name(first_name, last_name):


print(first_name, last_name)

print_name("rohit", "sharma")
print("hello")

print_name("virat", "kohli")

# OUTPUT:

>>> rohit sharma

Returning a value from a function:

You can return a value from a function using the returnkeyword. This enables you to
store the value in some variable.

def summation(num1, num2):


total = num1 + num2

return total

addition1 = summation(4,89)
addition2 = summation(23,44)
print(addition1)

print(addition2)

# OUTPUT:

print function in python:

print function takes 3 arguments, one is positional and rest two are default.

print(*objects, sep=" ", end="\n")

separgument adds whatever is mentioned in it between two objects

Introduction of computer application By: Manisha Pandya, Harsh Sharma


endargument adds whatever is mentioned in it in the end
\nis new line character which means it'll move the cursor to the next line.

a = "tic"

b = "tac"

c = "toe"

print(a, b, c)

print(a, b, c)

# OUTPUT

>>> tic tac toe


tic tac toe

a = "tic"

b = "tac"

c = "toe"

print(a, b, c, sep="--", end="DONE")


print(a, b, c)

Introduction of computer application By: Manisha Pandya, Harsh Sharma


Strings, Lists, Dictionaries and Match Case

Strings in python:

Strings in python are defined by double quotes, like "rohit". Strings are indexable (starting
from 0), meaning, we can fetch a particular character from a string.
name = "rohit"

first_char = name[0]
second_char = name[1]

print(first_char, second_char)

# OUTPUT:

>>> r o

But if you index more than the length of string, python will give error. So, in the example of
"rohit", you can only index 0,1,2,3,4, any value above 4 will result in error, since the length
of "rohit" is 5, i.e. it has 5 characters.

name = "rohit"
char = name[5]

print(char)

# OUTPUT:

>>> Error

Introduction of computer application By: Manisha Pandya, Harsh Sharma


You can use lenfunction to get the length of a string:

name = "rohit"

length = len(name)

print(length)

# OUTPUT:
>>> 5

String Slicing:

You can obtain a part of string using slicing. In square brackets, the first number denote the
starting index and second number denote the ending index - 1. They both are seperated by
:.

text = "rohit is a good batsman"


name_sliced = text[0:5]

batsman_sliced = text[16:23]

print(name_sliced)

print(batsman_sliced)

# OUTPUT:

>>> 5

String Methods:

Strings in python offers various useful methods. Some of them are:

Introduction of computer application By: Manisha Pandya, Harsh Sharma


greet = "heLLo roHit"

lower_case = [Link]()
upper_case = [Link]()

capitalize = [Link]()

print(lower_case)
print(upper_case)
print(capitalize)

# OUTPUT:

>>> hello rohit


HELLO ROHIT

Hello rohit

greet = "heLLo roHit"

ro_position = [Link]("ro")
print(ro_position)

# OUTPUT:

>>> 6

Introduction of computer application By: Manisha Pandya, Harsh Sharma


Converting Strings into lists:

We can convert strings into list using splitmethod:

message1 = "rohit is a good batsman"


message2 = "dhoni-is-captain-cool"

message_list1 = [Link](" ")


message_list2 = [Link]("-")
greet = "hello rohit"
print(message_list1)
replace = [Link]("o", "x")
print(message_list2)
print(replace)

# OUTPUT:
# OUTPUT:
>>> ['rohit', 'is', 'a', 'good', 'batsman']

['dhoni', 'is', 'captain', 'cool']

Converting lists into strings:

We can convert list into a string using joinmethod:

text_list = ['rohit', 'is', 'a', 'good', 'batsman']

connector = " "


string = [Link](text_list)
print(string)

# OUTPUT:

>>> "rohit is a good batsman"

Introduction of computer application By: Manisha Pandya, Harsh Sharma


Lists in python:

you can store multiple values, of different data types in a list. list is defined by square
brackets and the elements inside the list are seperated by ,.

numbers = [1,3,4,6,1,2,33,89]

print(numbers, type(numbers))

my_list = [1,3,4.43,"virat",1,2.23,"rohit",89]
print(my_list, type(my_list))

# OUTPUT:

>>> [1, 3, 4, 6, 1, 2, 33, 89] <class 'list'>

[1, 3, 4.43, 'virat', 1, 2.23, 'rohit', 89] <class 'list'>

Similar to strings, lists are also indexable.

first_element = my_list[0]
last_element = my_list[7]

print(first_element)
print(last_element)

# OUTPUT:

>>> 1

89

Introduction of computer application By: Manisha Pandya, Harsh Sharma


Similar to strings, lists are also sliceable with the same syntax as used in strings.

slice = my_list[3:6]

print(slice)

# OUTPUT:
>>> ['virat', 1, 2.23]

You can add two lists with +operator:

list1 = [1,2,3]

list2 = [4,5,6]

list3 = list1 + list2


print(list3)

# OUTPUT:

>>> [1,2,3,4,5,6]

Introduction of computer application By: Manisha Pandya, Harsh Sharma


List Functions:

There are various built-in functions that can be applied on a list. Some of them are:

numbers = [2,3,-1,45,23,111,87,-90]

length = len(numbers)

summation = sum(numbers)
maximum = max(numbers)

minimum = min(numbers)
print(length)

print(summation)
print(maximum)

print(minimum)

# OUTPUT:

>>> 8

180

111

-90

List Methods:

appendis used to insert a new element at the end of a list:

Introduction of computer application By: Manisha Pandya, Harsh Sharma


numbers = [2,3]

[Link](5)
[Link](7)
print(numbers)

# OUTPUT:

>>> [2,3,5,7]

sortis used to sort a list in ascending order:

numbers = [222,3,98,78,-90,23]

[Link]()
print(numbers)

# OUTPUT:

>>> [-90, 3, 23, 78, 98, 222]

removeis used to remove an element:

numbers = [222,3,98,78,-90,23]

[Link](-90)
print(numbers)

# OUTPUT:

clearis used to empty the list:

Introduction of computer application By: Manisha Pandya, Harsh Sharma


numbers = [222,3,98,78,-90,23]

[Link]()
print(numbers)

# OUTPUT:

Dictionaries in python:

Dictionaries are key - value mappings in python. keyshave to be unique, while valuescan
have duplicates. In a dictionary, an element is a key-value pair. A dictionary is made with
curly brackets {} and each element is seperated with ,. key and it's corresponding value is
seperated with :.

my_dict = {"name":"rohit", "surname":"sharma", "age":38}

print(my_dict)

# OUTPUT:
>>> {'name': 'rohit', 'surname': 'sharma', 'age': 38}

name = my_dict["name"]
print(name)

# OUTPUT:

>>> rohit

You can get a value of a key using square brackets: You can also use the getmethod to get
a value of a key. benefit of using getis that it'll not throw an error if the key you're trying
to get value of does not exist in the dictionary.

Introduction of computer application By: Manisha Pandya, Harsh Sharma


value1 = my_dict.get("surname", 0)
value2 = my_dict.get("hobbie", 0)
print(value1)

print(value2)
# OUTPUT:

>>> sharma
0

Introduction of computer application By: Manisha Pandya, Harsh Sharma


Working with Files and Business Application Program

Opening files in python:

you open a file using the openfunction and input the file name. Along with the file name,
you also input the action you wanna do with the file with the mode input. Here is a list of
actions you can do:

1. mode=r: readthe file


2. mode=w: write in the file
3. mode=a: appending to the end of a file (basically updating an existing file)

Writing data in files:

You can write to a file using mode=w.

file = open("my_file.txt", mode="w")

names = ["rohit", "virat", "dhoni", "shivam"]


for n in names:

message1 = "How are you " + n + "\n"


message2 = n + " is a good player" + "\n"
[Link](message1)

[Link](message2)
[Link]()

Appending new data to files:

You can append new data to a file using mode=a.

file = open("my_file.txt", mode="a")

names = ["rohit", "virat", "sachin", "sehwag"]


for n in names:

message = n + " is a legend" + "\n"


[Link](message)

[Link]()

Introduction of computer application By: Manisha Pandya, Harsh Sharma


Reading data from files:

You can read data from files using mode=r.

file = open("my_file.txt", mode="r")


for line in file:

if "rohit" in line:
print(line, end="")
[Link]()

A program to manage inventory for a business:

def add_item(inventory, item_name, quantity):


if item_name in inventory:

inventory[item_name] += quantity
print("updated quantity for", item_name, "New quantity:",
inventory[item_name])

else:
inventory[item_name] = quantity

print("Added", item_name, "with quantity", quantity, "to inventory.")

def update_quantity(inventory, item_name, new_quantity):


if item_name in inventory:

inventory[item_name] = new_quantity
print("Quantity for", item_name, "updated to", new_quantity)
else:

print(item_name, "not found in inventory.")

def display_inventory(inventory):
if len(inventory) == 0:

print("Inventory is empty.")
else:

print("Current Inventory:")
for key in inventory:

Introduction of computer application By: Manisha Pandya, Harsh Sharma


print("3. Display Inventory")
print("4. Exit")

choice = input("Enter your choice: ")

if choice == '1':

item = input("Enter item name: ")


qty = int(input("Enter quantity: "))
add_item(inventory, item, qty)

elif choice == '2':


item = input("Enter item name to update: ")
new_qty = int(input("Enter new quantity: "))
update_quantity(inventory, item, new_qty)

elif choice == '3':


display_inventory(inventory)
elif choice == '4':

print("Exiting Inventory Management System. Goodbye!")


break

Introduction of computer application By: Manisha Pandya, Harsh Sharma

You might also like