Summary Notes

Variables in Python

Variables are named containers that store data values in computer memory. In Python, variables are created when you first assign a value to them using the assignment operator (=). Unlike many other programming languages, Python doesn't require you to declare the variable type explicitly - it determines the type automatically based on the assigned value.

Variable Naming Rules:

Examples: student_name, total_score, is_valid

Data Types

Python has several built-in data types that determine what kind of data a variable can hold and what operations can be performed on it.

You can check a variable's type using the type() function: print(type(variable_name))

Python also supports type conversion (casting) between compatible types:

Operators

Operators are special symbols that perform operations on variables and values.

Arithmetic Operators:

Comparison Operators: Used to compare values, return boolean results

Logical Operators: Used to combine conditional statements

Assignment Operators:

Control Structures

Control structures allow you to control the flow of execution in your program based on conditions or loops.

Conditional Statements (if-elif-else):

The if statement executes a block of code if a specified condition is true. You can use elif (else if) to check multiple conditions, and else to execute code when none of the conditions are true.

Indentation: Python uses indentation (whitespace) to define code blocks. All statements within the same block must have the same indentation level.

Loops:

range() function: Commonly used with for loops to generate sequences of numbers. range(start, stop, step)

Functions

Functions are reusable blocks of code that perform specific tasks. They help organize code, avoid repetition, and make programs more modular.

Defining Functions:

Function Syntax:

def function_name(parameter1, parameter2):
    # function body
    # statements
    return result

Calling Functions: Use the function name followed by parentheses containing arguments.

Parameters vs Arguments:

Return Statement: Functions can return values using the return statement. If no return statement, the function returns None.

Scope: Variables defined inside functions are local to that function. Variables defined outside are global.

Q&A

How to declare a variable in Python?
Simply assign a value: x = 5. No need to specify type - Python determines it automatically.
What is the difference between / and //?
/ is float division (5/2 = 2.5), // is integer division (5//2 = 2).
How to define a function?
def function_name(parameters): followed by indented code block.
What are the main data types in Python?
int (integers), float (decimals), str (strings), bool (True/False).
How do you check a variable's type?
Use the type() function: type(variable_name).
What is the difference between = and ==?
= is assignment operator (x = 5), == is equality comparison (x == 5).
How does Python handle indentation?
Indentation defines code blocks. Use 4 spaces or 1 tab consistently.
What is the purpose of the else clause in loops?
The else clause executes when the loop completes normally (not via break).
How do you convert between data types?
Use int(), float(), str(), bool() functions for type conversion.
What is the difference between parameters and arguments?
Parameters are in function definition, arguments are values passed when calling.
How do you return multiple values from a function?
Return them as a tuple: return value1, value2
What happens if a function doesn't have a return statement?
It returns None implicitly.
How do you use the range() function?
range(stop), range(start, stop), or range(start, stop, step).
What is variable scope?
Scope determines where a variable can be accessed. Local inside functions, global outside.
How do logical operators work?
and: both true, or: at least one true, not: reverses boolean value.
What are assignment operators?
Operators like +=, -= that combine assignment with operation (x += 3 means x = x + 3).
How do you write a multi-line string?
Use triple quotes: """multi-line string""" or '''multi-line string'''.
What is the difference between break and continue?
break exits the loop entirely, continue skips current iteration and continues.
How do you check if a number is even or odd?
Use modulo operator: if num % 2 == 0 (even) else (odd).
What are the rules for variable naming?
Start with letter/underscore, contain letters/digits/underscores, case-sensitive, no reserved words.

Fill in the Blanks

  1. In Python, variables are created by ________ a value. (assigning)
  2. The data type for whole numbers is ________. (int)
  3. The operator for exponentiation is ________. (**)
  4. A ________ loop repeats as long as a condition is true. (while)
  5. Functions are defined using the ________ keyword. (def)
  6. The ________ operator returns the remainder of division. (modulus or %)
  7. ________ division always returns a float result. (regular or /)
  8. The ________ statement is used to exit a loop prematurely. (break)
  9. ________ operators compare two values and return True or False. (comparison)
  10. The ________ function generates a sequence of numbers. (range)
  11. Variables defined inside a function are ________ scope. (local)
  12. The ________ operator combines two conditions with AND logic. (and)
  13. ________ is used to convert a string to an integer. (int())
  14. The ________ statement sends a value back from a function. (return)
  15. ________ loops are used to iterate over sequences. (for)
  16. The ________ operator checks if two values are equal. (==)
  17. ________ indentation defines code blocks in Python. (consistent)
  18. The ________ clause executes when no conditions are met. (else)
  19. ________ assignment adds a value to a variable. (+=)
  20. The ________ function checks the type of a variable. (type)

