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

Python Programming

Python programming for bcom bba bca

Uploaded by

abaivox009
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Python Programming

Python programming for bcom bba bca

Uploaded by

abaivox009
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

PYTHON PROGRAMMING

UNIT I
THE WAY OF THE PROGRAM

The single most important skill for a computer scientist


is problem solving.
Problem solving means the ability to formulate problems,
think creatively about solutions, and express a solution
clearly and accurately.
As it turns out, the process of learning to program is an
excellent opportunity to practice problem-solving skills.
On one level, the user will be learning to program, a useful
skill by himself/ herself.
On another level, the user will use programming as a
means to an end.
As the user go along, that end will become clearer.
THE PYTHON PROGRAMMING LANGUAGE

Python is a popular programming language.


It was created by Guido van Rossum, and released in 1991.

USED:

✔ Web Development (Server - Side)


✔ Software Development
✔ Mathematics
✔ System Scripting
USES OF PYTHON :
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and
modify files.
Python can be used to handle big data and perform complex
mathematics.
Python can be used for rapid prototyping, or for
production-ready software development.
WHY PYTHON?
Python works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with
fewer lines than some other programming languages.
Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be
very quick.
Python can be treated in a procedural way, an object-oriented way or
a functional way.
WHAT IS A PROGRAM?
A program is a sequence of instructions that specifies how to
perform a computation.
The computation might be something mathematical,
✔ Such as solving a system of equations or
✔ Finding the roots of a polynomial,
▪ but it can also be a symbolic computation,
• Such as searching and replacing text in a document
• Something graphical, like processing an image or
playing a video.
The details look different in different languages, but a few basic
instructions appear in just about every language
Contd..
INPUT:
Get data from the keyboard, a file, the network, or some other
device.

OUTPUT:
Display data on the screen, save it in a file, send it over the
network, etc.

MATH:
Perform basic mathematical operations like addition and
multiplication.
DEBUGGING

Debugging in Python involves identifying and fixing errors


in your code.
Python provides several tools and techniques to help with
debugging:
Contd..

CONDITIONAL EXECUTION:
Check for certain conditions and run the appropriate code.

REPETITION:
Perform some action repeatedly, usually with some variation.
Contd..
1. Print Statements:
Adding print statements at strategic points in the code can
help the user to understand the flow of execution and the
values of variables at different stages.
2. Using `pdb` (Python Debugger):
The `pdb` module provides a built-in debugger for Python.
The user can insert breakpoints in code and run it in
interactive mode, allowing to inspect variables, step through
code, and identify issues.
3. IDEs with Debugging Support:
Integrated Development Environments (IDEs) like PyCharm,
Visual Studio Code, and others offer debugging tools
integrated into the development environment.
These tools provide features like breakpoints, variable
inspection, stepping through code, and more
Contd..
4. Syntax Errors:
Python raises syntax errors when there's a mistake in the
syntax of code.
The user needs to read the error message carefully to identify
the location of the error and fix it.

5. Logical Errors:
These are errors in the logic of code, where it produces
unexpected results.
Use print statements and debugging tools to trace the flow of
execution and identify where the logic deviates from what you
intended.
Contd..
6. Tracebacks:
When an exception occurs, Python generates a traceback that
shows the sequence of function calls leading to the error.
Read the traceback carefully to identify the source of the
error.
7. Unit Testing:
Writing unit tests for code can help identify and fix
errors more efficiently.
Unit tests provide automated checks to verify that
individual components of code behave as expected.
When debugging, it's essential to approach the problem
systematically, starting with understanding the error,
identifying its source, and then applying the appropriate
debugging technique to fix it.
FORMAL AND NATURAL LANGUAGE

NATURAL LANGUAGE:
Natural languages are the languages that people speak,
such as English, Spanish, and French. They were not
designed by people (although people try to impose some
order on them); they evolved naturally
FORMAL LANGUAGE:
Formal languages are languages that are designed by
people for specific applications.
For example, the notation that mathematicians use is a
formal language that is particularly good at denoting
relationships among numbers and symbols.
Chemists use a formal language to represent the chemical
structure of molecules.
Programming languages are formal languages that
have been designed to express computations.
Contd..

Formal languages tend to have strict rules about syntax.


