🚀 Excited to share my first Python project! I’ve built a simple Snake-Water-Gun game while learning the basics of Python. This project helped me understand concepts like logic building, conditionals, and randomness. 🚀 Snake-Water-Gun Game using Python As part of my learning journey in Python, I built a simple Snake-Water-Gun game (similar to Rock-Paper-Scissors). Here’s a step-by-step breakdown of how the code works: 🔹 1. Importing Required Module We use the random module to allow the computer to make a random choice. import random 🔹 2. Defining Game Logic We assign numeric values to each option: Snake → 1 Water → -1 Gun → 0 This helps simplify comparison logic. 🔹 3. Computer’s Choice The computer randomly selects one of the three values: computer = random.choice([1, -1, 0]) 🔹 4. User Input The user enters their choice as: "s" for Snake "w" for Water "g" for Gun youstr = input("Enter your choice (s/w/g): ") 🔹 5. Mapping User Input We use a dictionary to convert user input into numeric form: youDict = {"s": 1, "w": -1, "g": 0} you = youDict[youstr] 🔹 6. Reverse Mapping for Output Another dictionary helps display readable results: reverseDict = {1: "Snake", -1: "Water", 0: "Gun"} 🔹 7. Display Choices We print both the user’s and computer’s selections: print(f"You chose {reverseDict[you]} and Computer chose {reverseDict[computer]}") 🔹 8. Game Result Logic If both choices are same → Draw Otherwise, conditions decide the winner: Snake drinks water → Snake wins Gun kills snake → Gun wins Water damages gun → Water wins if computer == you: print("It's a draw") else: if (computer == -1 and you == 1) or (computer == 1 and you == 0) or (computer == 0 and you == -1): print("You win 🎉") else: print("You lose 😢") 💡 Key Learnings: Using dictionaries for efficient mapping Applying conditional logic Generating randomness in Python Structuring a simple game 📌 This small project helped me understand how logic building works in real programs. Looking forward to building more! #Python #Coding #BeginnerProjects #LearningJourney #100DaysOfCode
More Relevant Posts
-
🚀 Day 8 of Learning Python: Error Handling 💻 ✅ Back with a learning update 👉 Today I explored how Python handles errors gracefully using exception handling. This helps prevent programs from crashing and improves user experience. 🔹 Common Python Errors: ZeroDivisionError → Dividing by zeroValueError → Invalid input (e.g., text instead of number)TypeError → Wrong data type usedFileNotFoundError → File does not exist 💡 1. Simple Error Handling try: num = int(input("Enter number: ")) print(10 / num) except: print("Error occurred!")👉 Prevents the program from crashing on invalid input 💡 2. Handling Specific Errors try: num = int(input("Enter number: ")) print(10 / num) except ZeroDivisionError: print("Cannot divide by zero!") except ValueError: print("Please enter a valid number!") 💡 3. Using else try: num = int(input("Enter number: ")) except ValueError: print("Invalid input") else: print("You entered:", num)👉 else runs only when no exception occurs 💡 4. Using finally try: file = open("data.txt") except FileNotFoundError: print("File not found!") finally: print("Execution completed")👉 finally always executes (useful for cleanup) 💡 5. Handling Multiple Errors Together try: a = int(input()) b = int(input()) print(a / b) except (ValueError, ZeroDivisionError): print("Invalid input or division by zero") ⚡ Raising Your Own Error age = int(input("Enter age: ")) if age < 18: raise Exception("You must be 18+") 🔥 Custom Exception (Advanced) class MyError(Exception): pass try: raise MyError("Something went wrong") except MyError as e: print(e) ✅ Key Takeaway: Error handling makes your programs more robust, user-friendly, and professional. #Python #CodingJourney #LearnPython #30DaysOfCode #Programming
To view or add a comment, sign in
-
------------------------------------------- Day 19 of My Python Learning Journey ------------------------------------------- ==> Functions in Python Today I explored one of the most powerful concepts in Python: Functions 🔥 🔹 What are Functions? Functions are reusable blocks of code that perform a specific task. They help us write cleaner and more efficient programs. 🔹 Why do we need Functions? ✔ Reduce code repetition ✔ Improve readability ✔ Break complex problems into smaller parts ✔ Promote code reusability 🔹 Advantages of Functions ✅ Reusability ✅ Easy debugging ✅ Better structure (modular programming) ✅ Saves time and effort 💡 How to Define a Function? def function_name(parameters): # code return value 🔹 Types of Functions 👉 Built-in Functions: print(), len(), sum() 👉 User-defined Functions: Created using def 🔹 Types of Arguments in Python ✔ Default Arguments def greet(name="Guest"): print("Hello", name) ✔ Positional Arguments def add(a, b): print(a + b) ✔ Keyword Arguments def student(name, age): print(name, age) ✔ Arbitrary Arguments 👉 *args (Multiple values → Tuple) def total(*numbers): print(sum(numbers)) 👉 **kwargs (Key-value pairs → Dictionary) def details(**info): print(info) 🔥 *args vs **kwargs *args → handles multiple positional arguments (tuple) **kwargs → handles multiple keyword arguments (dictionary) def demo(*args, **kwargs): print(args) print(kwargs) demo(1, 2, 3, name="Madhava", age=20) 📌 Key Takeaway: Functions make code reusable, organized, and efficient — a must-know for every developer! ------------------ Implementation ------------------ # Day 19 - Functions in Python # 1. Default Argument def greet(name="Guest"): print("Hello", name) # 2. Positional Arguments def add(a, b): print("Sum:", a + b) # 3. Keyword Arguments def student(name, age): print("Name:", name, "| Age:", age) # 4A. Arbitrary Positional Arguments (*args) def total(*numbers): sum_val = 0 for n in numbers: sum_val += n print("Total:", sum_val) # 4B. Arbitrary Keyword Arguments (**kwargs) def details(**info): print("Details:") for key, value in info.items(): print(key, ":", value) # 5. *args vs **kwargs together def demo(*args, **kwargs): print("Args:", args) print("Kwargs:", kwargs) # Function Calls greet() greet("Madhava") add(10, 20) student(age=20, name="Madhava") total(1, 2, 3, 4, 5) details(name="Madhava", age=20, dept="CSE") demo(1, 2, 3, name="Madhava", age=20)
To view or add a comment, sign in
-
-
🚀 Day 8 to10 — Python Full Stack Training | Conditional statements 🐍 Condition statements in Python are fundamental constructs used to control the flow of execution in a program. They enable decision-making by executing specific blocks of code based on whether given conditions evaluate to True. 1️⃣ if Statement The simplest form, used to execute a block of code only when a condition is satisfied. Example: x = 10 if x > 5: print("x is greater than 5") 2️⃣ if-else Statement Provides an alternative path of execution when the condition is not satisfied. Example: x = 2 if x > 5: print("Condition is True") else: print("Condition is False") 3️⃣ if-elif-else Structure Used when multiple conditions need to be evaluated in sequence. Python executes the first block where the condition is True. Example: score = 78 if score >= 90: print("Excellent") elif score >= 75: print("Good") elif score >= 50: print("Average") else: print("Needs Improvement") 4️⃣ Multiple if Statements In some scenarios, conditions need to be evaluated independently rather than exclusively. Using multiple if statements ensures each condition is checked regardless of others. Example: x = 15 if x > 10: print("Greater than 10") if x % 5 == 0: print("Divisible by 5") 5️⃣ Nested if Statements A nested structure allows you to place one condition inside another, enabling more granular decision-making. Example: x = 18 if x > 10: if x < 20: print("x is between 10 and 20") else: print("x is 20 or more") else: print("x is 10 or less")
To view or add a comment, sign in
-
I recently explored Python Lists and how they work in real-world scenarios, and here’s what I learned 👇 Python lists are one of the most powerful and beginner-friendly data structures. They allow us to store multiple values in a single variable and work with them efficiently. In my blog, I covered: • Creating and accessing lists • Indexing and slicing • Adding, removing, and updating elements • Important methods like append(), remove(), sort(), reverse() • Real-world examples like shopping lists, student marks, and to-do lists 🔑 Key Learnings: • Lists are mutable, which makes them flexible for real-time changes • Built-in methods simplify complex operations • Lists are widely used in real-world applications and problem-solving Read the full blog here: https://lnkd.in/g5kK2jPF #Python #DataStructures #Coding #Programming #LearningInPublic #Tech #Beginners A heartfelt thanks to Vishwanath Nyathani, Raghu Ram Aduri, Kanav Bansal, and Mayank Ghai, along with my mentors Harsha Mg for their continuous guidance and motivation.
To view or add a comment, sign in
-
Day 16 / 30 - while Loops in Python What is a while Loop? A while loop keeps running its block of code as long as a condition is True. Unlike a for loop which runs a fixed number of times, a while loop runs an unknown number of times, it stops only when the condition becomes False. Perfect for situations where you don't know in advance how many repetitions you'll need. Syntax Breakdown while condition: # runs as long as condition is True # must update something to eventually make condition False while --> checks the condition before every single run condition --> any expression that evaluates to True or False How It Works, step by step Python checks the condition at the top of the loop If True --> it runs the indented block of code Goes back to the top and checks the condition again Keeps repeating until the condition becomes False When False --> exits the loop and continues the program for Loop vs while Loop for loop 1. Use when you know how many times to repeat 2. Looping over a list, range, sequence while loop 1. Use when you don't know how many times 2. Keep going until a condition changes The Infinite Loop -Most Common Mistake If your condition never becomes False, the loop runs forever, freezing your program. Always make sure something inside your loop changes the condition like incrementing a counter or taking user input so the loop can eventually stop. break and continue break - stops the loop immediately, exits even if the condition is still True continue → skips the current iteration and jumps back to the condition check Both break and continue work in for and while loops. Code Example # Count from 1 to 5 count = 1 while count <= 5: print("Count: " + str(count)) count = count + 1 # break — stop early number = 0 while number < 10: if number == 5: break # stops loop at 5 print(number) number += 1 Key Learnings ☑ A while loop runs as long as its condition is True , checks before every iteration ☑ Always update something inside the loop, counter, input, or flag or you'll get an infinite loop ☑ break exits the loop immediately when a condition is met ☑ continue skips the current iteration and jumps back to the condition check ☑ Use for when you know the count — use while when you don't Why It Matters While loops power real systems — PIN verification, login retry limits, game loops, servers waiting for requests. Anywhere your program needs to wait or keep trying until something changes, a while loop is the answer. My Takeaway A for loop is like a to-do list — you know how many items there are. A while loop is like waiting for a bus — you keep waiting until it arrives. Different tools, different situations. #30DaysOfPython #Python #LearnToCode #CodingJourney #WomenInTech
To view or add a comment, sign in
-
-
Understanding Python Objects: Mutability, Identity, and Function Arguments Introduction In this project, we explored how Python treats objects, focusing on identity, mutability, and how arguments are passed to functions. These concepts are fundamental to writing reliable and efficient Python code. id and type Every object in Python has an identity (id) and a type. The id represents the memory address where the object is stored, and the type tells us what kind of object it is. For example: IMAGE BELOW Objects with the same value may or may not share the same identity depending on how Python manages them. Mutable objects Mutable objects can be changed after creation. Lists are a classic example: IMAGE BELOW Here, both l1 and l2 point to the same list, so modifying one affects the other. Immutable objects Immutable objects cannot be changed after creation. Integers and tuples are immutable: IMAGE BELOW This produces a new tuple rather than modifying the original. Why does it matter? Understanding mutability and immutability is crucial because Python treats them differently. Mutating an object keeps its identity, while reassigning creates a new object. This distinction affects performance, memory usage, and program behavior. Function arguments When passing arguments to functions, Python passes references to objects. For mutable objects, changes inside the function affect the original: IMAGE BELOW For immutable objects, reassignment inside the function does not affect the original: IMAGE BELOW Conclusion By mastering these concepts—identity, mutability, immutability, and argument passing—you gain deeper insight into Python’s object model. This knowledge helps avoid subtle bugs and write more predictable, efficient code.
To view or add a comment, sign in
-
Python Functions Cheat Sheet --- def greet(): print("Hello! Welcome to Python Functions.") greet() Output: Hello! Welcome to Python Functions. --- def greet_user(name): print(f"Hello, {name}! How are you today?") greet_user("Hs") Output: Hello, Hs! How are you today? --- def add_numbers(a, b): return a + b result = add_numbers(5, 7) print("Sum:", result) Output: Sum: 12 --- def greet_user(name="Guest"): print(f"Hello, {name}!") greet_user() greet_user("Hs") Output: Hello, Guest! Output: Hello, Hs! --- def arithmetic_operations(a, b): sum_ = a + b diff = a - b prod = a * b return sum_, diff, prod s, d, p = arithmetic_operations(10, 5) print("Sum:", s, "Difference:", d, "Product:", p) Output: Sum: 15 Difference: 5 Product: 50 --- square = lambda x: x**2 print(square(5)) Output: 25 --- def outer(): print("This is the outer function.") def inner(): print("This is the inner function.") inner() outer() Output: This is the outer function. This is the inner function. --- def add_all(*numbers): total = 0 for num in numbers: total += num return total print(add_all(1, 2, 3, 4, 5)) Output: 15 --- def greet(name): """This function greets the user by name.""" print(f"Hello, {name}!") print(greet.doc) greet("Hs") Output: This function greets the user by name. Output: Hello, Hs!
To view or add a comment, sign in
-
🚀 Python Series – Day 15: Exception Handling (Handle Errors Like a Pro!) Yesterday, we learned how to work with files in Python 📂 Today, let’s learn how to handle errors smartly without crashing your program ⚠️ 🧠 What is Exception Handling? Exception handling is a way to manage runtime errors so your program continues running smoothly. 👉 Without it → program crashes ❌ 👉 With it → program handles error gracefully ✅ 💻 Understanding try and except try: # risky code (may cause error) except: # runs if error occurs 🔍 How it Works: ✔️ Python first executes code inside try ✔️ If NO error → except is skipped ✔️ If error occurs → Python jumps to except ⚡ Example 1 (Basic) try: num = int(input("Enter number: ")) print(10 / num) except: print("Something went wrong!") 👉 If user enters 0 or text, error is handled. 🔥 Why Avoid Only except? Using only except is not a good practice ❌ 👉 It hides the real error. ✅ Best Practice: Handle Specific Errors try: num = int(input("Enter number: ")) print(10 / num) except ZeroDivisionError: print("Cannot divide by zero!") except ValueError: print("Please enter a valid number!") ⚡ Multiple Exceptions in One Line except (ZeroDivisionError, ValueError): print("Error occurred!") 🧩 else Block (Less Known 🔥) try: num = int(input("Enter number: ")) except ValueError: print("Invalid input") else: print("No error, result:", num) 👉 else runs only if no error occurs 🔒 finally Block (Very Important) try: print("Trying...") except: print("Error") finally: print("This always runs ✅") 👉 Used for cleanup (closing files, database, etc.) 🎯 Why This is Important? ✔️ Prevents crashes ✔️ Makes programs professional ✔️ Used in real-world apps, APIs, ML projects ⚠️ Pro Tips: 👉 Always use specific exceptions 👉 Use finally for cleanup 👉 Don’t hide errors blindly 📌 Tomorrow: Modules & Packages (Organize Your Code Like a Pro) Follow me to master Python step-by-step 🚀 #Python #Coding #Programming #DataScience #LearnPython #100DaysOfCode #Tech #MustaqeemSiddiqui
To view or add a comment, sign in
-
-
Day 15/30 - for Loops in Python What is a for Loop? A for loop is used to iterate — to go through every item in a sequence one by one and execute a block of code for each item. Instead of writing the same code 10 times, you write it once and let the loop repeat it automatically. The loop stops when it has gone through every item. The Golden Rule: A for loop works on any iterable — any object Python can step through one item at a time. This includes lists, tuples, strings, dictionaries, sets, and ranges. Syntax Breakdown for item in iterable: item -> This is a temporary variable holding the current item on each loop , you name it anything in -> It's the keyword that connects the variable to the iterable , always required iterable → the collection being looped - list, tuple, string, range, dict, set 1. How It Works, Step by Step 2. Python looks at the iterable and picks the first item 3. It assigns that item to your loop variable 4. It runs the indented block of code using that item 5. It moves to the next item and repeats steps 2–3 6. When there are no more items, the loop ends automatically The range() Function The range() generates a sequence of numbers for looping. The stop value is always excluded: range(5) -> 0, 1, 2, 3, 4 range(2, 6) -> 2, 3, 4, 5 range(0, 10, 2) -> 0, 2, 4, 6, 8 range(10, 0, -1) -> 10, 9, 8 ... 1 What You Can Loop Over List → loops through each item String → loops through each character one by one Tuple → same as list — goes item by item Dictionary → loops through keys by default; use .items() for key and value Range → loops through a sequence of generated numbers Set → loops through unique items (order not guaranteed) Tip: Use a name that makes the code readable — for fruit in fruits, for name in names, for i in range(10). i is the convention for index-style loops. Key Learnings ☑ A for loop iterates through every item in a sequence — running the same block for each one ☑ range(start, stop, step) generates numbers .Stop is always excluded ☑ You can loop over lists, strings, tuples, dicts, sets, and ranges ☑ The loop variable is temporary , holds the current item on each pass ☑ Indentation matters , only the indented block runs inside the loop Why It Matters: Loops are what turn Python from a calculator into an automation tool. Processing 10,000 sales records, sending emails to every customer, checking every row in a database - all of it uses loops. Writing code once and letting it repeat is one of the most powerful ideas in programming. My Takeaway Before loops, I was writing the same thing over and over. Now I write it once and Python handles the rest. That's what automation actually means - not robots, just smart repetition. #30DaysOfPython #Python #LearnToCode #CodingJourney #WomenInTech
To view or add a comment, sign in
-
-
🔹 I recently explored how strings work in Python and how small syntax choices can make code more readable and efficient 👇 🔹 Blog Summary In this blog, I explain how Python allows strings to be defined using single quotes, double quotes, and triple quotes. I also cover when to use each approach, especially for multi-line text and writing clean, maintainable code. 🔹 Key Learnings ✔ Gained clarity on different ways to define strings in Python ✔ Learned how to handle quotes within strings effectively ✔ Understood the importance of readability in real-world coding #Python #DataStructures #MachineLearning #AI #LearningInPublic #Coding #Tech A heartfelt thanks to Vishwanath Nyathani, Raghu Ram Aduri, Kanav Bansal, and, Mayank Ghai, along with my mentors Harsha M. for their continuous guidance and motivation. Innomatics Research Labs
To view or add a comment, sign in
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development