0% found this document useful (0 votes)
14 views23 pages

Python Notes

The Python Programming Syllabus covers fundamental topics including Python basics, operations, control flow, and functions. Each unit includes practical programming exercises and references for further reading. The syllabus emphasizes hands-on learning through practice programs and covers essential Python concepts such as data types, debugging, and string manipulation.

Uploaded by

singh1977anuj
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)
14 views23 pages

Python Notes

The Python Programming Syllabus covers fundamental topics including Python basics, operations, control flow, and functions. Each unit includes practical programming exercises and references for further reading. The syllabus emphasizes hands-on learning through practice programs and covers essential Python concepts such as data types, debugging, and string manipulation.

Uploaded by

singh1977anuj
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

Python Programming Syllabus

Unit-I
Basics of Python: The Python Interpreter; The print statement; Variables and
Assignments; Strings; Comments and Docstrings; Debugging; Input; Data types
and Data conversion.
Unit-II
Opera ons: Lists and List Opera ons; Comparison Opera ons; Logical
Opera ons; Prac ce Programs: Mathema cal opera ons, Convert Celsius to
Fahrenheit, Solve Quadra c Equa on.
Unit-III
Control Flow: Sequencing, Itera on and Selec on; For and While Loops;
Condi onal Statements: if, if-else, elif; Break and Con nue Statements; Ranges;
Prac ce Programs: Simple Harmonic Mo on, Mo on of a Ball Under Gravity,
Projec le Mo on.
Unit-IV
Func ons: Built-in Func ons, List and String Func ons, User-defined func on,
Dic onaries and Dic onary Func ons, Tuples, Sets, List Comprehensions;
Prac ce Programs: Make a Simple Calculator, Ohm’s Law and Power
Calcula on.
References
1. Eric Ma hes, Python Crash Course, 2nd Edi on, No Starch Press, 2019.
2. John Zelle, Python Programming: An Introduc on to Computer Science,
Franklin, Beedle & Associates Inc., 2003.
3. Rubin H. Landau, Manuel J. Páez, Cris an C. Bordeianu, Computa onal
Physics: Problem Solving with Python, 3rd Edi on, Wiley VCH, 2015.
4. Python Documenta on: h ps://[Link]/3/

&"C:\Users\91880\AppData\Local\Microso \WindowsApps\[Link]"
"c:\Users\91880\Downloads\[Link]"
Basics of python programming

Unit I

1. Python Interpreter
Definition:
The Python Interpreter is a program that reads, translates, and executes Python code line by
line.

 Translation: Converts source code into bytecode (.pyc).


 Execution : Bytecode runs on Python Virtual Machine (PVM).
 Provides runtime environment and memory management.
 Makes Python platform independent.

2. Python Execution Modes


Interactive Mode (REPL)
Definition:
Interactive mode allows users to execute Python statements one by one and get immediate
results.

REPL = Read → Evaluate → Print → Loop

Example

>>> 2 + 3
5

Uses

 Testing small code


 Learning Python
 Quick calculations

Script Mode
Definition:
Script mode executes Python code written in a .py file as a complete program.

Example

python [Link]

Uses

 Large programs
 Applications
 Automation scripts

3. print() Function
Definition:
print() is a built-in function used to display output on the screen.

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

Important Parameters

 objects – values to print


 sep – separator between values
 end – character printed at end
 file – output stream
 flush – forces immediate output

Example

print("Hello World")

4. Escape Characters
Definition:
Escape characters are special character sequences starting with a backslash (\) used to
represent special formatting characters.

Examples

Escape Meaning
\n New line
\t Tab
\ Backslash
\' Single quote
\" Double quote
Example

print("Hello\nWorld")

5. Variables
Definition:
A variable is a named storage location used to store a value in memory.

Example

x = 10
name = "Python"

Variable Naming Rules

 Must start with letter or _


 Can contain letters, digits, _
 Case sensitive
 Cannot use keywords

Example

Valid

age
user_name

Invalid

1name
my-variable

6. Dynamic Typing
Definition:
Dynamic typing means Python automatically determines the data type of a variable
during program execution.

Example

x = 10
x = "Hello"
7. Assignment Statement
Definition:
An assignment statement assigns a value to a variable using the = operator.

Example

x = 10

Types of Assignment

Assignment Type examples Use Case


