Intriduction to python
24 September 2025 19:35
⚡ Python Features (Short & Sweet)
1. Simple & Easy – Clean syntax, beginner-friendly.
2. Interpreted & Interactive – No compilation needed; supports live testing.
3. Object-Oriented – Supports OOP concepts like inheritance and encapsulation.
4. Portable – Runs on all major platforms (Windows, Linux, macOS).
5. Scalable – Suitable for small scripts to large applications.
6. Extendable – Can integrate with C, Java, COM, etc.
7. Dynamic – Dynamic typing and automatic memory management.
8. GUI & Database Support – Builds desktop apps and connects to major databases.
9. Rich Standard Library – Built-in modules for diverse tasks.
10. Free & Open Source – Freely available and modifiable.
🚀 Applications of Python (Concise Overview)
Area Description
1. Web Applications Build dynamic websites using Django, Flask, Pyramid; supports HTML, XML,
JSON.
2. GUI Desktop Apps Create cross-platform desktop apps with PyQt, wxPython, Tkinter.
3. Scientific Computing Used in data science and research with libraries like SciPy, Pandas, NumPy.
4. Software Supports build automation, testing, and control systems.
Development
5. Business Applications Ideal for ERP, e-commerce systems; Tryton is a notable platform.
6. Console Applications Develop CLI tools like IPython.
7. Multimedia Apps Create audio/video apps like TimPlayer, cplay.
8. 3D CAD Applications Build CAD tools; Fandango is a real-world example.
9. Enterprise Used in internal tools like OpenERP, Tryton, Picalo.
Applications
10. Image Processing Apps like VPython, Gogh, imgSeek for image manipulation.
11. Education Widely used for teaching programming at all levels.
🧱 Structure of a Python Program
Section Purpose
1. Documentation Comments explaining the program's purpose.
2. Import Includes built-in or user-defined modules.
3. Global Declaration Defines global variables used across the program.
4. Class Section Contains user-defined classes with data members and methods.
5. Subprogram Section Defines functions that perform specific tasks.
6. Playground Section Main execution area where functions and classes are called.
python chp1 Page 1
🧪 Example: Circle Area & Circumference
# Documentation Section
# Program to calculate area and circumference of a circle
import math # Import Section
radius = 5 # Global Declaration Section
class Circle: # Class Section
def getArea(self):
return math.pi * radius * radius
def getCircumference(self):
return 2 * math.pi * radius
def showRadius(): # Subprogram Section
print("Radius =", radius)
# Playground Section
showRadius()
c = Circle()
print("Area =", c.getArea())
print("Circumference =", c.getCircumference())
🖨 Output:
Radius = 5
Area = 78.53981633974483
Circumference = 31.41592653589793
🧠 Basics of Python: Standard Data Types
Data Type Description Example
Boolean Represents True or False values. Internally, True = 1, False = 0. size = -1 → size < 0 → True
None Represents a null or undefined value. Type: NoneType. answer = None
Integer Whole numbers, positive or negative. Can be binary (0b), octal a = 10, print(0xFF) → 255
(int) (0o), hex (0x).
Float Numbers with decimal points or scientific notation. x = 10.1, print(72e3) →
72000.0
Complex Numbers with real and imaginary parts (a + bj). x = 3+4j, x.real → 3.0
String Sequence of Unicode characters in quotes. Immutable and s = "Hello" or 'Hi'
ordered.
List Ordered, mutable collection. Can hold mixed types. first = [10, 20, 30]
Tuple Ordered, immutable collection. t = (70, 2.5, "tybca")
Dictionary Unordered key-value pairs. Mutable. dic = {1: "First", "Second":
2}
Set Unordered collection of unique items. s = {1, 2, 3}
🔍 Key Concepts
• Use type(variable) to check data type.
• Mutable types: List, Dictionary, Set.
• Immutable types: String, Tuple, Boolean, None, Numbers.
• Strings and lists are ordered; sets and dictionaries are unordered.
• Python supports Unicode and dynamic typing.
python chp1 Page 2
• Python supports Unicode and dynamic typing.
🧪 Python Variables: Quick Summary
🔹 What is a Variable?
• A variable is a named reference to a memory location that stores a value.
• It can hold different types of data and its value can change during execution.
🔹 Key Properties
• Automatically created when assigned a value.
• No need for explicit declaration.
• Lifetime = duration it exists in memory during execution.
🔹 Syntax
variable_name = value
🔹 Rules for Naming Variables
1. Use letters, digits, and underscores (_)
2. Cannot start with a digit
3. Case-sensitive (Amar ≠ AMAR)
4. No special characters like @, $, %
5. Avoid Python keywords (e.g., if, class, True)
6. Can be of unlimited length
🧪 Examples
✅ Basic Assignment
a = 10
print(a) # Output: 10
✅ Multiple Assignment
a = b = c = 1 # All share the same value
✅ Different Types
a, b, c = 10, 5.4, "hello"
✅ Computation
x = 10
y=5
z=x+y
print(x, y, z) # Output: 10 5 15
🔒 What Are Constants in Python?
• A constant is like a variable—but with a twist: once assigned, its value should not change during
the program’s execution.
• While Python doesn’t enforce immutability like some other languages (e.g., final in Java),
developers follow naming conventions and modular design to treat certain values as constants.
🧱 How Constants Are Declared
Python doesn’t have a built-in const keyword. Instead, constants are typically:
• Written in uppercase letters (e.g., PI, GRAVITY)
• Placed inside a separate module (e.g., constant.py) to isolate them from the main logic
📁 Example Setup
File: constant.py
PI = 3.14
GRAVITY = 9.8
File: main.py
python chp1 Page 3
File: main.py
import constant
print(constant.PI) # Output: 3.14
print(constant.GRAVITY) # Output: 9.8
This structure helps maintain clean code and ensures that values meant to remain unchanged are not
accidentally modified.
🧠 Why Use Constants?
• Improves readability and maintainability
• Prevents accidental changes to critical values
• Encourages modular programming by separating configuration from logic
Here’s a crisp and structured explanation of Literals in Python, tailored for clarity and quick learning,
Pramod-style:
🔹 What Are Literals in Python?
• Literals are fixed values written directly in the code.
• They represent constant data assigned to variables or used in expressions.
• Python supports various types of literals for different data types.
🧠 Types of Literals in Python
Type Description Example
String Literals Text enclosed in single ' ' or double " " quotes "Hello", '12345'
Int Literals Whole numbers 0, 1, -2
Long Literals Large integers (Python 2 only) 89675L
Float Literals Numbers with decimals 3.14, -0.5, 72e3
Complex Literals Numbers with real and imaginary parts 3+4j, 12j
Boolean Literals Truth values True, False
Special Literals Represents null or undefined None
Unicode Literals Unicode string (Python 2 syntax) u"hello"
List Literals Ordered, mutable collection [1, 2, 3], []
Tuple Literals Ordered, immutable collection (8, 9, 0), (9,)
Dict Literals Key-value pairs {'x': 1}, {}
Set Literals Unordered collection of unique items {8, 9, 10}
🧪 Examples
✅ String Literals
Fname = 'Hello'
Lname = "Python"
print(Fname) # Output: Hello
print(Lname) # Output: Python
✅ Boolean Literals
print(5 <= 2) # Output: False
print(3 < 9) # Output: True
✅ Special Literal
val1 = 10
python chp1 Page 4
val1 = 10
val2 = None
print(val2) # Output: None
✅ Literal Collections
numbers = [1, 2, 3, 4]
letters = ('a', 'b', 'c')
info = {'fname': 'Vijay', 'lname': 'Patil'}
print(numbers) # Output: [1, 2, 3, 4]
print(letters) # Output: ('a', 'b', 'c')
print(info) # Output: {'fname': 'Vijay', 'lname': 'Patil'}
🔹 Value and Type of Literals in Python
• Value: Any fixed data like numbers, strings, or characters used in a program.
• Type: Python uses the type() function to identify the data type of a value.
✅ Examples:
type('hello python') # → str
type('a') # → str
type(123) # → int
type(11.22) # → float
🆔 Python Identifiers: Quick Summary
🔹 What is an Identifier?
• A name used to identify variables, functions, classes, modules, etc.
• Acts as a label for memory locations or objects in a Python program.
✅ Rules for Valid Identifiers
Rule Description Examples
1. Allowed characters Letters (A–Z, a–z), digits (0–9), underscore myClass, var_1, _Address
(_)
2. Cannot start with Must begin with a letter or underscore ❌ 2variable, 10ID
digit
3. No spaces or tabs Identifiers must be continuous ❌ my name
4. No special %, @, $, etc. are not allowed ❌ $Money, @salary
characters
5. Case-sensitive Age ≠ age Both are different
6. No keywords Reserved words can't be used ❌ class, if, True
7. Any length Long names are allowed this_is_a_very_long_identifier_na
me
🧪 Examples
• ✅ Valid: Circle_Area, EmpName, Student, Salary2018, _PhoneNo
• ❌ Invalid: !count, 4marks, %Loan, 2018Salary
python chp1 Page 5
🛑 Reserved Words in Python
• Keywords are special words with predefined meaning and purpose in Python.
• They define the syntax and structure of the language.
• Cannot be used as variable names, function names, or identifiers.
• Python is case-sensitive, so True ≠ true.
🔑 Common Python Keywords
and as assert break class continue
def del elif else except exec
False finally for from global if
import in is lambda None not
or pass print raise return True
try while with yield
🧾 Python Statements
• A statement is a single instruction executed by the Python interpreter.
• Typically written on one line, e.g., a = 1.
🧱 Indentation in Python
• Python uses indentation (spaces) instead of {} braces to define code blocks.
• A block starts with an indented line and ends when indentation stops.
• Consistent indentation is mandatory—usually 4 spaces.
• Example:
for i in range(1, 11):
print(i)
if i == 5:
break
🔄 Multi-Line Statements
✅ Explicit Line Continuation
Use \ to split a long statement across lines:
stat = line_one + \
line_two + \
line_three
✅ Implicit Line Continuation
No need for \ inside brackets:
days = ['Monday', 'Tuesday',
'Wednesday', 'Thursday', 'Friday']
Python Comments: Quick Overview
• Comments are non-executable lines meant for explaining code.
• They help programmers understand the logic and structure.
• Python ignores comments during execution.
🧾 Types of Comments
1. Single-Line Comment
• Starts with #
• Ends at the line break
python
# This is a comment
python chp1 Page 6
# This is a comment
print("Hello Python") # Inline comment
2. Multi-Line Comment
• Enclosed in triple quotes: ''' ... ''' or """ ... """
python
'''This is a
multi-line comment'''
🖥 Input/Output in Python
🔹 Input Function: input()
• Used to take user input during program execution.
• Stores input as a string by default.
Syntax:
variable = input() # Without prompt
variable = input("Enter data:") # With prompt
Example:
x = input("Enter data: ")
print(x)
🔹 Output Function: print()
• Displays data on the screen.
• Can print variables, expressions, or strings.
Syntax:
print(expression)
Example:
a = "Hello"
b = "Python"
print(a + b) # Output: HelloPython
🎨 Formatting Output with str.format()
• Use {} as placeholders inside strings.
• Fill them using .format() method.
Examples:
x = 10; y = 20
print("The value of x is {} and y is {}".format(x, y))
print("I love {0} and {1}".format("apple", "milk")) # apple first
print("I love {1} and {0}".format("apple", "milk")) # milk first
⚙ Python Operators: Quick Overview
🔹 What Are Operators?
• Symbols used to perform operations on values or variables.
• Example: In 4 + 5, 4 and 5 are operands, + is the operator.
🔸 1. Unary Operators
• Operate on a single operand.
• Used for sign or bitwise inversion.
Operators: +, -, ~
python chp1 Page 7
Operators: +, -, ~
Examples:
x = 10
print(+x) # 10
print(-x) # -10
print(~x) # -11 (bitwise inversion)
🔸 2. Binary Operators
• Operate on two operands.
• Used for arithmetic, comparison, bitwise, etc.
Examples:
x = 10
y = 20
print(x + y) # 30
print(2 + 3) # 5
Common Binary Operators:
Arithmetic: +, -, *, /, %, **, //
Comparison: <, >, <=, >=, ==, !=
Bitwise: <<, >>, &, |, ^
🧮 Expression in Python
• An expression is a combination of variables, constants, operators, and function calls that
evaluates to a value.
• Examples:
1+8
(3 * 9) / 5
a*b+c*3
🔧 Types of Python Operators
Python supports:
• Arithmetic
• Assignment
• Comparison (Relational)
• Logical
• Bitwise
• Identity
• Membership
➕ Arithmetic Operators (with Examples)
Operator Symbol Function Example Result
Addition + Adds two operands a+b 30
Subtraction - Subtracts right from left b - a 10
Multiplication * Multiplies operands a*b 200
Division / Divides left by right b/a 2.0
Exponent ** Raises to power a ** 2 100
Modulus % Remainder of division a%b 10
Floor Div. // Removes decimal part b // a 2
python chp1 Page 8
🧮 Assignment Operators (Augmented)
Used to assign and update values in variables.
Operator Meaning Example Equivalent To
= Simple assignment c=a+b —
+= Add and assign c += a c=c+a
-= Subtract and assign c -= a c=c-a
*= Multiply and assign c *= a c=c*a
/= Divide and assign c /= a c=c/a
%= Modulus and assign c %= a c=c%a
**= Power and assign c **= a c = c ** a
//= Floor divide assign c //= a c = c // a
🔍 Comparison (Relational) Operators
Used to compare values. Returns True or False.
Operator Meaning Example Result
== Equal to a == b False
!= Not equal to a != b True
> Greater than a>b False
< Less than a<b True
>= Greater than or equal to a >= b False
<= Less than or equal to a <= b True
🔗 Logical Operators
Used to combine multiple conditions. Returns Boolean result.
Operator Meaning Example Result
and Both must be true a and b False
or At least one true a or b True
not Reverses condition not(a and b) True
🧮 Bitwise Operators
Operate directly on binary bits of integers.
Operator Name Example (a=10, b=4) Result
& AND a & b → 1010 & 0100 0
` ` OR `a b→1010 0100` 14
^ XOR a ^ b → 1010 ^ 0100 14
~ NOT (1's comp.) ~a → ~1010 -11
<< Left Shift a << 2 → 101000 40
>> Right Shift a >> 2 → 0010 2
python chp1 Page 9
>> Right Shift a >> 2 → 0010 2
🧠 Identity Operators
Used to compare memory locations of two objects.
Operator Description Example Result
is True if both refer to the same object a is b True
is not True if they refer to different objects a is not b False
🔍 Membership Operators
Used to check if a value exists in a sequence like a string, list, tuple, or dictionary.
Operator Meaning Example Result
in True if value is present 'H' in "Hello World" True
not in True if value is absent "Hello" not in "Hello World" False
🧠 Use Case
• Simplifies element search in sequences.
• Works with: string, list, tuple, set, dictionary (checks keys only).
🧪 What Is a Dry Run?
• A dry run is a manual step-by-step walkthrough of code to trace variable values.
• Helps verify logic and correctness before actual execution.
• Typically involves a table showing how variables change at each step.
🔍 Dry Run Example Using String
name = "Python"
greeting = "Hello " + name
print(greeting)
Step name greeting
1 "Python" —
2 "Python" "Hello Python"
Output Hello Python
🔍 Dry Run Example Using Dictionary
student = {"name": "Pramod", "marks": 85}
student["grade"] = "A"
print(student)
Step student
1 {"name": "Pramod", "marks": 85}
2 {"name": "Pramod", "marks": 85, "grade": "A"}
Output {'name': 'Pramod', 'marks': 85, 'grade': 'A'}
🔍
python chp1 Page 10
🔍 Dry Run Example Using Tuple
data = (10, 20, 30)
sum_val = data[0] + data[2]
print(sum_val)
Step data sum_val
1 (10, 20, 30) —
2 (10, 20, 30) 40
Output 40
🖥 Input in Python
• input() function takes user input as a string.
• Optional prompt can be added inside the parentheses.
Syntax:
name = input("Enter your name: ")
Conversion:
int('5') # → 5
float('5') # → 5.0
eval('2+3') # → 5
📤 Output in Python
• print() function displays output on the screen.
Examples:
print("Hello") # → Hello
print(1, 2, 3, 4) #→1234
print(1, 2, 3, 4, sep='*') # → 1*2*3*4
print(1, 2, 3, 4, sep='#', end='&')# → 1#2#3#4&
🎨 Formatted Output
• Use str.format() with {} placeholders.
Examples:
print("x is {} and y is {}".format(10, 20)) # → x is 10 and y is 20
print("I love {0} and {1}".format("apple", "milk")) # → I love apple and milk
print("I love {1} and {0}".format("apple", "milk")) # → I love milk and apple
python chp1 Page 11
python chp1 Page 12