Python Programming: Detailed Notes with Short Code Examples
1. Origins and History of Python
- Creator: Guido van Rossum, 1989 (Netherlands)
- First Released: Python 0.9.0 in 1991.
- Named after: "Monty Python's Flying Circus" (comedy group).
- Goal: Easy readability, clean syntax, support for multiple programming paradigms.
2. Structure of a Python Program
- Python code flows from top to bottom.
- Organized using functions, conditionals, loops, and indentation.
Example:
def greet(name):
print("Hello", name)
greet("Salman")
3. Interpreter Shell
- Known as REPL: Read-Eval-Print Loop.
- Executes Python code line by line.
Example:
>>> 5 + 3
4. Indentation
- Used to define blocks of code.
Example:
if 5 > 2:
print("5 is greater than 2")
5. Comments
- Single-line: #
- Multi-line: ''' or """
Example:
# This is a comment
""" Multi-line comment """
6. Identifiers and Keywords
- Identifiers: variable/function names. Must start with a letter or _.
- Keywords: reserved words like if, else, for, while, True, False.
Example:
name = "Alice" # valid
# 2name = "Bob" # invalid
7. Literals
- Fixed values like: 10, "Hello", True, None.
Example:
x = 10
name = "Ali"
flag = True
8. Basic Operators
Arithmetic: +, -, *, /, //, %, **
Relational: ==, !=, >, <, >=, <=
Logical: and, or, not
Assignment: =, +=, -=, *=, /=
Bitwise: &, |, ^, ~, <<, >>
Example:
a, b = 5, 2
print(a + b)
9. Entering Expressions into the Interactive Shell
- Can test simple expressions.
Example:
>>> 10 + 20
30
>>> "Hi" * 3
'HiHiHi'
10. Data Types
Integer: x = 10
Float: pi = 3.14
String: text = "Python"
Use type() to check.
11. String Concatenation and Replication
Example:
name = "Sal"
print(name + "man") # Salman
print(name * 3) # SalSalSal
12. Storing Values in Variables
- No need to declare type.
Example:
age = 20
name = "Sara"
price = 99.99
13. Creating Python Programs: Input and Output
Input:
name = input("Enter name: ")
Output:
print("Hello", name)
14. Control Statements
Branching:
if x > 0:
print("Positive")
Looping:
for i in range(3):
print(i)
Range:
range(2, 10, 2)
Exit:
import sys; [Link]()
Break:
for i in range(5):
if i == 3: break
Continue:
for i in range(5):
if i == 2: continue
Pass:
for i in range(5): pass