Download Python Programming: A Beginner's Guide and more Exams Computer Science in PDF only on Docsity!
Python Programming: A Beginner to Intermediate
Guide
Classroom Notes by chetna gour Senior Instructor
Over a decade of teaching experience in Computer Science
SECTION 1: INTRODUCTION TO PYTHON
What is Python?
Think of Python as a translator between you and your computer. You give it
instructions in a language that's relatively close to English, and Python converts
those instructions into the machine code (1s and 0s) that the computer's
processor understands. It's a high-level, interpreted, general-purpose
programming language.
History and Features
Python was created by Guido van Rossum and first released in 1991. The name
comes not from the snake, but from the British comedy series Monty Python's
Flying Circus, which Guido enjoyed.
Key Features That Make Python Special:
1. Readability: Python code often looks like plain English. It uses indentation
(whitespace) to define code blocks, which forces clean, readable
structure.
2. python
# Compare a simple task in two styles
# Less readable style (not Python):
if (x> 10 ) { print("Large"); }
# Python's readable style:
if x > 10 :
3. print("Large")
4. Interpreted: You don't need to compile your code before running it. The
Python interpreter reads and executes your code line-by-line. This makes
testing and debugging faster.
5. Dynamically Typed: You don't need to declare the type of a variable (like
int or string ). Python figures it out when you assign a value.
6. python
age = 25 # Python knows it's an integer
7. name = "Alice" # Python knows it's a string
8. Vast Ecosystem: Python has a huge collection of free, reusable code
packages called libraries or modules for almost everything—web
development, data science, machine learning, game development, and
more.
Applications of Python
Python isn't locked into one field. Its simplicity and power make it versatile.
● Web Development: Frameworks like Django and Flask are used to build
websites like Instagram and Pinterest.
message = "Hello, World!" # Created a variable 'message' storing text
score = 95 # Created a variable 'score' storing a
number
Common Data Types:
Type Example Description
int -5, 0, 100 Integer (whole number)
float 3.14, -0.001, 2.0 Floating-point number (decimal)
str "hello", 'Python' String (text, enclosed in quotes)
bool True, False Boolean (logical value)
list [1, 2, 3] Ordered, changeable collection
tuple (1, 2, 3) Ordered, unchangeable
collection
dict {"key": "value"} Unordered key-value pair
collection
Keywords and Identifiers
● Keywords: These are Python's reserved words with special meanings. You
cannot use them as variable names. Examples: if , else , for , while , def ,
class , True , False , None.
● Identifiers: These are names you give to variables, functions, classes, etc.
(e.g., my_variable , calculate_total ).
Rules for Naming Identifiers:
1. Can contain letters (a-z, A-Z), digits (0-9), and underscores (_).
2. Must start with a letter or underscore (not a digit).
3. Case-sensitive ( Age , age , and AGE are three different variables).
4. Should be descriptive. student_name is better than sn.
Input and Output Functions
● Output: The print() function sends data to the console (screen).
● python
print("Welcome to Python!") # Prints text
print( 10 + 5 ) # Prints the result of 10+5, which is 15
name = "Bob"
● print("Hello,", name) # Prints multiple items with a
space
● Input: The input() function pauses the program and waits for the user to
type something. It always returns a string.
● python
SECTION 3: OPERATORS & EXPRESSIONS
An expression is a combination of values, variables, and operators that
computes a value (e.g., 2 + 3 ). The operator is the symbol that performs the
operation.
Arithmetic Operators
Used for basic mathematical operations.
Operator Example Result Description
+ 5 + 3 8 Addition
- 5 - 3 2 Subtraction
* 5 * 3 15 Multiplication
/ 10 / 3 3.333... Division (always gives a
float)
// 10 // 3 3 Floor/Integer Division
(drops decimal)
% 10 % 3 1 Modulus (remainder of
division)
** 2 ** 3 8 Exponentiation (2 to the
power of 3)
Relational (Comparison) Operators
Compare two values. The result is always a Boolean ( True or False ).
Operator Example Result Description
== 5 == 3 False Equal to
!= 5 != 3 True Not equal to
> 5 > 3 True Greater than
Assignment Operators
Used to assign values to variables. The basic one is =.
python
x = 10 # Simple assignment
x += 5 # Equivalent to x = x + 5 (now x is 15)
x -= 3 # Equivalent to x = x - 3 (now x is 12)
x *= 2 # Equivalent to x = x * 2 (now x is 24)
x /= 4 # Equivalent to x = x / 4 (now x is 6.0)
SECTION 4: CONTROL STRUCTURES
Programs don't always run in a straight line. Control structures let you decide the
flow of execution based on conditions or repetition.
if, if-else, Nested if
The if statement is your program's decision-maker.
python
# Basic if
age = 20
if age >= 18 :
print("You are eligible to vote.")
print("Please register.") # Notice the indentation for the block
print("This line always runs.")
# if-else
temperature = 35
if temperature > 30 :
print("It's a hot day.")
else:
print("It's not very hot.")
# if-elif-else (for multiple conditions)
score = 82
if score >= 90 :
grade = 'A'
elif score >= 75 : # Checked only if the first 'if' was False
grade = 'B'
elif score >= 60 :
grade = 'C'
else:
grade = 'F'
print("Your grade is:", grade)
count = 1
while count <= 5 :
print("Count is:", count)
count += 1 # CRUCIAL: change the condition variable, or loop runs forever!
# User-controlled loop
user_input = ""
while user_input.lower() != "quit":
user_input = input("Type something (or 'quit' to exit): ")
print("You typed:", user_input)
break, continue, pass
These are loop control statements.
● break : Immediately exits the entire loop it is in.
● python
for num in range( 10 ):
if num == 5 :
break
● print(num) # Prints: 0 1 2 3 4
● continue : Skips the rest of the code inside the loop for the current
iteration and jumps to the next iteration.
● python
for num in range( 5 ):
if num == 2 :
continue
● print(num) # Prints: 0 1 3 4 (skips 2)
● pass : A "do nothing" placeholder. Used when syntax requires a statement
but you don't want to execute any code.
● python
for num in range( 5 ):
if num == 2 :
pass # Come back and add code here later
● print(num) # Prints all numbers 0 through 4
SECTION 5: FUNCTIONS
A function is a named, reusable block of code designed to perform a specific,
well-defined task.
Why use functions?
1. Avoid Repetition (DRY): Don't Repeat Yourself. Write the code once, use it
many times.
2. Improve Readability: Break a complex program into smaller,
understandable pieces.
3. Simplify Debugging: Isolate problems to a specific function.
4. Promote Reuse: Use the same function in different parts of your program,
or even in different programs.
User-Defined Functions
def add_numbers(a, b):
result = a + b
return result # Sends the value back
sum_result = add_numbers( 5 , 3 ) # Captures the returned value
● print("The sum is:", sum_result) # Output: The sum is: 8
SECTION 6: DATA STRUCTURES
Containers that let you organize and store multiple items efficiently.
Lists
● Ordered, changeable, allows duplicates. Enclosed in [].
● Think of it like a train where each compartment holds an item and has a
number (index starting at 0).
● python
students = ["Alice", "Bob", "Charlie", "Alice"]
print(students[ 0 ]) # Output: Alice
students[ 1 ] = "Bobby" # Change an element
students.append("David") # Add to the end
students.remove("Alice") # Removes the first "Alice"
● print(len(students)) # Prints the length (number of items)
Tuples
● Ordered, unchangeable (immutable), allows duplicates. Enclosed in ().
● Use it for data that shouldn't change, like coordinates or constant
configurations.
● python
point = ( 10 , 20 )
colors = ("red", "green", "blue")
print(point[ 0 ]) # Output: 10
● # point[0] = 5 # ERROR! Cannot change a tuple.
Sets
● Unordered, unchangeable (but can add/remove), no duplicates. Enclosed
in {}.
● Perfect for membership testing and removing duplicates.
● python
unique_ids = { 101 , 102 , 103 , 101 } # Duplicate is automatically removed
print(unique_ids) # Output: {101, 102, 103} (order may vary)
unique_ids.add( 104 )
● print( 102 in unique_ids) # Membership test: Output: True
Dictionaries
● Unordered, changeable, indexed by unique keys (not numbers). Enclosed
in {} with key: value pairs.
● Think of it like a real-world dictionary: you look up a word (key) to find its
definition (value).
● python
line = "-" * 20 # "--------------------"
# Indexing (getting a single character)
word = "Python"
first_char = word[ 0 ] # 'P'
last_char = word[- 1 ] # 'n' (negative index counts from the end)
# Slicing (getting a substring)
# Syntax: string[start:stop:step]
slice1 = word[ 0 : 2 ] # "Py" (from index 0 up to, but not including, 2)
slice2 = word[ 2 :] # "thon" (from index 2 to the end)
slice3 = word[::- 1 ] # "nohtyP" (reverses the string)
Common String Methods
Methods are functions that "belong to" an object (like a string).
python
text = " Welcome to Python Programming "
# Case changing
print(text.upper()) # " WELCOME TO PYTHON PROGRAMMING "
print(text.lower()) # " welcome to python programming "
print(text.title()) # " Welcome To Python Programming "
# Stripping whitespace
print(text.strip()) # "Welcome to Python Programming"
# Finding and replacing
print(text.find("Python")) # Returns the index where "Python" starts
new_text = text.replace("Python", "Java")
print(new_text) # " Welcome to Java Programming "
# Splitting into a list
words = text.strip().split(" ") # Splits by space
print(words) # ['Welcome', 'to', 'Python', 'Programming']
# Checking content
print(text.startswith(" We")) # True
print("123".isdigit()) # True
print("abc".isalpha()) # True
SECTION 8: EXCEPTION HANDLING