Simple x = 5 Assigning a single value
Chained x = y = z = 5 Initializing multiple variables to the same value
Multiple x, y = 5, 10 Assigning different values to multiple variables
Augmented x += 5 Updating a variable with an operation

8. Comments
Definition:
Comments are notes in code ignored by the Python interpreter, used to explain the
program.

Example

# This is a comment

9. Docstrings
Definition:
Docstrings are special strings used to document modules, classes, and functions.

Example

def add(a, b):


"""Returns sum of two numbers"""
return a + b

Access using

help(add)
10. Debugging
Definition:
Debugging is the process of finding and fixing errors (bugs) in a program.

Common Techniques

 Reading traceback errors


 Using print()
 Using assert
 Using pdb debugger
 Using logging

11. Data Types


Definition:
A data type is a classifica on that specifies the type of value a variable can store and the
opera ons that can be performed on it.

In Python, data types are automatically assigned by the interpreter, which means Python
follows dynamic typing.

Python Data Types



├── Numeric
│ ├── int
│ ├── float
│ └── complex

├── Sequence
│ ├── str
│ ├── list
│ └── tuple

├── Mapping
│ └── dict

├── Set
│ ├── set
│ └── frozenset

├── Boolean
│ └── bool

└── Special
└── NoneType
Built-in Data Types Types

Category Data Type Definition Examples Characteristics


Numeric Integer (int) A whole number without a decimal a = 10 • Can be positive, negative, or
point. b = -5 zero.
c = 0 • Size is unlimited (limited by
memory).
Float (float) A number with a decimal point. x = 3.14 • Represents real numbers.
y = 25.75 • Stored in floating-point
format.
Complex A number with a real and an imaginary z = 3 + 4j • j represents the imaginary
(complex) part, written as a + bj. unit.
Sequence String (str) A sequence of characters used to name = "Python" • Ordered
represent text. message = 'Hello' • Indexed
text = """Multiline""" • Immutable
List (list) An ordered, mutable collection of numbers = [10, 20, 30] • Ordered
elements enclosed in square data = [1, "Python", 3.5, • Mutable
brackets []. True] • Allows duplicates
Tuple (tuple) An ordered, immutable collection of t = (1, 2, 3) • Ordered
elements enclosed in parentheses (). colors = ("red", "blue") • Immutable
• Allows duplicates
Mapping Dictionary A collection of key-value pairs enclosed student = { "name": • Keys must be unique.
(dict) in curly braces {}. "Rahul", "age": 20 } • Values can be duplicated.
• Mutable.
Set Types Set (set) An unordered collection of unique numbers = {1, 2, 3, 4} • Unordered
elements. • No duplicate values
• Mutable
Frozen Set An immutable version of a set. fs = frozenset([1,2,3]) • Cannot be modified after
(frozenset) creation.
• Immutable.
Boolean Boolean (bool) Represents logical truth values. x = True • Only two possible
y = False values: True and False.
None NoneType Represents the absence of a value. x = None • The only value is None.
Type

12. Checking Data Type


Python provides the type() function to check the data type.

Example:

x = 10
print(type(x))

Output:

<class 'int'>
13. Type Conversion
Definition:
Type conversion is the process of changing one data type into another.

Types of conversion:

1. Implicit conversion
2. Explicit conversion

1. Implicit Type Conversion


Python automatically converts one data type into another.

Example:

x = 10
y = 2.5
result = x + y
print(result)

Output:

12.5

2. Explicit Type Conversion (Type Casting)


Programmer manually converts data types using functions.

Type Conversion Functions

Example Output /
Function Purpose
Usage Result

int(3.14) 3
Converts a value to an integer.
int() int("10") 10
Truncates decimal points. int(True) 1

float(5) 5.0
Converts a value to a floating-point
float() float("3.14") 3.14
number. float(False) 0.0

str(123) "123"
str() Converts a value to a string. str(3.14) "3.14"
str(True) "True"
Example Output /
Function Purpose
Usage Result

bool(1) True
Converts a value to a Boolean bool(0) False
bool()
(True or False). bool("") False
bool("Hello") True

list("ABC") ['A', 'B',


Converts a sequence or iterable to
list() list((1, 2, 'C']
a list. 3)) [1, 2, 3]

tuple([1, 2, (1, 2, 3)
Converts a sequence or iterable to
tuple() 3]) ('A', 'B',
a tuple. tuple("ABC") 'C')

