0% found this document useful (0 votes)
19 views3 pages

Python Codebook: Beginner to Advanced

The document is a Python practice codebook that covers various phases from beginner to advanced topics. It includes basic syntax, core Python concepts, object-oriented programming, mini projects, and specialization starters like Flask and Matplotlib. Each phase contains practical code examples for learners to practice and understand Python programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views3 pages

Python Codebook: Beginner to Advanced

The document is a Python practice codebook that covers various phases from beginner to advanced topics. It includes basic syntax, core Python concepts, object-oriented programming, mini projects, and specialization starters like Flask and Matplotlib. Each phase contains practical code examples for learners to practice and understand Python programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Practice Codebook - Beginner to Advanced

Phase 1: Python Basics

1. Hello World & Input


print("Hello World")
name = input("Enter your name: ")
print("Welcome,", name)

2. Sum of Two Numbers


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Sum:", a + b)

3. Even or Odd
n = int(input("Enter a number: "))
print("Even" if n % 2 == 0 else "Odd")

4. Multiplication Table
n = int(input("Enter a number: "))
for i in range(1, 11):
print(n, "x", i, "=", n * i)

Phase 2: Core Python

1. Function to Find Factorial


def fact(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
print(fact(5))

2. Reverse List
nums = [1, 2, 3, 4]
print("Reversed:", nums[::-1])

3. Handle Division Exception


try:
a = int(input("Enter number: "))
b = int(input("Enter divisor: "))
print("Result:", a / b)
except ZeroDivisionError:
print("Cannot divide by zero")

4. Lambda with Map


nums = [1, 2, 3, 4]
squares = list(map(lambda x: x*x, nums))
print(squares)
Python Practice Codebook - Beginner to Advanced

Phase 3: OOP in Python

1. Class and Object


class Car:
def __init__(self, brand):
[Link] = brand

def drive(self):
print([Link], "is driving")

c1 = Car("Toyota")
[Link]()

2. Inheritance
class Animal:
def sound(self):
print("Animal Sound")

class Dog(Animal):
def sound(self):
print("Bark!")

d = Dog()
[Link]()

Phase 4: Mini Projects

1. Guess the Number


import random
secret = [Link](1, 10)
guess = int(input("Guess (1-10): "))
print("Correct!" if guess == secret else "Wrong! Number was", secret)

2. Simple Calculator
def calc(a, b, op):
if op == '+': return a + b
elif op == '-': return a - b
elif op == '*': return a * b
elif op == '/': return a / b
else: return "Invalid"
print(calc(10, 5, '*'))

Phase 5: Specialization Starters

1. Flask Hello World


from flask import Flask
app = Flask(__name__)
@[Link]('/')
def home():
Python Practice Codebook - Beginner to Advanced

return "Hello from Flask!"

2. Matplotlib Example
import [Link] as plt
x = [1, 2, 3]
y = [2, 4, 6]
[Link](x, y)
[Link]()

Common questions

Powered by AI

Python handles division to avoid runtime errors by using exception handling with try-except blocks to catch specific exceptions such as ZeroDivisionError. This allows the code to manage and respond gracefully to situations where division by zero might occur, printing a custom message like 'Cannot divide by zero' instead of allowing the program to crash .

Inheritance in Python allows a class (child class) to inherit attributes and methods from another class (parent class). This promotes code reusability and hierarchical classification. For example, the class 'Dog' inherits from the class 'Animal', overriding the 'sound' method to print 'Bark!' instead of the generic 'Animal Sound', thus demonstrating polymorphism by modifying specific behavior .

Users can determine if a number is even or odd by using the modulus operator %. A number is even if 'n % 2' equals 0, indicating no remainder when divided by 2. Otherwise, it is odd. The program requests user input for a number, applies this logic, and prints 'Even' or 'Odd' accordingly .

A multiplication table in Python is created using a for loop that iterates through a specified range, typically from 1 to 10. The user input number is multiplied by each iterator, and the results are printed in a structured format using print statements. This provides a simple way to display calculated multiplication values for each integer in the range .

Lambda functions are anonymous functions defined using the lambda keyword. When used with the map function, they provide a concise way to apply a function to each item in an iterable. For instance, using lambda to square numbers in a list involves mapping the lambda function 'lambda x: x*x' over the list, which returns a list of squared numbers .

Reversing a list in Python can be significant for algorithms where order matters or for presenting data in reverse chronological order. Practical scenarios include sorting historical events from most recent to least, reversing travel itineraries, or manipulating stack-like data structures where the last-in element is processed first. The reverse operation can be easily performed using slicing like 'nums[::-1]' .

Python calculates the factorial of a number using a function that initializes a result variable to 1. It employs a for loop that iterates from 2 to the user-input number (n) inclusive, multiplying the result by each iterator, 'i', which cumulatively calculates the factorial. This iterative process efficiently computes the factorial value by sequential multiplication .

Flask is a lightweight web framework in Python used to build web applications. To create a simple web application, you define a function in Flask that returns a response 'Hello from Flask!' This function is linked to a specific URL path ('/') using the @app.route decorator, which handles HTTP GET requests to that URL, allowing users to access the 'Hello World' message when visiting the app's root URL .

A 'Guess the Number' game in Python randomly generates a secret number using the random module's 'randint' function, covering a specified range (e.g., 1 to 10). The user is prompted to guess the number through input. Their guess is compared to the secret number, and a conditional statement checks for equality, printing 'Correct!' for a match or revealing the correct number otherwise .

Exception handling in Python manages errors that occur during execution, preventing full program termination upon encountering exceptions like division by zero. By wrapping the division operation in a try block and catching the ZeroDivisionError exception in an except block, the program can gracefully notify users of invalid operations without crashing, thus maintaining control flow and informing users with custom messages .

You might also like