For example, 3+3=6 is a syntactically correct mathematical
statement, but 3=+6$ is not.
H2O is a syntactically correct chemical name, but 2 Zz is not.
DIFFERENCES
Ambiguity
✔ Natural languages are full of ambiguity, which people deal
with by using contextual clues and other information.
✔ Formal languages are designed to be nearly or completely
unambiguous, which means that any statement has exactly
one meaning, regardless of context.
Contd..
Redundancy
✔ In order to make up for ambiguity and reduce
misunderstandings, natural languages employ lots of
redundancy. As a result, they are often verbose.
✔ Formal languages are less redundant and more
concise.
Literalness
✔ Formal languages mean exactly what they say.
✔ On the other hand, natural languages are full of
idiom and metaphor.
✔ If someone says, “The other shoe fell”, there is
probably no shoe and nothing falling.
THE FIRST PROGRAM
Python is one of the simplest programming language out
there.
In fact, it was developed for the sole purpose of
simplifying the process of learning a programming
language and exposed beginners to the concepts of
Programming.
The following steps to be followed
✔ Step 1: Open an editor of your choice to write the
Python code. Here we will simply use Notepad
but it is completely up to you what you prefer.
✔ Step 2: Now write the code in the editor.
✔ Step 3: Now that we have completed the code
save it as gfg.py (‘gfg’ is just a name that we gave
to the python file)
Contd..
✔ Step 4: Now it’s time to run the python code so open up the
terminal that your OS provides and move to the directory
(it’s on Desktop in this case) where the file has been saved.
Here we will be using Command Prompt.
✔ Step 5: Now make a call to the python interpreter from
the cmd to run the gfg application as below:

Example :
>>> print("Welcome to Nehru Arts and Science College!")
Welcome to Nehru Arts and Science College!
VARIABLES

Python Variable is containers that store values.


Python is not “statically typed”.
No need to declare variables before using them or declare
their type.
A variable is created the moment the user first assign a
value to it.
A Python variable is a name given to a memory location.
It is the basic unit of storage in a program.
Contd..
Rules for Python Variables:

A Python variable name must start with a letter or the underscore


character.
A Python variable name cannot start with a number.
A Python variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ ).
Variable in Python names are case-sensitive (name, Name, and
NAME are three different variables).
The reserved words(keywords) in Python cannot be used to name
the variable in Python.
Contd..
Variables Assignment :

# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A string
name = "John"
print(age)
print(salary)
print(name)

Output:
45
1456.8
John
Contd..
Declaration and Initialization of Variables:

# declaring the var


Number = 100

# display
print( Number)

Output:

100
Contd..
Redeclaring variables in Python:

# declaring the var


Number = 100
# display
print("Before declare: ", Number)
# re-declare the var
Number = 120.3
print("After re-declare:", Number)
Output:
Before declare: 100
After re-declare: 120.3
Contd..
Assign Values to Multiple Variables :

a = b = c = 10

print(a)
print(b)
print(c)

Output:
10
10
10
Contd..
Assigning different values to multiple variables :

a, b, c = 1, 20.2, “NASC"

print(a)
print(b)
print(c)
Output:
1
20.2
NASC
Contd..
Can We Use the Same Name for Different Types? :

a = 10
a = “NASC"

print(a)

Output:
NASC
Contd..
How does + operator work with variables? :

The Python plus operator + provides a convenient way to add


a value if it is a number and concatenate if it is a string.
If a variable is already created it assigns the new value back to
the same variable.
a = 10 Output
b = 20 30
print(a+b) Am a Good Person
a = “Am a"
b = “Good Person"
print(a+b)
Contd..
Global and Local Python Variables :

Local variables in Python are the ones that are defined and
declared inside a function.
Global variables in Python are the ones that are defined and
declared outside a function

# This function uses global variable s


def f():
s = "Welcome NASC" Output:
print(s) Welcome NASC
f()
Contd..
# This function has a variable with
# name same as s
def f():
print(s)

# Global scope
s = "I love India"
f()

Output:
I love India
EXPRESSIONS
An expression is a combination of operators and operands that is
interpreted to produce some other value.
In any programming language, an expression is evaluated as per
the precedence of its operators.
If there is more than one operator in an expression, their
precedence decides which operation will be performed first.
There are eight types of expressions. They are
1. Constant Expressions
2. Arithmetic Expressions
3. Integral Expressions
4. Floating Expressions
5. Relational Expressions
6. Logical Expressions
7. Bitwise Expressions
8. Combinational Expressions
Contd..
1. Constant Expressions:
These are the expressions that have constant values only.

# Constant Expressions
x = 15 + 1.3
print(x)

Output
16.3
Contd..
2. 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.
Here are some arithmetic operators in Python:
Contd..
Operators Syntax Functioning

+ x+y Addition

– x–y Subtraction

* x*y Multiplication

/ x/y Division

// x // y Quotient

% x%y Remainder

** x ** y Exponentiation
Contd..
# Arithmetic Expressions
x = 40
y = 12
add = x + y
sub = x - y Output
pro = x * y 52
div = x / y 28
print(add) 480
print(sub) 3.3333333333333335
print(pro)
print(div)
Contd..
3. Integral Expressions:
These are the kind of expressions that produce only integer results
after all computations and type conversions.