set([1, 2, 2, {1, 2, 3}
Converts a sequence or iterable to
set() 3]) {'A', 'B',
a set (duplicates are removed). set("AABBCC") 'C'}

14. input() Function


Definition:
input() is a built-in function used to take input from the user through the keyboard.

Example

name = input("Enter name: ")

15. Comparison Operators


Definition:
Comparison operators compare two values and return True or False.

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

Example
10 > 5

16. Logical Operators


Definition:
Logical operators combine multiple conditions or reverse their result.

Operator Meaning
and Both conditions true
or At least one true
not Reverse condition

Example

age > 18 and has_license

x = "100"
y = int(x)
print(y)
17. Strings

Strings
Definition A string is a sequence of characters used to represent name = "Python"
text.
Creation Strings can be created using: single_quotes = 'Hello'
double_quotes = "World"
triple_quotes =
"""Multiline text"""
Characteristics
• Ordered: Characters maintain their position
• Indexed: Each character has an index (starting from 0 from left and -1 from right)
• Immutable: Cannot be changed after creation
Aspect Description Examples / Syntax
String Indexing Accessing individual characters using their position. s = "Python"
print(s[0]) → P
print(s[-1]) → n
Immutable Strings cannot be modified after creation. s = "Hello"
Nature s[0] = "J" → ❌ Error!
Must create new string: s =
"J" + s[1:] → "Jello"
String Formatting
Definition: String formatting is the process of inserting variables or values into a string.

f-Strings Formatted string literals (Python 3.6+). name = "Alice"


Direct embedding of variables inside curly age = 25
braces {} within the string. Most modern and readable f"My name is {name} and I
approach. am {age} years old"
Syntax: f"string {variable}"

