0% found this document useful (0 votes)
2 views10 pages

Python_Phase1_Study_Guide

The document is a comprehensive study guide for Python Phase 1, covering key concepts such as variables, data types, loops, and functions. It includes explanations, code examples, and exercises to reinforce learning. Additionally, it features a mini project that integrates all learned concepts into a practical application.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

Python_Phase1_Study_Guide

The document is a comprehensive study guide for Python Phase 1, covering key concepts such as variables, data types, loops, and functions. It includes explanations, code examples, and exercises to reinforce learning. Additionally, it features a mini project that integrates all learned concepts into a practical application.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Phase 1 — Complete Study Guide Variables | Data Types | Loops | Functions

Python
Phase 1 — Complete Study Guide
Variables Data Types Loops Functions

7 exercises • Real code examples • Hints included

SECTION 1 — VARIABLES & ASSIGNMENT

1. Variables & Assignment


A variable is a named container that stores a value. In Python, you create a variable simply by
assigning a value to a name using the = sign. Python automatically determines the type — no
declaration needed.

1.1 Creating variables


# Creating variables
name = "Ravi" # stores text (string)
age = 21 # stores a whole number (int)
height = 5.9 # stores a decimal number (float)
is_student = True # stores True or False (bool)

# Printing variables
print(name) # Ravi
print(age) # 21
print(f"Hello, {name}! You are {age} years old.")

Output:
Ravi
21
Hello, Ravi! You are 21 years old.

What is an f-string?
An f-string lets you embed variable values directly inside a string. Prefix the string with f and wrap
variables in curly braces: f"Hello, {name}".

Page N | Python Tutor — Phase 1


Python Phase 1 — Complete Study Guide Variables | Data Types | Loops | Functions

1.2 Arithmetic operators


x = 10
y = 3

print(x + y) # 13 — addition
print(x - y) # 7 — subtraction
print(x * y) # 30 — multiplication
print(x / y) # 3.333... — division (always float)
print(x // y) # 3 — floor division (drops decimal)
print(x % y) # 1 — modulo (remainder)
print(x ** y) # 1000 — power (10 to the power of 3)

Output:
13 7 30 3.333 3 1 1000

1.3 Variable naming rules


• Use letters, digits, and underscores only (e.g., student_name, age2)
• Cannot start with a digit (2name is invalid)
• Case-sensitive: Name and name are different variables
• Use snake_case for readability: first_name, not firstName

Exercise 1: Your first variable


Write a Python program that stores your name, city, and age in variables, then prints: "My name is
[name], I live in [city] and I am [age] years old."
Hint: Use an f-string: print(f"My name is {name}, I live in {city}...")

Exercise 2: Calculator practice


Create two variables a = 45 and b = 7. Print their sum, difference, product, and the remainder when a
is divided by b.
Hint: Use +, -, *, and % operators. Wrap each result in print().

SECTION 2 — DATA TYPES

2. Data Types
Python has several built-in data types. The type of a variable determines what operations you can
perform on it and how it behaves.

2.1 All data types at a glance


Type Example Description
int age = 21 Whole numbers
float price = 9.99 Decimal numbers

Page N | Python Tutor — Phase 1


Python Phase 1 — Complete Study Guide Variables | Data Types | Loops | Functions

str name = "Ravi" Text / string


bool active = True True or False
list [1, 2, 3] Ordered, changeable collection
tuple (10, 20, 30) Ordered, unchangeable collection
dict {"key": "val"} Key-value pairs
set {1, 2, 3} Unique unordered values

2.2 Strings — working with text


name = "Ravi Shankar"

print([Link]()) # RAVI SHANKAR


print([Link]()) # ravi shankar
print([Link]()) # ['Ravi', 'Shankar']
print(len(name)) # 12
print(name[0]) # R (indexing starts at 0)
print(name[0:4]) # Ravi (slicing)
print([Link]("Ravi", "Kumar")) # Kumar Shankar

Output:
RAVI SHANKAR
ravi shankar
['Ravi', 'Shankar']
12 R Ravi Kumar Shankar

2.3 Lists — ordered collections


A list holds multiple values in order. You can add, remove, and change items freely.
fruits = ["apple", "banana", "mango"]

print(fruits[0]) # apple (first item)


print(fruits[-1]) # mango (last item)
print(fruits[0:2]) # ['apple', 'banana'] (slice)

[Link]("grape") # add to end


[Link](1, "kiwi") # insert at position 1
[Link]("banana") # remove by value
print(len(fruits)) # 4
print(fruits)

Output:
apple
mango
['apple', 'banana']
4
['apple', 'kiwi', 'mango', 'grape']

2.4 Dictionaries — key-value pairs


A dictionary stores data as key-value pairs. Use a key to look up its value — like looking up a word in a
dictionary.

Page N | Python Tutor — Phase 1


Python Phase 1 — Complete Study Guide Variables | Data Types | Loops | Functions

student = {
"name": "Ravi",
"age": 21,
"city": "Coimbatore"
}

print(student["name"]) # Ravi
student["grade"] = "A" # add a new key-value pair
print([Link]()) # all keys
print([Link]()) # all values
print("age" in student) # True — check if key exists

Output:
Ravi
dict_keys(['name', 'age', 'city', 'grade'])
dict_values(['Ravi', 21, 'Coimbatore', 'A'])
True

2.5 Type checking & conversion


x = 42
y = 3.14
s = "100"

print(type(x)) # <class 'int'>


print(type(y)) # <class 'float'>
print(type(s)) # <class 'str'>

# Type conversion
print(int(y)) # 3 (float to int)
print(float(x)) # 42.0 (int to float)
print(int(s) + 10) # 110 (string to int)
print(str(x)) # "42" (int to string)

Output:
<class 'int'> <class 'float'> <class 'str'>
3 42.0 110 42

Exercise 3: Student record dictionary


Create a dictionary with your name, age, and three hobbies stored as a list. Print each value
separately, and also print just the second hobby.
Hint: profile = {"name": "...", "age": ..., "hobbies": [...]} then print(profile["hobbies"][1])

SECTION 3 — LOOPS

3. Loops
Loops let you repeat a block of code multiple times. Python has two types: the for loop (iterate over a
sequence) and the while loop (repeat while a condition is true).

Page N | Python Tutor — Phase 1


Python Phase 1 — Complete Study Guide Variables | Data Types | Loops | Functions

3.1 for loop — iterate over a sequence


# Loop over a list
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)

