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

LectureNote_UnitI

This document provides a comprehensive overview of Python programming, covering topics such as installation, the Python shell, code indentation, identifiers, keywords, literals, strings, and various operators. It emphasizes Python's ease of use, high-level data structures, and the importance of proper indentation for code readability and structure. The document also includes practical instructions for installing Python on different operating systems and running Python scripts.

Uploaded by

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

LectureNote_UnitI

This document provides a comprehensive overview of Python programming, covering topics such as installation, the Python shell, code indentation, identifiers, keywords, literals, strings, and various operators. It emphasizes Python's ease of use, high-level data structures, and the importance of proper indentation for code readability and structure. The document also includes practical instructions for installing Python on different operating systems and running Python scripts.

Uploaded by

rofi.lcbc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Lecture Note Python Programming Session: Jan-July, 2025

Unit 1: Introduction to Python Programming (8 hrs)


Introduction, Installation of Python Interpreter, Python Shell, Code Indentation, Identifiers and Keywords,
Literals, Strings, Operators ( Arithmetic, Relational, Logical, Assignment, Ternary, Bitwise, Increment and
Decrement Operators), Input and output statements, Output Formatting.

1. Introduction:
Python is an easy to learn, powerful programming language. It has efficient high-level data structures
and a simple but effective approach to object-oriented programming. Python‟s elegant syntax and
dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid
application development in many areas on most platforms. The Python interpreter and the extensive
standard library are freely available in source or binary form for all major platforms from the Python
Web site, http://www.python.org/, and can be freely distributed. The same site also contains distributions
of and pointers to many free third party Python modules, programs and tools, and additional
documentation. The Python interpreter is easily extended with new functions and data types
implemented in C or C++ (or other languages callable from C). Python is also suitable as an extension
language for customizable applications.
Python is a high-level language. Programs written in a high-level language have to be translated into
something more suitable before they can run. The engine that translates and runs Python is called the
Python Interpreter: There are two ways to use it: immediate mode and script mode. In immediate mode,
we type Python expressions into the Python Interpreter window, and the interpreter immediately shows
the result. Alternatively, we can write a program in a file and use the interpreter to execute the contents
of the file. Such a file is called a script.

Structure of a Python Program:


Python programs can be decomposed into modules, statements, expressions, and objects, as
follows:
a. Programs are composed of modules.
b. Modules contain statements.
c. Statements contain expressions.
d. Expressions create and process objects
Every file of Python source code whose name ends in a .py extension
is a module. Other files can access the items a module defines by importing that module. Import
operations essentially load another file and grant access to that file‟s contents.
A python program consists of a sequence of python statements. A statement is an instruction that
the Python interpreter can execute. When we type a statement on the command line, Python executes
it. Statements don‟t produce any result.
An expression is a combination of values, variables, operators, and calls to functions. If we type
an expression at the Python prompt, the interpreter evaluates it and displays the result.

IT-LCBC/LN/MAR/JAN-JUL-2025/PYTHON Page 1
Lecture Note Python Programming Session: Jan-July, 2025

2. Installation of Python Interpreter:


Interpreters are the computer program that will convert the source code or a high level language into
intermediate code (machine level language). It is also called translator in programming terminology.
Interpreters execute each line of statements slowly. This process is called Interpretation. For example
Python is an interpreted language, PHP, Ruby, and JavaScript.

The engine that translates and runs Python is called the Python Interpreter: There are two ways to
use it: immediate mode and script mode.
In immediate mode, we type Python expressions into the Python Interpreter window, and the
interpreter immediately shows the result.
Alternatively, we can write a program in a file and use the interpreter to execute the contents of the
file. Such a file is called a script.
In this class it is advised to use the latest stable version of Python3 to avoid issues from the
official website only with an IDE like VSCode/Atom/PyCharm etc.

IT-LCBC/LN/MAR/JAN-JUL-2025/PYTHON Page 2
Lecture Note Python Programming Session: Jan-July, 2025

1. Download the Python Installer

1. Go to the Python website: https://www.python.org.


2. Navigate to the Downloads section.
3. Select the installer suitable for your operating system:
o Windows: Download the .exe file.
o macOS: Download the .pkg file.
o Linux: Most distributions come with Python pre-installed. If not, you can install it using a
package manager like apt or yum.

2. Install Python on Your System

Windows

1. Run the downloaded .exe file.


2. Check the box for "Add Python to PATH" to avoid configuration issues later.
3. Click "Customize installation" if you want to change the default options or location.
4. Click "Install Now" and wait for the installation to complete.
5. Verify the installation:
o Open a Command Prompt (Win + R, type cmd, press Enter).
o Type: python --version or python3 --version.

macOS

1. Run the .pkg installer.


2. Follow the on-screen instructions.
3. Verify the installation:
o Open Terminal.
o Type: python3 --version.

Linux