True/False

  1. Python variables must be declared with a type. (False)
  2. 5 / 2 equals 2.5 in Python 3. (True)
  3. The 'or' operator returns True if both operands are True. (False)
  4. For loops can iterate over lists. (True)
  5. Functions in Python must return a value. (False)
  6. The == operator is used for assignment. (False)
  7. Python uses indentation to define code blocks. (True)
  8. The range() function returns a list. (False - returns an iterator)
  9. Variables defined in functions are global. (False - they are local)
  10. The 'and' operator requires both conditions to be true. (True)
  11. Break statement continues to the next iteration. (False - it exits the loop)
  12. Float division uses the // operator. (False - / is float division)
  13. Strings can be enclosed in single or double quotes. (True)
  14. The modulus operator % returns the quotient. (False - it returns remainder)
  15. While loops check condition before each iteration. (True)
  16. Function parameters are required. (False - they can be optional)
  17. The += operator is shorthand for addition and assignment. (True)
  18. Boolean values are True and False (capitalized). (True)
  19. Integer division always rounds down. (True)
  20. The type() function can change a variable's type. (False - it only checks type)

Multiple Choice Questions

  1. What is the output of 3 ** 2?
    a) 6
    b) 9
    c) 8
    d) 5
    Answer: b) 9
  2. Which keyword is used to define a function?
    a) func
    b) def
    c) function
    d) define
    Answer: b) def
  3. What does the 'and' operator do?
    a) Returns True if one operand is True
    b) Returns True if both operands are True
    c) Returns True if both are False
    d) Negates the operand
    Answer: b) Returns True if both operands are True
  4. Which of these is a valid variable name?
    a) 2variable
    b) variable-name
    c) variable_name
    d) variable name
    Answer: c) variable_name
  5. What is the result of 7 // 3?
    a) 2.333
    b) 2
    c) 3
    d) 1
    Answer: b) 2
  6. Which operator checks for equality?
    a) =
    b) ==
    c) ===
    d) equals
    Answer: b) ==
  7. What does the range(1, 5) function generate?
    a) [1, 2, 3, 4]
    b) [1, 2, 3, 4, 5]
    c) [0, 1, 2, 3, 4]
    d) [2, 3, 4, 5]
    Answer: a) [1, 2, 3, 4]
  8. Which statement is used to exit a loop?
    a) exit
    b) stop
    c) break
    d) end
    Answer: c) break
  9. What is the data type of 3.14?
    a) int
    b) float
    c) str
    d) bool
    Answer: b) float
  10. Which logical operator reverses a boolean value?
    a) and
    b) or
    c) not
    d) nor
    Answer: c) not
  11. What does x += 3 do?
    a) Sets x to 3
    b) Adds 3 to x
    c) Multiplies x by 3
    d) Divides x by 3
    Answer: b) Adds 3 to x
  12. Which loop is best for iterating over a list?
    a) while loop
    b) for loop
    c) if statement
    d) switch statement
    Answer: b) for loop
  13. What does the type() function return?
    a) The value of a variable
    b) The type of a variable
    c) The memory address
    d) The variable name
    Answer: b) The type of a variable
  14. Which of these converts a string to an integer?
    a) str()
    b) int()
    c) float()
    d) bool()
    Answer: b) int()
  15. What happens if a function has no return statement?
    a) Error occurs
    b) Returns 0
    c) Returns None
    d) Returns empty string
    Answer: c) Returns None

Application Based Questions

1. Write a program to check if a number is even or odd using if-else.

Solution:

num = int(input("Enter a number: "))
if num % 2 == 0:
    print("Even")
else:
    print("Odd")

2. Create a function that calculates the area of a rectangle.

Solution:

def calculate_area(length, width):
    return length * width

# Usage
area = calculate_area(5, 3)
print(f"Area: {area}")  # Output: Area: 15

3. Write a program that prints numbers from 1 to 10 using a for loop.

Solution:

for i in range(1, 11):
    print(i)

4. Create a function to check if a number is positive, negative, or zero.

Solution:

def check_number(num):
    if num > 0:
        return "Positive"
    elif num < 0:
        return "Negative"
    else:
        return "Zero"

print(check_number(5))   # Positive
print(check_number(-3))  # Negative
print(check_number(0))   # Zero

5. Write a program to find the sum of first n natural numbers using a while loop.

Solution:

n = int(input("Enter n: "))
sum = 0
i = 1
while i <= n:
    sum += i
    i += 1