# Loop over a range of numbers


for i in range(1, 6): # 1 to 5 (6 is excluded)
print(i, i * i) # number and its square

Output:
apple
banana
mango
1 1 2 4 3 9 4 16 5 25

3.2 while loop — repeat until condition is false


Use a while loop when you do not know in advance how many times to repeat. Always update the
condition variable inside the loop or it will run forever.
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1 # IMPORTANT: always update the variable

Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

3.3 break and continue


break stops the loop immediately. continue skips the current iteration and jumps to the next one.
for num in range(1, 10):
if num == 4:
continue # skip 4, go to next iteration
if num == 7:
break # stop the loop entirely at 7
print(num)

Output:
1 2 3 5 6

3.4 Looping through a dictionary


person = {"name": "Ravi", "age": 21, "city": "Coimbatore"}

for key, value in [Link]():


print(f"{key}: {value}")

Output:
name: Ravi

Page N | Python Tutor — Phase 1


Python Phase 1 — Complete Study Guide Variables | Data Types | Loops | Functions

age: 21
city: Coimbatore

for vs while — when to use which?


Use for when you know what to iterate over (a list, range, string, dictionary). Use while when you
repeat until a condition changes — like waiting for user input or a value to reach a threshold.

Exercise 4: Multiplication table


Write a program that prints the full multiplication table for any number (1 to 10) using a for loop and
range().
Hint: n = int(input("Enter number: ")) then for i in range(1, 11): print(f"{n} x {i} = {n*i}")

Exercise 5: Sum and max without built-ins


Given numbers = [4, 7, 2, 9, 1, 5], use a loop to find the total sum and the largest number — without
using the built-in sum() or max().
Hint: Start with total = 0 and largest = numbers[0]. Update both inside the loop.

SECTION 4 — FUNCTIONS

4. Functions
A function is a reusable, named block of code. You define it once with def and call it as many times as
you need. Functions make your code organised, readable, and avoid repetition.

4.1 Defining and calling a function


def greet(name):
return f"Hello, {name}! Welcome to Python."

message = greet("Ravi")
print(message)

def add(a, b):


return a + b

print(add(10, 25)) # 35
print(add(3.5, 1.5)) # 5.0

Output:
Hello, Ravi! Welcome to Python.
35
5.0

Page N | Python Tutor — Phase 1


Python Phase 1 — Complete Study Guide Variables | Data Types | Loops | Functions

4.2 Default parameters


