Python Basic Handbook with a Twist of Humor 🤪
Welcome to the Python Basic Handbook! We'll explore Python concepts while sprinkling in some humor to keep things light and fun. So, grab your coffee (or tea), and let's dive in! ☕
Print Statement 📢
Description: The print()
function outputs data to the console.
print("Hello World")
It's like shouting into the void, but the void actually responds!
Variables 📝
Description: Variables store data values.
name = "technocraft27" # String
age = 19 # Integer
cgp = 9.9 # Float
Think of variables as labeled boxes where you can stash your stuff. Just don't forget where you put them!
Single Variable in One Line 🚀
print("Hello", name)
Because who has time for multiple lines? We're efficient like that!
Multiple Variables in One Line 🎩
Using formatted strings (f-strings):
print(f"Hello {name}, you are {age} years old, with a CGP of {cgp}")
It's like Mad Libs, but your code fills in the blanks!
Boolean Variable 🤖
is_bestcoder = True # Boolean
True or False? In coding, there's no room for "maybe."
If-Else Ladder 🪜
if is_bestcoder:
print("You are a great coder")
else:
print("You are a bad coder")
If you code like a pro, Python gives you a high-five. If not... well, there's always coffee!
Basic Math Operations ➕➖✖️➗
number = 18
number = number + 9 # Addition (Method 1)
number += 9 # Addition (Method 2)
number -= 9 # Subtraction
number *= 3 # Multiplication
number /= 3 # Division (returns float)
number //= 3 # Floor division (returns integer)
print('Value of number is:', number)
Math in Python is like pizza—no matter how you slice it, it's still delicious!
Typecasting 🎭
Converting one data type to another.
position = 72
position = float(position)
print("Position code:", position)
Sometimes you need to change costumes to fit the role, even if you're an integer at heart.
Taking Input From User 🎤
name = input("Enter your name: ")
print("Hello", name)
rollno = int(input("Enter your roll number: "))
print("Roll number:", rollno)
Python wants to get to know you. Don't be shy!
Logical Operators 🧠
- and: Both conditions must be True.
- or: Only one condition needs to be True.
- not: Negates the condition.
Logic in programming is like deciding whether to binge-watch a series or sleep—you often use 'or'!
Loops 🔄
While Loop:
pet_name = input("Enter your pet's name: ")
while pet_name == "":
pet_name = input("Please enter your pet's name: ")
print("Your pet's name is:", pet_name)
This loop is like your mom nagging you until you clean your room.
For Loop:
for i in range(10):
print(i)
Counting sheep to fall asleep? Nah, let's count numbers with Python!
Functions 🎢
Reusable pieces of code.
def say(value):
print("Hello", value)
text = input("Enter value: ")
say(text)
Functions are like that one friend who always has the right advice—reliable and reusable.
Lists 📜
Ordered and changeable collections.
sequence = [2, 9, 3, 5, 4]
sequence.append(7)
print(sequence)
Lists are like shopping carts—you can add or remove items, but don't forget to pay!
Tuples 🔒
Ordered and unchangeable collections.
coordinates = (10, 20)
print(coordinates)
Tuples are like a sealed envelope—once closed, you can't change what's inside.
Dictionaries 📖
Collections of key-value pairs.
marks = {"Ved": 97, "Ravi": 78, "Jay": 34, "Shiv": 86}
print(marks.keys())
print(marks.values())
Dictionaries: Because even data likes to keep things in alphabetical order.
Sets 🎲
Unordered collections with no duplicate elements.
aset = {2, 3, 4, 7, 6}
print(aset)
Sets are like party invitations—no duplicates allowed!
String Methods 🎨
Manipulating text data.
text = input("Enter Name: ")
print(text.capitalize()) # First letter uppercase
print(text.upper()) # All uppercase
print(text.lower()) # All lowercase
Because sometimes you need to SHOUT or whisper.
Multiline Strings 📝
message = '''This is a multiline string.
It can span multiple lines.
Isn't that neat?'''
print(message)
When one line isn't enough to express your code poetry.
Comments 🗯️
Single-line and multi-line comments.
# This is a single-line comment
'''
This is a
multi-line comment
'''
Comments are like the silent letters in words—they're there, but only you know why.
File Handling 📂
Writing to a File:
value = input("Message: ")
with open("text.txt", "w") as write_file:
write_file.write(value)
Saving data to a file because our brains can't remember everything!
Appending to a File:
with open("text.txt", "a") as write_file:
write_file.write(value)
Adding more to the story, one line at a time.
Reading from a File:
with open("text.txt", "r") as read_file:
print(read_file.read())
Time to see what secrets we've stored away!
Exception Handling 🚫
try:
number = int(input("Enter your number: "))
print(f"Your number is: {number}")
except Exception as e:
print(f"Something went wrong: {e}")
Errors happen. This is Python's way of saying, "It's not you; it's me."
The match
Statement 🎯
work = int(input("Name your Pokémon by order (1-3): "))
match work:
case 1:
print("It's a fire type!")
case 2:
print("It's a water type!")
case 3:
print("It's a grass type!")
case _:
print("No record found here!")
Because sometimes you gotta catch 'em all, one case at a time.
List Comprehensions 🎩
A concise way to create lists.
squares = [x**2 for x in range(10)]
print(squares)
List comprehensions: making loops look fancy since forever.
Lambda Functions 🐑
Anonymous, small functions.
add = lambda x, y: x + y
print(add(5, 3))
Lambdas are like the ninjas of functions—short and stealthy.
Modules and Imports 📦
Reusing code across scripts.
import math
print(math.sqrt(16))
Why reinvent the wheel when you can just import it?
Classes and Objects 🏭
Object-Oriented Programming basics.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print("Woof!")
my_dog = Dog("Buddy")
my_dog.bark()
Classes are like blueprints, and objects are the houses we build. Just watch out for the Big Bad Wolf!
Generators 🔄
Functions that return an iterable set of items.
def generate_numbers(n):
for i in range(n):
yield i
for number in generate_numbers(5):
print(number)
Generators: Because sometimes you need to produce numbers on demand, like a vending machine.
Decorators 🎀
Functions that modify other functions.
def shout(func):
def wrapper():
return func().upper()
return wrapper
@shout
def greet():
return "hello"
print(greet())
Decorators are like adding sprinkles to your ice cream function—makes it extra special!
Map, Filter, Reduce 🗺️
Map:
numbers = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)
Filter:
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
Map and filter are like the personal trainers of lists—helping them get in shape!
Exception Handling with Specific Exceptions 🎯
try:
result = 10 / 0
except ZeroDivisionError:
print("Can't divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")
Because dividing by zero is like trying to find a unicorn—impossible!
The Zen of Python 🧘
Type import this
in your Python interpreter.
import this
These are the guiding principles of Python, like Yoda but for coding.
Virtual Environments 🛠️
Isolate your Python projects.
python -m venv myenv
Virtual environments: Keeping your dependencies in line, so they don't throw a party without you knowing.
Conclusion 🎉
This handbook covers the basics of Python programming with a humorous twist. From variables and loops to OOP and error handling, we've sprinkled in some laughs to make learning enjoyable.
Remember, coding is like cooking—follow the recipe, but don't be afraid to add your own spice!
Happy coding! And may your bugs be few and your prints be many! 🐛➡️🚫
Top comments (0)