Tutorial on Python's Conditional Statements (If-Else) In Python allow your program to make decisions and execute specific blocks of code based on whether a given condition evaluates to True or False. They are fundamental for controlling the flow of a program and handling different inputs or scenarios. ### 1. If Statement (2:45) Purpose: The if statement is used to test a single condition and execute a block of code only if that condition evaluates to True. If the condition is False, the code block associated with the if statement is skipped, and nothing is executed. Syntax: python if condition: # Code to be executed if the condition is True Important Points: The code inside the if block must be indented. This indentation is crucial for Python to understand the code structure. Conditions typically involve comparison operators (e.g., > , < , == ) which return a True or False boolean value. Example: python age = 26 if age > 19: print("You are an adult.") # Output: You are an adult. If age was 15, there would be no output. ### 2. If-Else Statement Purpose: The if-else statement provides an alternative block of code to execute if the if condition is False. This ensures that something happens regardless of whether the initial condition is true or false, avoiding empty outputs. Syntax: python if condition: # Code to be executed if the condition is True else: # Code to be executed if the condition is False Important Points: The else block does not require a condition because it automatically executes when the if condition is false. Example: python temperature = 30 if temperature < 25: print("It's a cool day!") else: print("It's a hot day!") # Output: It's a hot day! (since 30 is not less than 25) ### 3. If-Elif-Else Statement Purpose: This statement allows for checking multiple conditions sequentially. It provides a way to handle more complex scenarios where there are several possible outcomes based on different conditions. Python checks conditions from top to bottom, executing the code block for the first True condition it encounters. Syntax: python if condition1: # Code if condition1 is True elif condition2: # Code if condition2 is True (and condition1 was False) else: # Code if all preceding conditions were False Important Points: You can have multiple elif blocks. The else block is optional but provides a fallback for all cases where no if or elif condition is met. Example: python marks = int(input("Enter your marks (out of 100): ")) if marks >= 90: print("Grade A+") elif marks >= 80: print("Grade A") elif marks >= 70: print("Grade B") else: print("Grade C") # Example Input: 77 --> Output: Grade B # Example Input: 91 --> Output: Grade A+ #Python #Programming #ConditionalStatements #IfElse #Coding #TechEducation Continue..
Python Conditional Statements: If-Else and Beyond
More Relevant Posts
-
Day 1️⃣ of my Python Journey 100 Days, 100 Projects Day 1️⃣ Topic: Working with Variables, Input, String Formatting (f-strings), and the datetime module. Before I started the Day 1 task, the course included a Python crash course video to help refresh previously learned concepts. This section served as a quick revision of the fundamentals such as variables, loops, conditionals, and the basic structure of Python programs. Going through this video helped reinforce my understanding and prepared me for the projects to be made. During this revision, I also learned about functions, which was something I didn’t previously have much prior knowledge about💔. Functions allow you to create your own reusable commands so that instead of repeating the same block of code multiple times, you can organize it into a function and call it whenever needed. I also learned that variables inside functions are known as parameters, which allow the function to accept and work with different inputs. After learning about functions, I built a small mini-project (first picture in the collage): a number guessing game. In this project, I worked with Python’s random library, specifically the randint() function, which generates a random number within a given range. The program randomly selects a number between 1 and 10, and the user is given three attempts to guess the correct number. This project helped me understand how libraries can extend Python’s functionality and how randomness can be introduced into a program. It also allowed me to combine conditional statements, loops, and user input to create a simple interactive program. I then moved on to the Day 1 main project (second picture in the collage), which was to create a simple program that welcomes a user. The program was created in the thonny IDE, because of network issues using the Google Collab website. The program asks the user for their name and favorite color using the input() function. I used f-strings to dynamically format the output so the response would be more readable and personalized. I also used title case formatting to ensure that the user’s name appears properly formatted, there are other case formatting styles like upper and lower, but since it is a sentence, I added the title case for more grammatical accuracy. To add more functionality, I imported the datetime module, which allowed the program to display the exact date and time when the user entered their information. This showed how Python programs can interact with system data to provide more context. Even though today’s project was simple, it helped me combine several concepts: functions, parameters, libraries, randomness using randint(), user input, string formatting, and modules. Looking forward to learning more and building bigger projects as the challenge continues. #Python #DataScience #100Projects #100Days0fCode #TechJourney #StudentGrowth
To view or add a comment, sign in
-
-
5 Python mistakes that slow down your code: 1. Using mutable default arguments If your function has `def func(items=[])`, that list persists across all calls. Every Python dev has debugged this at 2am. Use `None` and initialize inside the function. 2. Not using list comprehensions Writing a loop with .append() when a comprehension would be one line and faster. Comprehensions aren't just shorter - they're optimized at the bytecode level. 3. Forgetting context managers for resources Still seeing `f = open('file.txt')` and `f.close()` in production code. If an exception happens between those lines, you leak the file handle. Use `with open()` - that's what it's for. 4. Using `==` to check None, True, False `if x == None` works but `if x is None` is the correct way. Identity checks are faster and handle edge cases better. Same for boolean singletons. 5. No `if __name__ == "__main__":` guard Your script runs differently when imported vs executed directly. Guard your main execution code or your tests will have side effects. 5 Python tips that improved my code: 1. F-strings for everything If you're still using .format() or % formatting, stop. f"Hello {name}" is faster, cleaner, and reads naturally. 2. enumerate() instead of range(len()) `for i, item in enumerate(items)` is more Pythonic than manually tracking indexes. You get both the value and position. 3. dict.get() with sensible defaults `config.get('timeout', 30)` handles missing keys gracefully. No try/except blocks, no KeyError debugging. 4. Multiple assignment and unpacking Python lets you swap variables without a temp: `x, y = y, x`. Unpack lists: `first, *rest = items`. Use it. 5. Pathlib instead of os.path `Path('data') / 'file.txt'` is more intuitive than os.path.join(). It's chainable, handles Windows/Unix differences, and reads like plain English. Most Python mistakes aren't about skill - they're about not knowing the language idioms. Once you learn them, your code gets cleaner and you stop writing Java in Python syntax. #python #engineering #development
To view or add a comment, sign in
-
Day 10 of my Python journey — functions. If I had to choose the single most important concept in software engineering, it would be this: write small, focused, well-named functions. Not because it is a rule. Because it is the only practical way to manage complexity as programs grow larger. A 20-line program can be understood by reading it top to bottom. A 2,000-line program cannot — unless it is broken into functions, each doing one clear thing, each named for what it does, each testable independently. *args and **kwargs — why every Python developer needs to understand these def print_scores(*names): for name in names: print(f"Score recorded for: {name}") print_scores("Rahul") # Works print_scores("Rahul", "Priya", "Arjun") # Also works *args collects any number of positional arguments into a tuple. **kwargs collects any number of keyword arguments into a dictionary. When you call print("a", "b", "c", sep=", ") — that works because print uses *args. When Flask's @app.route("/path", methods=["GET"]) accepts options — that is **kwargs. When requests.get(url, timeout=5, verify=False) takes optional parameters — **kwargs again. Understanding these means understanding how every Python library and framework is designed from the inside. The mutable default argument trap — a famous Python gotcha # DANGEROUS — this is a silent bug def add_task(task, task_list=[]): task_list.append(task) return task_list add_task("Buy groceries") # ["Buy groceries"] — correct add_task("Call dentist") # ["Buy groceries", "Call dentist"] — WRONG The default list is created once when the function is defined. Every call shares the same list. This is one of the most well-known bugs in Python — and I learned it on Day 10. The correct approach: def add_task(task, task_list=None): then task_list = task_list or []. Docstrings — the habit I build from today def calculate_gst(amount: float, rate: float = 0.18) -> float: """Calculate GST on a given amount. Args: amount (float): base price. rate (float): GST rate, default 18%. Returns: float: the GST amount to add.""" return amount * rate Every function I write from now on has a docstring. IDEs read them for autocomplete. Documentation generators build API docs from them. Code reviewers judge them. Professional habit, built from Day 10. Functions are the architecture of every program worth reading. #Python#Day10#ConditionalLogic#SelfLearning#CodewithHarry#PythonBasics#w3schools.com#W3Schools
To view or add a comment, sign in
-
Python dict: Fast Lookups and How Collisions Are Handled The "dict" is one of the most powerful and frequently used data structures in Python. It provides average O(1) time complexity for lookups, insertions, and deletions. But how does it stay so fast? Under the hood, a Python dictionary is implemented as a hash table. When you insert a key into a dictionary, Python first computes a hash value using the "hash()" function. This hash determines where the key–value pair should be placed in the internal table. However, different keys can sometimes produce the same hash index. This situation is called a hash collision. Python handles collisions using a technique called open addressing. Instead of storing multiple elements in the same bucket (like chained hash tables), Python searches for the next available slot in the table using a probing sequence. The simplified process looks like this: 1. Compute the hash of the key 2. Map the hash to an index in the table 3. If the slot is occupied, probe another position 4. Continue probing until an empty slot or the key itself is found Python dictionaries also maintain performance by resizing the table when it becomes too full. When the load factor increases, the dictionary allocates a larger table and rehashes the existing keys. This design allows Python dictionaries to remain extremely fast even with millions of entries. Understanding how collisions are handled helps explain why "dict" is both efficient and reliable for real-world applications. What’s the most interesting thing you’ve learned about Python dictionaries?
To view or add a comment, sign in
-
🧠 Level Up Your #Python Knowledge with Real Understanding 𝗠𝗼𝘀𝘁 𝗽𝗲𝗼𝗽𝗹𝗲 𝗹𝗲𝗮𝗿𝗻𝗶𝗻𝗴 𝗣𝘆𝘁𝗵𝗼𝗻 𝗺𝗮𝗸𝗲 𝘁𝗵𝗲 𝘀𝗮𝗺𝗲 𝗺𝗶𝘀𝘁𝗮𝗸𝗲. 𝗧𝗵𝗲𝘆 𝗺𝗲𝗺𝗼𝗿𝗶𝘇𝗲 𝘀𝘆𝗻𝘁𝗮𝘅. But real-world Python development isn't built on memorizing syntax. It is built on logic, problem-solving, and understanding how code behaves under pressure. Knowing how to write a function is basic. Knowing why it breaks in production—and how to fix it—is what separates a "Coder" from a "Problem Solver." That’s exactly why we created this "𝟱𝟬𝟬 𝗣𝘆𝘁𝗵𝗼𝗻 𝗦𝗰𝗲𝗻𝗮𝗿𝗶𝗼-𝗕𝗮𝘀𝗲𝗱 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗲 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀" 𝗴𝘂𝗶𝗱𝗲. If you are aiming for that Junior → Senior or Developer → Lead promotion... you will eventually face these 10 challenges. 👇 𝗛𝗲𝗿𝗲 𝗶𝘀 𝘁𝗵𝗲 𝗿𝗲𝗮𝗹 𝗣𝘆𝘁𝗵𝗼𝗻 𝗹𝗶𝘁𝗺𝘂𝘀 𝘁𝗲𝘀𝘁: 1️⃣ What happens when you use a mutable default argument (like a list) in a function, and why does it cause unexpected behavior across multiple calls? 2️⃣ How does the yield keyword differ from return, and how does it manage memory differently in large datasets? 3️⃣ When should you use a deque instead of a list for stack/queue operations, and what performance gain do you get? 4️⃣ How do you implement a custom context manager using __enter__ and __exit__ to handle database connections safely? 5️⃣ What is the Method Resolution Order (MRO) in multiple inheritance, and how does Python use the C3 linearization algorithm to resolve conflicts? 6️⃣ How can you use functools.lru_cache to optimize a recursive function, and when does it become a memory risk? 7️⃣ What is the difference between deep and shallow copy when working with nested lists or dictionaries, and how do you control it? 8️⃣ How does the Global Interpreter Lock (GIL) affect multithreading in Python, and when would you choose multiprocessing instead? 9️⃣ How do you use __slots__ in a class to reduce memory footprint when creating thousands of instances? 🔟 What is the correct way to handle and propagate exceptions in a generator pipeline without breaking the iteration? If you can answer these with confidence—not just "I read it in a book"—you aren't just writing scripts. You are engineering robust solutions. 👇 Three ways to level up today: 🔁 Repost ♻️ to help your network move from "syntax learners" to "logic engineers." 💬 Comment "𝟱𝟬𝟬" below and DM us "𝟱𝟬𝟬" We'll send you access to then full PDF. 🧑🤝🧑 Tag a teammate who still debugs with print() instead of using a proper logger. Let's build code that actually scales. 🚀 ------------------------------------------- 𝗙𝗿𝗼𝗺 𝗡𝗼𝘁𝗵𝗶𝗻𝗴 ▶️ 𝗧𝗼 𝗡𝗼𝘄 —𝗕𝘂𝗶𝗹𝗱𝗶𝗻𝗴 𝗝𝗼𝗯-𝗥𝗲𝗮𝗱𝘆, 𝗣𝘆𝘁𝗵𝗼𝗻 𝗣𝗿𝗼𝗳𝗲𝘀𝘀𝗶𝗼𝗻𝗮𝗹𝘀 ...✈️ -------------------------------------------
To view or add a comment, sign in
-
-
python study day - 9 While Loops in Python A loop is a programming structure that repeats a set of instructions as long as a specified condition is True. In Python, the while loop allows you to repeatedly execute a block of code as long as the condition is True. 1. The Basic Structure of a while Loop The while loop repeatedly executes a block of code as long as the condition is True. Syntax: while condition: # Code to execute as long as condition is True Example: Let’s print numbers from 1 to 5 using a while loop. i = 1 while i <= 5: print(i) i += 1 # Incrementing i by 1 after each iteration The loop starts with i = 1 and checks if i <= 5. As long as this condition is True, it prints the value of i and increases it by 1 (i += 1). The loop ends when i becomes 6, as the condition i <= 5 becomes False. Output: 1 2 3 4 5 2. Common Example: Counting Sheep Let’s relate this to a common example: Imagine you're counting sheep to fall asleep. sheep_count = 1 while sheep_count <= 10: print(f"Sheep {sheep_count}") sheep_count += 1 This prints "Sheep 1", "Sheep 2", and so on, until "Sheep 10". After that, the loop stops. 3. Avoiding Infinite Loops A while loop can run indefinitely if the condition is always True. To prevent this, ensure that the condition eventually becomes False. Example of an Infinite Loop: i = 1 while i <= 5: print(i) # Forgot to update i, so the condition remains True forever! In this case, the loop will keep printing 1 forever because i is never incremented, so the condition i <= 5 will always be True. To avoid this, make sure to update the variable that controls the condition within the loop. 4. Using break to Exit a while Loop You can use the break statement to exit a loop when a certain condition is met. Example: Let’s stop counting sheep after 5 sheep, even though the condition allows counting up to 10: sheep_count = 1 while sheep_count <= 10: print(f"Sheep {sheep_count}") if sheep_count == 5: print("That's enough counting!") break sheep_count += 1 The loop stops after "Sheep 5" because of the break statement, even though the condition was sheep_count <= 10. Output: Sheep 1 Sheep 2 Sheep 3 Sheep 4 Sheep 5 That's enough counting!
To view or add a comment, sign in
-
Data Structures in Python (Types and Examples Explained) Data structures in Python help organize and store data efficiently in computer memory. They improve performance by making tasks like searching, sorting, and accessing data faster. Common examples include lists, tuples, sets, and dictionaries. Advanced structures like stacks, queues, trees, and graphs help developers manage complex data and build efficient applications. Read more here: https://lnkd.in/ggQg-Giy. #python #datastructures #pythonprogramming #computerscience #TechLearning #softwaredevelopment #ProgrammingBasics #igmguru
To view or add a comment, sign in
-
What is the use of self in Python? If you are working with Python, there is no escaping from the word “self”. It is used in method definitions and in variable initialization. The self method is explicitly used every time we define a method. The self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason why we use self is that Python does not use the ‘@’ syntax to refer to instance attributes self is used in different places and often thought to be a keyword. But unlike in C++, self is not a keyword in Python. self is a parameter in function and the user can use a different parameter name in place of it. Although it is advisable to use self because it increases the readability of code. In Python, self is the keyword referring to the current instance of a class. Creating an object from a class is actually constructing a unique object that possesses its attributes and methods. The self inside the class helps link those attributes and methods to a particular created object. Self in Constructors and Methods self is a special keyword in Python that refers to the instance of the class. self must be the first parameter of both constructor methods (__init__()) and any instance methods of a class. For a clearer explanation, see this: When creating an object, the constructor, commonly known as the __init__() method, is used to initialize it. Python automatically gives the object itself as the first argument whenever you create an object. For this reason, in the __init__() function and other instance methods, self must be the first parameter. If you don’t include self, Python will raise an error because it doesn’t know where to put the object reference. Is Self a Convention? In Python, instance methods such as __init__ need to know which particular object they are working on. To be able to do this, a method has a parameter called self, which refers to the current object or instance of the class. You could technically call it anything you want; however, everyone uses self because it clearly shows that the method belongs to an object of the class. Using self also helps with consistency; hence, others-and, in fact, you too-will be less likely to misunderstand your code. Why is self explicitly defined everytime? In Python, self is used every time you define it because it helps the method know which object you are actually dealing with. When you call a method on an instance of a class, Python passes that very same instance as the first argument, but you need to define self to catch that. By explicitly including self, you are telling Python: “This method belongs to this particular object.” What Happens Internally when we use Self? When you use self in Python, it’s a way for instance methods—like __init__ or other methods in a class—to refer to the actual object that called the method. #Python #Data_analaysis
To view or add a comment, sign in
-
Whether you want to automate repetitive tasks, analyze data, build websites, or dive into machine learning — Python is the perfect starting point. And the best way to start is by getting solid on the fundamentals. In this guide you will learn every basic Python operation through concise explanations, real code examples, and the exact output you can expect to see when you run them. No fluff, no setup headaches — just Python. #Python #DataEngineering https://lnkd.in/g6bvfhHX
To view or add a comment, sign in
-
🐍 Python Developer Series | Prepare for Your Next Opportunity — Day 1 📌 Very Common but Most Asked Python Question ❓ What is the difference between a List and a Tuple in Python? 💡 Explain it like this: In Python, the main difference between a list and a tuple is mutability. 🟢 A list is mutable, which means we can modify its elements after creation, such as adding, removing, or updating values. 🔒 A tuple is immutable, meaning once it is created its elements cannot be modified. ⚡ Because tuples are immutable, Python can optimize memory usage and access speed, so tuples are generally slightly faster than lists. 💻 From a backend development perspective, we usually use: ✔ Lists when the data needs modification 📌 Examples: storing query results, request data, or dynamic collections. ✔ Tuples when the data should remain constant 📍 Examples: database coordinates, fixed configurations, or returning multiple values from a function. ✨ Another advantage is that tuples can be used as dictionary keys because they are immutable, while lists cannot. 🧠 This is a clean and professional way to explain it as a backend developer. 🚀 Now let’s go one level deeper 👉 Why are tuples faster than lists in Python? Tuples are generally faster mainly because they are immutable. Since tuples cannot be modified after creation, Python does not need to allocate extra memory for operations like append, remove, or resize. Lists are mutable, so Python needs extra memory allocation and resizing mechanisms to support dynamic operations like append and insert. Because tuples are immutable: ⚡ Python can optimize memory usage ⚡ Tuples require less overhead ⚡ Iteration over tuples is slightly faster Another reason is that tuples are stored in a more compact memory structure, while lists store extra information to support dynamic resizing. 📊 That is why tuples are generally faster and more memory efficient than lists. 🤔 Follow-up question 👉 Can a tuple contain a mutable object? 🧩 Scenario Question (Real Project Thinking) Imagine you are building a Django API that returns latitude and longitude of a location. 📍 Why might a developer prefer a tuple instead of a list in this case? Think from a backend design perspective, not just theory. 💬 Drop your answer in the comments. 🎯 Preparing for the next opportunity 📚 Learn with me 🤝 Stay connected and keep learning #python #pythondeveloper #backenddeveloper #django #softwaredeveloper #coding #programming #learnpython #developers #softwareengineering #techcommunity #devcommunity #codinglife #learnwithme #devlife #programmingtips #careerindevelopment #opportunities #pythonlearning
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