1. Open Terminal.
2. Use your package manager to install Python:
o Debian/Ubuntu: sudo apt update && sudo apt install python3
o Fedora/Red Hat: sudo yum install python3
3. Verify the installation:
o Type: python3 --version.

3. Install pip (Python Package Installer in Mac and Ubuntu)

 Pip usually comes pre-installed with Python 3.x.


 To verify:
o Type: pip --version in your terminal or command prompt.
 If not installed:
o Download and run get-pip.py from pip's website.

IT-LCBC/LN/MAR/JAN-JUL-2025/PYTHON Page 3
Lecture Note Python Programming Session: Jan-July, 2025

4. Test Python Environment.

3. Python Shell:
Shell is a command processor. The Python Shell gives you a command line interface you can use to
specify commands directly to the Python interpreter in an interactive manner. The Python Shell is the
interpreter that executes python programs, other pieces of Python code, or simple commands. The user of a
Python shell types commands at the prompt (>>>), and presses the return key to send these commands
immediately to the interpreter for processing.
To start the Python shell, simply type python or py and hit Enter in the terminal(in Windows , in case of
*nix systems type python3):

The interactive shell is also called REPL which stands for read, evaluate, print, loop. It'll read each
command, evaluate and execute it, print the output for that command if any, and continue this same process
repeatedly until you quit the shell.
There are different ways to quit the shell:
1. you can hit Ctrl+Z on Windows or Ctrl+D on Unix systems to quit
2. use the exit() command
3. use the quit() command

How to Run Python Scripts:


The Python shell is useful for executing simple programs or for debugging parts of complex
programs.
But really large Python programs with a lot of complexity are written in files with a .py extension,
typically called Python scripts. Then you execute them from the terminal using the Python command

IT-LCBC/LN/MAR/JAN-JUL-2025/PYTHON Page 4
Lecture Note Python Programming Session: Jan-July, 2025

IT-LCBC/LN/MAR/JAN-JUL-2025/PYTHON Page 5
Lecture Note Python Programming Session: Jan-July, 2025

4. Code Indentation:
Indentation in Python refers to the (spaces and tabs) that are used at the beginning of a statement. The
statements with the same indentation belong to the same group called a suite. All adjacent statements at the
same level of indentation are considered to be a block/suite. The block ends when the indentation returns to
the previous level.
Primary purpose of indentation in Python is to define the scope of statements, such as those within loops,
conditionals, functions, and classes. Consistent and proper indentation is crucial for the interpreter to
understand the logical structure of the code. Indentation is not just a matter of style or convention in Python.
Here are the rules of indentation in python:
 Python‟s default indentation spaces are four spaces. The number of spaces, however, is
entirely up to the user. However, a minimum of one space is required to indent a statement.
 Indentation is not permitted on the first line of Python code.
 Python requires indentation to define statement blocks.
 A block of code must have a consistent number of spaces.
 To indent in Python, whitespaces are preferred over tabs. Also, use either whitespace or tabs
to indent; mixing tabs and whitespaces in indentation can result in incorrect indentation
errors.

Advantages of Indentation in Python


 Improved Readability: Indentation makes the code more readable by clearly indicating
which statements belong to which block of code. This makes it easier for other developers to
understand your code and makes it more maintainable.
 Consistency: By requiring consistent indentation levels, Python ensures that the code follows
a consistent style, making it easier to read and understand.
 Reduced Syntax: Python‟s use of indentation reduces the amount of syntax required to
define blocks of code. This makes Python code shorter and easier to read than code written in
other languages.
 Reduced Errors: By requiring consistent indentation levels, Python reduces the likelihood of
indentation-related errors that can occur in other languages. This improves code quality and
reduces the time required for debugging.
 Increased Efficiency: Python‟s use of indentation simplifies the coding process and allows
developers to write code faster and with fewer errors.

Disadvantages of Indentation in Python


 Limited Flexibility: Python‟s use of indentation can limit the flexibility of code formatting,
as all code blocks must follow a consistent indentation level. This can be problematic in
certain situations where code formatting needs to be adjusted for different environments or
requirements.
 Difficulties with Copy and Paste: If code is copied and pasted from one editor to another,
the indentation levels may not be preserved. This can lead to errors in the code and make it
more difficult to debug.
 Increased Learning Curve: The requirement for consistent indentation levels can increase
the learning curve for new Python programmers. This can make it more difficult to get started
with Python, especially for those who are used to other programming languages that use
different syntax to define blocks of code.
 Maintenance Issues: In some cases, changes to the indentation levels can have unintended
consequences that may be difficult to diagnose and fix. This can make maintenance more
difficult and time-consuming.

IT-LCBC/LN/MAR/JAN-JUL-2025/PYTHON Page 6
Lecture Note Python Programming Session: Jan-July, 2025

5. Identifiers and Keywords:

A Python identifier is a name used to identify a variable, function, class, module or other object. An
identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
Naming conventions for Python identifiers −
 Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
 Starting an identifier with a single leading underscore indicates that the identifier is private.
 Starting an identifier with two leading underscores indicates a strongly private identifier.
 If the identifier also ends with two trailing underscores, the identifier is a language-defined