You can give a parameter a default value. If the caller does not provide that argument, the default is
used.
def introduce(name, age=18): # age defaults to 18
print(f"I am {name}, aged {age}")

introduce("Priya") # uses default age — 18


introduce("Kumar", 25) # overrides default — 25

Output:
I am Priya, aged 18
I am Kumar, aged 25

4.3 Returning multiple values


def min_max(numbers):
return min(numbers), max(numbers) # returns a tuple

low, high = min_max([3, 1, 9, 4, 7])


print(f"Min: {low}, Max: {high}")

Output:
Min: 1, Max: 9

4.4 Functions with loops — combining concepts


def count_evens(numbers):
"""Count how many even numbers are in a list."""
count = 0
for num in numbers:
if num % 2 == 0:
count += 1
return count

data = [1, 2, 3, 4, 5, 6, 7, 8]
result = count_evens(data)
print(f"Even numbers found: {result}")

Output:
Even numbers found: 4

What is a docstring?
The triple-quoted string right below def is called a docstring. It describes what the function does. It is
optional but a great habit — it helps you and others understand the code later.

Exercise 6: Even or odd checker


Write a function check_even_odd(number) that returns "Even" if the number is even, and "Odd"
otherwise. Test it with 5 different numbers using a loop.
Hint: Use modulo: if number % 2 == 0: return "Even" then loop: for n in [1,2,3,4,5]: print(check_even_odd(n))

Page N | Python Tutor — Phase 1


Python Phase 1 — Complete Study Guide Variables | Data Types | Loops | Functions

Exercise 7: Grade calculator function


Write a function get_grade(score) that returns a letter grade: A (90+), B (75+), C (60+), D (45+), or F
(below 45). Test it with scores: 95, 78, 62, 44, 30.
Hint: Use if/elif/else inside the function. Start from the highest score and work downwards.

MINI PROJECT — COMBINE EVERYTHING

5. Mini Project — Student Report Card


Build a program that combines variables, lists, dictionaries, loops, and functions together. This is your
Phase 1 capstone challenge.

Project requirements
• Store 3 students, each with a name and a list of 4 subject marks (in a dictionary)
• Write a function calculate_average(marks) that returns the average of a list
• Write a function get_grade(avg) that returns A/B/C/D/F based on the average
• Loop through all students, calculate their average, get their grade, and print a neat report

Expected output format


Output:
===== Student Report Card =====
Ravi Avg: 82.5 Grade: B
Priya Avg: 91.0 Grade: A
Kumar Avg: 58.3 Grade: C
===============================
Class average: 77.3

How to approach this project


1. Start by creating the data (list of dicts). 2. Write and test calculate_average() alone. 3. Write and
test get_grade() alone. 4. Then combine them inside a loop. Build one piece at a time, not
everything at once.

QUICK REFERENCE CHEAT SHEET

6. Quick Reference Cheat Sheet

Page N | Python Tutor — Phase 1


Python Phase 1 — Complete Study Guide Variables | Data Types | Loops | Functions

Variables & operators


x = 10 name = "Ravi" flag = True pi = 3.14
x + y x - y x * y x / y x // y x % y x ** y
f"Hello {name}" # f-string
type(x) # check data type
int(x) float(x) str(x) bool(x) # type conversion

Lists
lst = ["a", "b", "c"]
lst[0] # first item
lst[-1] # last item
lst[1:3] # slice
[Link](x) # add to end
[Link](i, x) # insert at position
[Link](x) # remove by value
[Link]() # remove and return last
len(lst) # length
x in lst # True if x is in list

Dictionaries
d = {"key": "value"}
d[key] # get value
d[key] = v # set/update value
[Link]() # all keys
[Link]() # all values
[Link]() # key-value pairs
key in d # True if key exists
[Link](key, default) # safe get with fallback

Loops
for item in list: # iterate over list
for i in range(n): # 0 to n-1
for i in range(a, b): # a to b-1
for k, v in [Link](): # dict loop
while condition: # repeat while true
break # exit loop
continue # skip to next iteration

Functions
def function_name(param1, param2='default'):
"""Docstring describing the function."""
# body of function
return value

result = function_name(arg1, arg2) # call it

Page N | Python Tutor — Phase 1


Python Phase 1 — Complete Study Guide Variables | Data Types | Loops | Functions

Phase 1 complete!
You have covered all of Python Phase 1 — variables, data types, loops, and functions. Solve all 7
exercises and the mini project, then move on to Phase 2: OOP, file handling, and advanced Python.

Page N | Python Tutor — Phase 1

You might also like