format() method Placeholders {} are replaced by values passed print("Hello


to format() method. {}".format("Learners"))
Syntax: "string {}".format(value)
Example Output
Positional Use index print("{1} is {0} years Alice is
arguments numbers for old".format(25, "Alice")) 25 years
reordering. old
Named Use keyword print("{name} is {age} years Bob is 30
placeholders arguments for old".format(name="Bob", age=30)) years old
clarity.
Format Similar to f- print("Price:
specifiers strings {:.2f}".format(49.955))
formatting.
Syntax: "string %s" % value print("Hello %s" % "Rahul")
% Uses % operator with format specifiers. Inspired by print("%s is %d years old"
formatting (Old C's printf(). % ("Rahul",print("Float:
style) %.2f" % 3.14159) 28))
Common
specifiers: %s (string), %d (integer), %f (float), %x (hex).

Use a tuple for multiple values.

Escape Special characters in strings. \n - New line


Sequences \t - Tab
\\ - Backslash
\' - Single quote
\" - Double quote
Raw string A raw string treats backslash (\) as a literal character r"string content"
instead of an escape character. R'raw string'
r"""multiline raw string"""
Created by prefixing a string with r or R.
String Methods
Function Purpose Example Usage

Common
Operations
String Slicing : Extracting a portion of a string s = "Python Programming"
using [start:end:step]. s[0:6] → "Python"
s[7:] → "Programming"
s[::-1] → Reverse string
Concatenation: Joining strings "Hello" + " " +
"World" → "Hello World"
Repetition: Repeating strings "Ha" * 3 → "HaHaHa"
Length: Getting string length len("Python") → 6
Membership: Checking if substring exists "Py" in "Python" → True
Case Conversion upper() - Converts to
uppercase
lower() - Converts to
lowercase
capitalize() - Capitalizes
first letter
title() - Capitalizes first
letter of each word
Searching find(sub) - Returns index of
substring
count(sub) - Counts
occurrences
startswith(prefix) - Checks
prefix
endswith(suffix) - Checks
suffix
Modification replace(old, new) - Replaces
substring
strip() - Removes
whitespace
split(delim) - Splits into list
join(iterable) - Joins
elements
Validation isalpha() - Checks if all
alphabetic
isdigit() - Checks if all
digits
isalnum() - Checks if
alphanumeric
isspace() - Checks if all
whitespace
18 Lists
Aspect Description Examples / Syntax
Definition A list is an ordered, mutable collection of elements enclosed fruits = ["apple", "banana", "orange"]
in square brackets [].
Characteristics • Ordered: Elements maintain their position mixed = [1, "hello", 3.14, True, [5, 6]]
• Mutable: Can be changed after creation
• Allows duplicates: Same value can appear multiple times
• Heterogeneous: Can store different data types
Creation Methods
Square brackets list1 = [1, 2, 3]
list() constructor list2 = list((1, 2, 3)) → [1, 2, 3]
list3 = list("abc") → ['a', 'b', 'c']
List comprehension squares = [x**2 for x in range(5)] → [0, 1,
4, 9, 16]
Empty list empty = [] or empty = list()

List Operations

Operation Syntax Description Example Result


Accessing Elements
Indexing Access element by fruits[0] "apple"
position (0-based) fruits[-1] (last element) "orange"
Slicing Extract a portion of the fruits[1:3] ["banana", "orange"]
list fruits[:2] ["apple", "banana"]
fruits[::2] Every 2nd element
Modifying Lists
Assignment Change an element fruits[1] = "grape" ["apple", "grape", "orange"]
append() Add element to the end [Link]("mango") ["apple", "grape", "orange",
"mango"]
insert() Add element at specific [Link](1, "kiwi") ["apple", "kiwi", "grape",
position "orange", "mango"]
extend() Add multiple elements [Link](["pear", ["apple", "kiwi", "grape",
from another list "plum"]) "orange", "mango", "pear",
"plum"]
remove() Remove first occurrence [Link]("grape") Removes "grape"
of a value
pop() Remove and return last = [Link]() Removes last element
element at index first = [Link](0) Removes first element
clear() Remove all elements [Link]() []
del statement Delete element(s) by del fruits[1] Removes element at index 1
index del fruits[1:3] Removes slice
List Information
len() Get number of elements len(fruits) 5 (for example)
index() Find index of first [Link]("banana") Returns index position
occurrence
count() Count occurrences of a [1, 2, 2, 3].count(2) 2
value
in operator Check if element exists "apple" in fruits True or False
Reordering
sort() Sort list in ascending [Link]() Sorts in place
order [Link](reverse=True) Descending order
reverse() Reverse the list order [Link]() Reverses in place
sorted() Return new sorted list new_list = sorted(fruits) Original unchanged
Copying
Shallow copy Create a new list list2 = [Link]() Independent copy (1 level deep)
reference list2 = list1[:]
Deep copy Complete independent import copy Fully independent
copy list2 = [Link](list1)
Concatenation &
Repetition
+ operator Join two lists [1, 2] + [3, 4] [1, 2, 3, 4]
* operator Repeat a list [1, 2] * 3 [1, 2, 1, 2, 1, 2]
Other Operations
min() / max() Find smallest/largest min([5, 2, 8]) 2
element max([5, 2, 8]) 8
sum() Sum all elements sum([1, 2, 3]) 6
(numeric lists)
enumerate() Get index and value for i, val in i = index, val = value
while iterating enumerate(fruits):
zip() Pair elements from list(zip([1,2], ['a','b'])) [(1, 'a'), (2, 'b')]
multiple lists

List Comprehensions

Type Syntax Example Result


Basic [expression for item in iterable] [x**2 for x in range(5)] [0, 1, 4, 9, 16]
With [expression for item in iterable if condition] [x for x in range(10) if x % 2 [0, 2, 4, 6, 8]
Condition == 0]
With if-else [expression_if_true if condition else ["even" if x % 2 == 0 else ["even", "odd", "even",
expression_if_false for item in iterable] "odd" for x in range(5)] "odd", "even"]
Nested [expression for item1 in iterable1 for item2 in [(x, y) for x in [1,2] for y in [(1,3), (1,4), (2,3),
iterable2] [3,4]] (2,4)]

Common List Methods Summary


Method Description Example
append(x) Adds element x to the end [Link](10)
extend(iterable) Adds all elements from iterable [Link]([4,5,6])
insert(i, x) Inserts x at position i [Link](2, "hello")
remove(x) Removes first occurrence of x [Link]("apple")
pop([i]) Removes and returns element at i x = [Link]()
clear() Removes all elements [Link]()
index(x) Returns index of first occurrence of x pos = [Link](5)
count(x) Returns number of occurrences of x count = [Link](2)
sort() Sorts the list in place [Link]()
reverse() Reverses the list in place [Link]()
copy() Returns a shallow copy of the list new_list = [Link]()

Try this for fun: sys module

You might also like