special name.

Keywords are reserved words that cannot be used as variable names, function names, or any other
identifiers. Python keywords are the fundamental building blocks of any Python program. As of Python 3.8,
there are thirty-five keywords in Python. Some of the keywords are : if, for, while, break, continue, def, and,
or, return etc.
'False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'

6. Literals:
Literals are a notation for representing a fixed value in source code.
Python has different types of literals.
String literals: A string literal can be created by writing a text(a group of Characters ) surrounded by
the single(”), double(“”), or triple quotes. By using triple quotes we can write multi-line strings or
display in the desired way.
Numeric literals: There are three types of numeric literals:

Integer Both positive and negative numbers including 0. There should not be
literal any fractional part.
Float These are real numbers having both integer and fractional parts.
literal
Complex The numerals will be in the form of a + bj, where „a„ is the real part
literal and „b„ is the complex part
Boolean literals: There are only two Boolean literals in Python. They are True and False
Literal Collections: Like list literal, tuple literal etc.
Special literals: Python contains one special literal (None). ‘None’ is used to define a null variable

IT-LCBC/LN/MAR/JAN-JUL-2025/PYTHON Page 7
Lecture Note Python Programming Session: Jan-July, 2025

7. Strings:
Python string is an ordered collection of characters used to store and represent text-based
information. Python strings are categorized as immutable sequences, meaning that the characters they
contain have a left-to-right positional order and that they cannot be changed in-place.built-in len()
function is used to find length of a string.
There are a number of useful operations that can be performed with string. Among these are the
following:

s.capitalize() Capitalizes first character of s

s.capwords() Capitalizes first letter of each word in s

s.count(sub) Count number of occurrences of sub in s

s.find(sub) Find first index of sub in s, or -1 if not found

Find first index of sub in s, or raise ValueError if not


s.index(sub)
found

s.rfind(sub) Same as find, but last index

s.rindex(sub) Same as index, but last index

s.lower() Convert s to lower case

s.split() Return a list of words in s

s.join(lst) Join a list of words into a single string with s as separator

s.strip() Strip leading/trailing white space from s

s.upper() Convert s to upper string

s.replace(old,
Replace all instances of old with new in string
new)

IT-LCBC/LN/MAR/JAN-JUL-2025/PYTHON Page 8
Lecture Note Python Programming Session: Jan-July, 2025

8. Operators ( Arithmetic, Relational, Logical, Assignment, Ternary, Bitwise, Increment and


Decrement Operators):
Operators are special tokens that represent computations like addition, multiplication and
division. The values the operator uses are called operands.
Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Arithmetic operators are used with numeric values to perform common


mathematical operations:

Operator Name
+ Addition
- Subtraction
* Multiplication
/ Division
// Floor division
** Exponentiation
% modulus

Comparison operators are used to compare two values:

Operator Name
== Equal
!= Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Logical operators are used to combine conditional statements:


Operator Name
and Returns True if both statements are true

or Returns True if one of the statements is true

not Reverse the result, returns False if the result is true

IT-LCBC/LN/MAR/JAN-JUL-2025/PYTHON Page 9
Lecture Note Python Programming Session: Jan-July, 2025

Python Identity Operators


Identity operators are used to compare the objects, not if they are equal, but if
they are actually the same object, with the same memory location:
Operator Name
is Returns True if both variables are the same object

is not Returns True if both variables are not the same object

Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:

Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

Shift left by pushing zeros in from the right


<< Zero fill left shift
and let the leftmost bits fall off

Shift right by pushing copies of the leftmost


>> Signed right shift bit in from the left, and let the rightmost bits
fall off

IT-LCBC/LN/MAR/JAN-JUL-2025/PYTHON Page 10
Lecture Note Python Programming Session: Jan-July, 2025

9. Input and output statements


Python provides the input() function to take input from the user.
Syntax:
variable_name = input("Prompt message")

Example:
name = input("Enter your name: ")
print("Hello, " + name + "!")

Data Type Conversion:


By default, input() returns a string. You can convert it to other data types as needed:

age = int(input("Enter your age: "))


height = float(input("Enter your height in meters: "))

The print() function is used to display output on the screen.


Basic Syntax:
print(value1, value2, ..., sep=' ', end='\n')

 sep: Specifies the separator between values (default is a space).


 end: Specifies what to print at the end (default is a newline).

10. Output Formatting:

IT-LCBC/LN/MAR/JAN-JUL-2025/PYTHON Page 11
Lecture Note Python Programming Session: Jan-July, 2025

Sample Questions:

Answer the following as directed


1. Answer in very short: (1 marks each)
a) Python is a ___________ programming language. (Fill in the blank)
b) Who is known as the father of Python?
c)

IT-LCBC/LN/MAR/JAN-JUL-2025/PYTHON Page 12

You might also like