# Integral Expressions
a = 13
Output
b = 12.0
25
c = a + int(b)
print(c)
Contd..
4. Floating Expressions:
These are the kind of expressions which produce floating point
numbers as result after all computations and type conversions.

# Floating Expressions
a = 13
b=5 Output
2.6
c=a/b
print(c)
Contd..
5. Relational Expressions:

In these types of expressions, arithmetic expressions are


written on both sides of relational operator (> , < , >= , <=).
Those arithmetic expressions are evaluated first, and then
compared as per relational operator and produce a boolean
output in the end.
These expressions are also called Boolean expressions.
Contd..
# Relational Expressions
a = 21
b = 13
c = 40
d = 37

p = (a + b) >= (c - d)
print(p)

Output
True
Contd..
6. Logical Expressions:

These are kinds of expressions that result in


either True or False.
It basically specifies one or more conditions.
For example, (10 == 9) is a condition if 10 is equal to 9.
The above statement is not correct, so it will return False.
Here are some logical operators in Python:
Contd..

Operator Syntax Functioning

It returns true if
both P and Q are
and P and Q
true otherwise
returns false

It returns true if at
or P or Q least one of P and Q
is true

It returns true if
not not P
condition P is false
Contd..
P = (10 == 9)
Q = (7 > 5)

# Logical Expressions
R = P and Q
S = P or Q Output
T = not P False
True
print(R) True
print(S)
print(T)
Contd..
7. Bitwise Expressions:

These are the kind of expressions in which computations are


performed at bit level.

# Bitwise Expressions
a = 12

x = a >> 2 Output
y = a << 1 3 24

print(x, y)
Contd..
8. Combinational Expressions:

Different types of expressions can be used in a single


expression, and that will be termed as combinational expressions.

# Combinational Expressions
a = 16
b = 12
Output
c = a + (b >> 1) 22
print(c)
Contd..
OPERATOR PRECEDENCE
If there is more than one operator in an expression, it may give
different results on basis of the order of operators executed.
To sort out these confusions, the operator precedence is
defined.
Operator Precedence simply defines the priority of operators
that which operator is to be executed first.
Operator precedence or priority is given below
Contd..
Precedence Name Operator
1 Parenthesis ()[]{}
2 Exponentiation **
Unary plus or minus,
3 -a , +a , ~a
complement

4 Multiply, Divide, Modulo / * // %

5 Addition & Subtraction + –


Contd..
Precedence Name Operator
6 Shift Operators >> <<
7 Bitwise AND &
8 Bitwise XOR ^
9 Bitwise OR |
10 Comparison Operators >= <= > <
11 Equality Operators == !=
12 Assignment Operators = += -= /= *=
Contd..
Precedence Name Operator
Identity and membership
13 is, is not, in, not in
operators
14 Logical Operators and, or, not

# Multi-operator expression
a = 10 + 3 * 4
Output
print(a)
22
b = (10 + 3) * 4
52
print(b)
22
c = 10 + (3 * 4)
print(c)
STATEMENTS

Statements are instructions or commands that you write to


perform specific actions or tasks.
They are the building blocks of a Python program.
A statement is a line of code that performs a specific action.
It is the smallest unit of code that can be executed by the Python
interpreter.
There are 2 types of Statements. They are
1. Assignment Statement
2. Conditional Statement
Contd..
Assignment Statement:

An Assignment statement is a statement that is used to set a


value to the variable name in a program.
Assignment statement allows a variable to hold different types
of values during its program lifespan.

a = 16
Print(a) Output
16
Contd..
Conditional Statement:

Programmers can instruct the computer to perform a variety of


tasks, from simple arithmetic operations to complex
decision-making processes.
Proper use of statements is crucial to writing efficient and
effective Python code.

x=3
Output
if x < 5:
X is less than 5
print("x is less than 5")
else:
print("x is greater than or equal to 5")
Contd..
Statement Set:

Statement Description
Statements spanning multiple
Multi-Line Statements lines using line continuation
or braces.
Statements that contain other
Compound Statements
statements (e.g., if, while, for).
Basic standalone statements
Simple Statements
that perform a single action.
Statements that evaluate and
Expression Statements
produce a value.
A placeholder statement that
pass Statement
does nothing.
Contd..
Statement Description
Used to delete references to
del Statement
objects.
Terminates a function and
return Statement
returns a value (optional).
Imports modules or specific
import Statement
objects from modules.
Control flow statements used
in loops (continue skips to the
continue and break Statements
next iteration, break exits the
loop).
Contd..
Multi-Line Statements:

Multi-line statements are a convenient way to write long code in


Python without making it cluttered.
They allow users to write several lines of code as a single
statement, making it easier for developers to read and understand
the code.
1.Using backslash:

total = 10 +
\ 20 +
\ 30 print(total) ### Output
Contd..
2.Using parentheses:

fruit_list = ('Apple’,
'Mango’,
‘Banana’,
'Orange’)
print(fruit_list) ### Output
Contd..
Simple Statements:

Simple statements are the smallest unit of execution in Python


programming language and they do not contain any logical or
conditional expressions.
They are usually composed of a single line of code and can
perform basic operations such as assigning values
to variables, printing out values, or calling functions.
Simple statements are essential to programming in Python
and are often used in combination with more complex
statements to create robust programs and applications.
Contd..
Expression statements:

Expression statements in Python are lines of code that evaluate


and produce a value.
They are used to assign values to variables, call functions, and
perform other operations that produce a result.
Expression statements are an essential part of Python
programming and allow for the execution of mathematical and
computational operations.
Contd..
Assert Statement:
The assert statement in Python is used to test conditions and
trigger an error if the condition is not met.
It is often used for debugging and testing purposes.

Try Statement:
The try statement in Python is used to catch exceptions that may
occur during the execution of a block of code.
It ensures that even when an error occurs, the code does not stop
running.
VALUES AND TYPES

A value is one of the basic things a program works with,


like a letter or a number.
The user can print values in Python.

print(17)
print('Hello World!')

OUTPUT:
17
Hello World!
Contd..

By using the type function the user can find out the type of the value.

print(type('Hello, World!'))
print(type(17))
print(type(3.2))

OUTPUT:
<class 'str'>
<class 'int'>
<class 'float'>
KEYWORDS

Python Keywords are some predefined and reserved words


in Python that have special meanings.
Keywords are used to define the syntax of the coding.
The keyword cannot be used as an identifier, function, or
variable name.
All the keywords in Python are written in lowercase except
True and False.
There are 35 keywords in Python 3.11.
In Python, there is an inbuilt keyword module that provides
an iskeyword() function that can be used to check whether a
given string is a valid keyword or not.
The user can check the name of the keywords in Python by
using the kwlist attribute of the keyword module.
Contd..

Rules for Keywords in Python

Python keywords cannot be used as identifiers.

All the keywords in Python should be in lowercase except

True and False.


Contd..
List of Python Keywords

Keywords Description
This is a logical operator which
and returns true if both the operands
are true else returns false.

This is also a logical operator


or which returns true if anyone
operand is true else returns false.

This is again a logical operator it


not returns True if the operand is false
else returns false.
Contd..
Keywords Description

This is used to make a


if
conditional statement.

Elif is a condition statement used


with an if statement. The elif
elif statement is executed if the
previous conditions were not
true.

Else is used with if and elif


conditional statements. The else
else
block is executed if the given
condition is not true.
Contd..
Keywords Description

for This is used to create a loop.

This keyword is used to create


while
a while loop.

This is used to terminate the


break
loop.

This is used to create an


as
alternative.

def It helps us to define functions.


Contd..
Keywords Description

It is used to define the anonymous


lambda
function.

This is a null statement which


pass
means it will do nothing.

It will return a value and exit the


return
function.

True This is a boolean value.

False This is also a boolean value.

try It makes a try-except statement.


Contd..
Keywords Description
The with keyword is used to
with
simplify exception handling.

This function is used for


assert debugging purposes. Usually used
to check the correctness of code

class It helps us to define a class.

It continues to the next iteration of


continue
a loop

del It deletes a reference to an object.


Contd..
Keywords Description

Used with exceptions, what to do


except
when an exception occurs

Finally is used with exceptions, a


block of code that will be executed
finally
no matter if there is an exception or
not.

It is used to import specific parts of


from
any module.

global This declares a global variable.

import This is used to import a module.


Contd..
Keywords Description

It’s used to check whether a value is


in
present in a list, range, tuple, etc.

This is used to check if the two


is
variables are equal or not.

This is a special constant used to


denote a null value or avoid. It’s
none important to remember, 0, any empty
container(e.g empty list) do not
compute to None
Contd..
Keywords Description

nonlocal It’s declared a non-local variable.

raise This raises an exception.

It ends a function and returns a


yield
generator.

It is used to create asynchronous


async
coroutine.

It releases the flow of control back to


await
the event loop.
Contd..

# code
import keyword

print(keyword.kwlist)

Output

['False', 'None', 'True', 'and', 'as', 'assert', 'async',


'await', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'finally', 'for', 'from',
'global', 'if', 'import', 'in', 'is',...

You might also like