Python Programming Basics - Brief
Notes
1. Features and History of Python
• Created by Guido van Rossum, first released in 1991.
• Interpreted, dynamically typed, and open-source.
• Easy syntax, large standard library, and supports multiple paradigms.
2. Literal Constants
🔹 Literal Constants in Python
A literal constant is a fixed value that appears directly in the source code. These are the
values that do not change during program execution. Python supports several types of
literal constants:
🔸 Types of Literal Constants:
1. Numeric Literals
Represent numbers and are of types:
o int (e.g., 10, -25)
o float (e.g., 3.14, -0.001)
o complex (e.g., 3+5j)
Example:
x = 100 # Integer literal
y = 3.14 # Float literal
z = 2 + 3j # Complex literal
2. String Literals
Sequence of characters enclosed in:
o single quotes '...'
o double quotes "..."
o triple quotes '''...''' or """...""" for multi-line
Example:
name = "Alice"
text = '''This is
a multi-line
string.'''
3. Boolean Literals
Represents truth values:
o True
o False
Example:
flag = True
is_equal = (5 == 5) # Returns True
4. Special Literal: None
Used to denote absence of a value or null value.
Example:
result = None
5. Literal Collections
While not constants in strict sense, you can have literals for:
List: [1, 2, 3]
Tuple: (1, 2, 3)
Set: {1, 2, 3}
Dict: {'a': 1, 'b': 2}
🔸 Summary Table:
Type Example Description
Integer 42, -7 Whole numbers
Float 3.14, -0.5 Decimal numbers
String "hello" Sequence of characters
Boolean True, False Logical values
None None Absence of value
3. Variables and Identifiers
Variables store data. Identifiers must start with a letter or underscore and are case-
sensitive.
Variables:
A variable in Python is a name used to store data that can change during program
execution. You don't need to declare its type explicitly — Python automatically
determines the type based on the assigned value.
Example:
name = "Alice" # String
age = 25 # Integer
price = 10.5 # Float
Variables act as containers for data values.
The type of the variable can change dynamically:
x = 10 # Initially an integer
x = "Ten" # Now it's a string
🔸 Identifiers:
Identifiers are the names used to identify variables, functions, classes, modules, etc.
Rules for Identifiers:
1. Must begin with a letter (A–Z or a–z) or an underscore (_)
2. Can be followed by letters, digits (0–9), or underscores.
3. Case-sensitive: Age and age are different.
4. Cannot use Python keywords (e.g., if, def, while) as identifiers.
Valid Identifiers:
my_var = 10
_name = "Soumya"
marks123 = 95
Invalid Identifiers:
2name = "John" # Starts with digit → ❌
my-name = "John" # Contains hyphen → ❌
for = 5 # Uses keyword → ❌
✅ In Summary:
Variable: A named reference to a value.
Identifier: The name you give to variables, functions, etc., following naming
rules.
Python is dynamically typed, so variable types are inferred at runtime.
4. Data Types
In Python, data types define the kind of value a variable can hold. Python is
dynamically typed, so the type is inferred automatically based on the value assigned.
🔸 1. Numeric Types
Type Description Example
int Integer numbers a = 10
float Decimal numbers b = 3.14
complex Complex numbers c = 2 + 3j
🔸 2. Sequence Types
Type Description Example
str String of characters name = "Python"
list Ordered, mutable collection nums = [1, 2, 3]
tuple Ordered, immutable collection t = (1, 2, 3)
🔸 3. Set Types
Type Description Example
set Unordered, no duplicates s = {1, 2, 3}
frozenset Immutable set fs = frozenset([1, 2, 3])
🔸 4. Mapping Type
Type Description Example
dict Key-value pairs d = {'name': 'Alice', 'age': 25}
🔸 5. Boolean Type
Type Description Example
bool Logical values flag = True
🔸 6. Binary Types
Type Description Example
bytes Immutable byte sequence b = b'hello'
bytearray Mutable byte sequence ba = bytearray(b'hello')
memoryview View object on byte data mv = memoryview(b'abc')
🔸 7. None Type
Type Description Example
None Represents no value/null x = None
✅ Summary Table:
Type Category Types
Numeric int, float, complex
Sequence str, list, tuple
Set set, frozenset
Mapping dict
Boolean bool
Binary bytes, bytearray, memoryview
Special NoneType
5. Input Operations
In Python, input operations are used to take user input from the keyboard during
program execution.
🔸 Using input() Function
input() reads a line of text as a string.
You can convert the input to other data types using typecasting.
✅ Syntax:
variable = input("Prompt message")
🔸 Examples:
1. Basic String Input
name = input("Enter your name: ")
print("Hello", name)
2. Integer Input
age = int(input("Enter your age: "))
print("Next year you will be", age + 1)
3. Float Input
price = float(input("Enter price: "))
print("Price with tax:", price * 1.18)
🔸 Multiple Inputs (Using split())
x, y = input("Enter two numbers: ").split()
print("Sum:", int(x) + int(y))
🔸 Using eval() for Expression Input
expr = input("Enter a math expression: ") # e.g., 3 + 4
result = eval(expr)
print("Result =", result)
⚠️Use eval() carefully as it executes arbitrary code.
✅ Summary:
input() always returns a string.
Use int(), float() etc. for type conversion.
Use split() to take multiple inputs.
6. Comments
Comments are lines in the code that are not executed by Python. They are used to:
Explain the logic of code
Improve readability
Disable code temporarily during debugging
🔸 Types of Comments
✅ 1. Single-line Comment
Begins with a # symbol.
Everything after # on that line is ignored by the interpreter.
Example:
# This is a single-line comment
print("Hello") # This prints a greeting
✅ 2. Multi-line Comment
Python does not have a dedicated multi-line comment syntax, but triple quotes ''' or """
can be used as docstrings or informal block comments.
Example:
'''
This is a multi-line comment
used to describe the code block
'''
print("Python")
🔸 Note: Technically, triple-quoted strings are not real comments — they are string
literals not assigned to a variable. Python ignores them if not used as docstrings.
🔸 Best Practices:
Use comments to explain why, not what.
Keep comments concise and relevant.
Update comments as code changes.
✅ Summary:
Type Syntax Example
Single-line # # This is a comment
Multi-line '''...''' or """...""" ''' Multi-line comment '''
7. Reserved Words
Keywords like: if, else, while, for, def, return, lambda, try, import, etc.
Reserved words, also called keywords, are special words that are predefined in Python
and cannot be used as identifiers (variable names, function names, etc.). These words
have special meanings and are used to define the syntax and structure of Python
programs.
🔸 Examples of Python Keywords:
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
🔹 Total: 35 keywords in Python 3.x (as of latest versions)
🔸 Using the keyword Module
You can list all keywords in your version of Python using:
import keyword
print(keyword.kwlist)
🔸 Examples in Code:
# Correct usage
if True:
print("This is true")
# Incorrect usage: using a keyword as a variable
# def = 5 ❌ SyntaxError
✅ Summary:
Feature Description
What are they? Predefined, reserved words in Python
Can you use them? ❌ Cannot be used as variable or function names
How to list? Use import keyword; print(keyword.kwlist)
8. Indentation
Used to define blocks of code.
Example:
if True:
print('Yes')
Indentation refers to the spaces or tabs used at the beginning of a line to define the
structure and hierarchy of code blocks in Python.
🔸 Why Indentation is Important:
Unlike other languages (like C, Java, etc.), Python uses indentation to define
blocks of code instead of braces {}.
Consistent indentation is required, or Python will raise an IndentationError.
🔸 Basic Example:
if True:
print("This is indented") # Inside the if-block
print("This is outside") # Outside the block
🔸 Incorrect Indentation (Error):
if True:
print("Hello") # ❌ IndentationError: expected an indented block
🔸 Loops and Functions with Indentation:
def greet(name):
print("Hello", name) # Indented inside function
for i in range(3):
print(i) # Inside for-loop
🔸 Best Practices:
Use 4 spaces per indentation level (PEP 8 recommendation).
Do not mix tabs and spaces in the same file.
✅ Summary:
Feature Description
Purpose Defines code blocks
Required? ✅ Yes, mandatory in Python
Common Standard 4 spaces per indentation level
Feature Description
Error if misused IndentationError or unexpected behavior
9. Operators and Expressions
• Arithmetic: +, -, *, /, %, **, //
• Comparison: ==, !=, <, >, <=, >=
• Logical: and, or, not
• Bitwise: &, |, ^, ~
• Membership: in, not in
• Identity: is, is not
10. Operations on Strings
s = 'Python'
print(s.upper()), print(s[0:3]), print(len(s))
11. Other Data Types
• List: [1, 2, 3]
• Tuple: (1, 2, 3)
• Set: {1, 2, 3}
• Dictionary: {'a': 1, 'b': 2}
12. Conditional Branching Statements
if condition:
...
elif condition:
...
else:
...
13. Loop Structures
• for i in range(5): ...
• while condition: ...
14. Break, Continue, Pass, Else in Loops
for i in range(5):
if i == 2: break
elif i == 1: continue
else: pass
else:
print('Done')
15. Functions
def greet(name):
return 'Hello ' + name
print(greet('Soumya'))
16. Variable Scope and Lifetime
• Local: Inside function
• Global: Outside all functions
• Nonlocal: In nested functions
17. Return Statement
def add(x, y):
return x + y
18. More on Defining Functions
def greet(name='Guest'):
print('Hello', name)
def func(*args, **kwargs):
pass
19. Lambda Functions
add = lambda x, y: x + y
print(add(2, 3))
20. Recursive Functions
def fact(n):
if n==0: return 1
return n * fact(n-1)
21. Modules and Packages
import math
print(math.sqrt(16))
Packages are collections of modules with __init__.py
22. globals(), locals(), reload()
globals(): returns global scope
locals(): returns local scope
reload(): reload a module (use from importlib import reload)