DEV Community

Cover image for Python Basic Handbook with a Twist of Humor in 15 min 🤪
TechnoaCrats
TechnoaCrats

Posted on

Python Basic Handbook with a Twist of Humor in 15 min 🤪

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")
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

It's like Mad Libs, but your code fills in the blanks!


Boolean Variable 🤖

is_bestcoder = True  # Boolean
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

This loop is like your mom nagging you until you clean your room.

For Loop:

for i in range(10):
    print(i)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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())
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
'''
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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())
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

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!")
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

List comprehensions: making loops look fancy since forever.


Lambda Functions 🐑

Anonymous, small functions.

add = lambda x, y: x + y
print(add(5, 3))
Enter fullscreen mode Exit fullscreen mode

Lambdas are like the ninjas of functions—short and stealthy.


Modules and Imports 📦

Reusing code across scripts.

import math
print(math.sqrt(16))
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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())
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Filter:

evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

These are the guiding principles of Python, like Yoda but for coding.


Virtual Environments 🛠️

Isolate your Python projects.

python -m venv myenv
Enter fullscreen mode Exit fullscreen mode

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)