Download Python Fundamentals Study Notes: 23 Topics, Examples & Practice Questions and more Study notes Computer Science in PDF only on Docsity!
Python Beginner Learning
Notebook
Welcome to the Python Beginner Learning Notebook! This notebook is designed specifically for beginners who want to build a rock-solid, practical understanding of Python from the absolute ground up. Whether you are learning programming for the first time or wanting to rebuild your fundamental understanding before diving into Machine Learning (ML), Deep Learning (DL), and Artificial Intelligence (AI) , this notebook is your hands-on companion.
This notebook emphasizes active recall, code-first learning, and practical problem-solving. Rather than just reading explanations, you are expected to write, run, and debug code yourself.
For every topic, you will find:
- Concept : A simple, beginner-friendly 2–5 line explanation.
- Syntax : A general syntax block using clean Python code representation.
- Example : Real, simple code examples you can execute.
- Common Methods : Comprehensive tables (where applicable) detailing methods, their syntax, purpose, and a code snippet without explaining the output , so you can run the code and experience the result yourself.
- Beginner Mistakes & Best Practices : Clear highlights of common pitfalls that catch beginners off guard.
- Practice Questions : A carefully curated, progressive list of 5– questions (for normal topics) or 10–15 questions (for important topics) including implementation, debugging, output prediction, and coding exercises inspired by platforms like LeetCode, GeeksforGeeks, and HackerRank.
Table of Contents
- Variables and Data Types
- Naming Conventions (PEP 8 Basics)
- Input and Output
- Operators
- Conditional Statements
- Loops
- Strings (Important Topic)
- Lists (Important Topic)
- Tuples (Important Topic)
- Sets (Important Topic)
- Dictionaries (Important Topic)
- Functions (Important Topic)
- Lambda Functions
- List Comprehensions (Important Topic)
- Dictionary Comprehensions (Important Topic)
- Set Comprehensions (Important Topic)
- Modules and Packages
- File Handling
- Exception Handling
- *args and **kwargs
- Iterators and Generators
- Context Managers (with)
- Built-in Functions (Important Topic)
1. Variables and Data Types
Concept
In Python, variables act as named containers that store data values in your computer's memory. Python is dynamically typed , meaning you do not need to explicitly declare a variable's data type before using it; Python automatically detects the type based on the value you assign.
value True to a variable named status. On the next line, reassign the string "Completed" to the same variable status. Print the variable and its type before and after the reassignment. Explain what dynamic typing means based on this behavior.
- Integer and Float Conversion : Assign the value 9.99 to a variable decimal_num. Cast it to an integer using the int() constructor and store the result in a variable named whole_num. Print both variables. Does the conversion round the decimal or truncate it?
- Dynamic Typing Output Prediction : Predict the data type of the variable result after executing the following code. Write down your prediction before running the code to verify:
num_one = 10 num_two = 4. result = num_one + num_two
- Numeric Arithmetic : Create a float variable x with the value 2. and an integer variable y with the value 4. Multiply them together and store the result in a variable z. Predict and print the data type of z.
- Debugging Data Types : Find and fix the syntax or logical errors in the following code block:
Goal: Store a string value
message = Hello World!
Goal: Store a boolean value
is_logged_in = true
- Complex Number Check : Python supports complex numbers out of the box (e.g., 3 + 4j). Create a variable named complex_val with the value 2 + 5j. Extract its real and imaginary parts using .real and .imag attributes, and print their values and types.
- Boolean from Arithmetic : Create two variables, a = 15 and b = 20. Create a third variable is_less that stores the result of checking if a is less than b. Print is_less and its data type.
2. Naming Conventions (PEP 8 Basics)
Concept
Writing clean, readable code is just as important as writing working code. PEP 8 is Python's official style guide, defining standard rules for naming identifiers to ensure consistency. Variable and function names should write in snake_case (lowercase words separated by underscores), class names in PascalCase (capitalizing the first letter of each word), and constants in UPPERCASE_SNAKE_CASE. Identifiers cannot start with numbers, cannot contain spaces, and should avoid using Python reserved keywords like class, def, or if.
Syntax
Valid variable name (snake_case)
user_age = 30
Valid constant name (UPPERCASE)
MAX_LIMIT = 100
Valid class name (PascalCase)
class UserProfile: pass
Example
Good, readable PEP 8 naming
total_price = 450. interest_rate = 0. MAX_RETRIES = 3
Bad naming (hard to understand, non-standard style)
print(keyword.kwlist)
- Descriptive Names Redrafting : Rewrite the following variable names to make them descriptive and PEP 8 compliant, assuming they store: - The current temperature of a room in Celsius: t = 22. - Whether a user is currently subscribed to a newsletter: sub = True - A list of student names: names_list_of_students_enrolled = ["John", "Sara"]
- Constant Style Refactoring : Create a variable representing the speed of light in vacuum (299,792,458 meters per second). Name it in accordance with PEP 8 standards for constants, and write a single-line comment explaining its role.
3. Input and Output
Concept
Programs interact with users by taking input and displaying output. The print() function sends output to the screen, allowing you to format text, separate values using sep, or control line endings using end. The input() function prompts the user to type information via the keyboard, which is always returned as a String (str). To perform mathematical operations or handle sequential data from input(), you must explicitly typecast the output using constructors like int(), float(), list(), tuple(), or set().
Syntax
Output syntax
print(value1, value2, ..., sep=" ", end=" ")
Input syntax
variable = input("Prompt message: ")
Casting input
numeric_val = int(input("Enter an integer: "))
Example
Simple print with custom separator and ending
print("Python", "is", "awesome", sep="-", end="!!! ")
Reading and typecasting input
user_input = input("Enter your favorite number: ") numeric_input = int(user_input) # Typecasting string to i print("Double your number is:", numeric_input * 2)
Practice Questions (Normal Topic: 8 Questions)
- User Welcome Script : Write a script that prompts the user for their first name, last name, and birth year. Print a formatted greeting message like: "Welcome, [FirstName] [LastName]! You are approximately [CurrentYear - BirthYear] years old." (Assume the current year is 2026).
- Numeric Input and Arithmetic : Create a script that prompts the user to enter two floating-point numbers. Calculate their sum, difference, and product, and print the results with each result on a new line.
- Custom Sep and End Exercise : Write a single print() statement that prints three fruits: "Apples", "Bananas", and "Cherries". Use a comma and a space as the separator (sep=", "), and end the print with a period instead of a new line (end=". ").
- Casting Error Debugging : Run the following code block. Enter a decimal number (like 4.5) when prompted, observe the error
4. Operators
Concept
Operators are special symbols used to perform computations and operations on variables and values. Python features:
- Arithmetic Operators : +, - , *, / (float division), // (floor division
- truncates decimal), % (modulus - returns remainder), ** (exponentiation - power).
- Comparison Operators : ==, !=, <, >, <=, >= (return a boolean).
- Logical Operators : and (True if both are true), or (True if at least one is true), not (reverses boolean).
- Assignment Operators : =, +=, -=, *=, /=, //=, %=, **=.
- Membership Operators : in, not in (checks if an item exists within a sequence).
- Identity Operators : is, is not (checks if two variables refer to the exact same object in memory).
- Bitwise Operators : &, |, ^, ~, <<, >> (operates on binary bits).
Syntax
Arithmetic
result = a + b
Logical check
is_valid = (x > 5) and (y < 10)
Membership check
exists = item in sequence
Example
Exponentiation and floor division
base = 2 power = 3 print(base ** power) # 2 raised to 3
Modulus operator
print(10 % 3) # Remainder of 10 divided by 3
Membership check
fruits = ["apple", "banana", "cherry"] print("mango" not in fruits) # True
Practice Questions (Normal Topic: 8 Questions)
- Arithmetic Playground : Write a script that assigns 17 to a and 5 to b. Calculate and print: - The result of standard division (a / b) - The result of floor division (a // b) - The remainder of division (a % b) - a raised to the power of b (a ** b)
- Logical Evaluator : Predict the boolean value of the following logical expressions, then write a program to print and verify your answers:
x = True y = False z = True
expr1 = (x and not y) or (y and z) expr2 = not (x or y) and z expr3 = (x and z) or not (y or z)
- Compound Assignment Refactoring : Refactor the following arithmetic operations to use compact compound assignment operators (e.g., +=, *=, etc.):
score = 10 score = score + 5
5. Conditional Statements
Concept
Conditional statements allow your program to make decisions and execute different paths of code based on whether a condition is true or false. Python uses if to start a conditional execution block, elif (short for else-if) to check multiple conditions sequentially, and else as a fallback block if none of the preceding conditions are met. Proper indentation (standard is 4 spaces) is syntactically required in Python to define the boundaries of these code blocks.
Syntax
if condition_one:
Code block executed if condition_one is True
pass elif condition_two:
Code block executed if condition_one is False and c
pass else:
Code block executed if all conditions above are Fal
pass
Example
score = 85
if score >= 90: print("Grade: A") elif score >= 80: print("Grade: B")
elif score >= 70: print("Grade: C") else: print("Grade: F")
Practice Questions (Normal Topic: 8 Questions)
- Age Classifier : Write a script that prompts the user for their age. Classify them into one of these categories and print the classification: - Child: age < 12 - Teenager: 12 <= age < 20 - Adult: 20 <= age < 65 - Senior: age >= 65
- Leap Year Validator : Write a program that checks whether a given year input by the user is a leap year. A year is leap if it is divisible by 4, except for century years (divisible by 100) which must also be divisible by 400.
- Indentation Error Debugging : Find and resolve the structural and indentation errors in the following code block to make it compile and execute correctly:
temperature = 32 if temperature > 30: print("It is extremely hot outside!") print("Stay hydrated.") else: print("The weather is pleasant.")
- Greatest of Three Numbers : Write a program that accepts three numbers as input from the user and uses conditional statements to find and print the largest number among them without using the built-in max() function.
- Simple Calculator : Create an interactive script that accepts two numbers and an operator symbol (+, - , *, /) from the user. Use conditional checks to perform the designated operation and print the result. Include a guard condition to prevent division by zero.
- Nested Condition Challenge : Create a program that prompts the
loop immediately), continue (skips the rest of the current iteration and jumps to the next one), or pass (a placeholder statement that does nothing).
Syntax
For loop syntax
for item in sequence:
Execute code block
pass
While loop syntax
while condition:
Execute code block
pass
Example
Iterating through a range
for number in range(1, 4): print("Count:", number)
While loop with break
counter = 5 while counter > 0: if counter == 3: break print("Value:", counter) counter -= 1
Practice Questions (Normal Topic: 8 Questions)
- Sum of Natural Numbers : Write a program that prompts the user for a positive integer N. Use a loop to calculate and print the sum of all natural numbers from 1 to N.
- Reverse Countdown with While : Write a while loop that prints a countdown from 10 to 1, followed by the message "Blast off!". Ensure the loop does not run infinitely.
- Multiplication Table Generator : Prompt the user for an integer num. Generate and print the multiplication table for that number from 1 to 12. Format the output clearly (e.g., num x i = result).
- Infinite Loop Debugging : Identify the error in the following code block that causes it to run infinitely, and fix it so it terminates successfully when count reaches 5:
count = 1 while count <= 5: print("Current count is:", count)
- Prime Number Tester : Write a program that takes an integer input from the user and uses a loop to determine whether it is a prime number. Print a clear confirmation of the result.
- Even Numbers Skipper : Write a for loop that iterates through numbers from 1 to 20. Use the continue statement to skip printing even numbers, printing only odd numbers.
- Infinite Input with Break : Write a script containing a while True loop that repeatedly prompts the user to type something. The loop should only terminate when the user inputs the word "exit".
- Nested Loop Matrix : Write a nested loop that prints a 3x coordinate grid layout like this:
7. Strings
Slicing
print(sample_str[0:10]) # Extracting characters from inde print(sample_str[::-1]) # Reversing a string
Common Beginner Mistakes
- Attempting In-Place Modification : Because strings are immutable, trying to write text[0] = "M" will raise a TypeError: 'str' object does not support item assignment. If you want to modify a string, you must construct a brand new string and reassign it to the variable.
- Slicing Index Confusions : Beginners often forget that the stop index is exclusive. Slicing text[0:3] only extracts indices 0, 1, 2.
Practical Usage
Strings are used to handle textual data, parse file formats, manage user accounts, construct file paths, and communicate textual outcomes to users.
Common Methods Table
Below is a table of the most widely used string methods. You are encouraged to run these snippets yourself to observe and understand the output.
Method Syntax Purpose Code Example
upper s.upper() Converts all characters to uppercase.
"python".upp
lower s.lower() Converts all characters to lowercase.
"PYTHON".low
strip s.strip() Removes leading and trailing whitespace.
" clean ".st
replace s.replace(old, new) Replaces occurrences of a substring.
"apple".repl
split s.split(sep) Splits a string into a list of substrings.
"A,B,C".spli
join sep.join(iterable) Concatenates elements of an iterable into a string.
"-".join(["A
find s.find(sub) Returns the index of the first occurrence of sub, or -1 if not found.
"intelligenc
count s.count(sub) Counts non- overlapping occurrences of sub.
"banana".cou
startswith s.startswith(prefix) Checks if string begins with prefix (returns boolean).
"Neural".sta
endswith s.endswith(suffix) Checks if string ends with suffix (returns boolean).
"document.pd