print(f"Sum of first {n} natural numbers: {sum}")

6. Create a function that converts Celsius to Fahrenheit.

Solution:

def celsius_to_fahrenheit(celsius):
    return (celsius * 9/5) + 32

temp_c = 25
temp_f = celsius_to_fahrenheit(temp_c)
print(f"{temp_c}°C = {temp_f}°F")

7. Write a program that prints the multiplication table of a given number.

Solution:

num = int(input("Enter a number: "))
for i in range(1, 11):
    print(f"{num} x {i} = {num * i}")

8. Create a function that finds the maximum of three numbers.

Solution:

def find_maximum(a, b, c):
    if a >= b and a >= c:
        return a
    elif b >= a and b >= c:
        return b
    else:
        return c

print(find_maximum(5, 8, 3))  # 8

9. Write a program to check if a year is a leap year.

Solution:

year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print(f"{year} is a leap year")
else:
    print(f"{year} is not a leap year")

10. Create a function that reverses a string.

Solution:

def reverse_string(text):
    return text[::-1]

print(reverse_string("Hello"))  # olleH

Examples

Variables and Data Types

# Integer
age = 25
print(type(age))  # 

# Float
height = 5.9
print(type(height))  # 

# String
name = "Alice"
print(type(name))  # 

# Boolean
is_student = True
print(type(is_student))  # 

# Type conversion
num_str = "123"
num_int = int(num_str)
print(num_int + 1)  # 124

Arithmetic Operators

a = 10
b = 3

print(a + b)   # Addition: 13
print(a - b)   # Subtraction: 7
print(a * b)   # Multiplication: 30
print(a / b)   # Division: 3.333...
print(a // b)  # Floor division: 3
print(a % b)   # Modulus: 1
print(a ** b)  # Exponentiation: 1000

Comparison and Logical Operators

x = 5
y = 10

print(x == y)   # False
print(x != y)   # True
print(x < y)    # True
print(x > y)    # False

# Logical operators
print(x < 10 and y > 5)  # True (both conditions true)
print(x > 10 or y > 5)   # True (one condition true)
print(not(x > 10))       # True (negation)

Assignment Operators

x = 5
print(x)  # 5

x += 3    # x = x + 3
print(x)  # 8

x -= 2    # x = x - 2
print(x)  # 6

x *= 4    # x = x * 4
print(x)  # 24

x /= 3    # x = x / 3
print(x)  # 8.0

If-Else Statements

age = 18

if age >= 18:
    print("You are an adult")
else:
    print("You are a minor")

# Multiple conditions
score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
print(f"Your grade: {grade}")

For Loops

# Iterate over range
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

# Iterate over list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)

# With range(start, stop, step)
for i in range(2, 10, 2):
    print(i)  # 2, 4, 6, 8

While Loops

count = 1
while count <= 5:
    print(f"Count: {count}")
    count += 1

# Using break and continue
num = 0
while num < 10:
    num += 1
    if num == 3:
        continue  # Skip 3
    if num == 7:
        break     # Stop at 7
    print(num)     # Prints 1, 2, 4, 5, 6

Functions

# Simple function
def greet(name):
    return f"Hello, {name}!"

print(greet("World"))  # Hello, World!

# Function with multiple parameters
def add_numbers(a, b):
    return a + b

result = add_numbers(5, 3)
print(result)  # 8

# Function with default parameter
def power(base, exponent=2):
    return base ** exponent

print(power(3))     # 9 (3^2)
print(power(3, 3))  # 27 (3^3)

# Function returning multiple values
def get_name_and_age():
    return "Alice", 25

name, age = get_name_and_age()
print(f"{name} is {age} years old")

Variable Scope

global_var = "I'm global"

def test_scope():
    local_var = "I'm local"
    print(global_var)  # Can access global
    print(local_var)   # Can access local

test_scope()
print(global_var)    # Can access global
# print(local_var)   # Error: local_var not defined

Practical Examples

# Temperature converter
def celsius_to_fahrenheit(celsius):
    return (celsius * 9/5) + 32

temp_c = 25
temp_f = celsius_to_fahrenheit(temp_c)
print(f"{temp_c}°C = {temp_f}°F")

# Simple calculator
def calculator(a, b, operation):
    if operation == "+":
        return a + b
    elif operation == "-":
        return a - b
    elif operation == "*":
        return a * b
    elif operation == "/":
        return a / b
    else:
        return "Invalid operation"

print(calculator(10, 5, "+"))  # 15
print(calculator(10, 5, "/"))  # 2.0