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!
Python While Loops: Basic Structure and Examples
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
-
-
python study day - 10 For Loops in Python In Python, a for loop is used to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code repeatedly for each element in the sequence. 1. The Basic Structure of a for Loop A for loop allows you to repeat a block of code a fixed number of times, or once for each element in a sequence. Syntax: for item in sequence: # Code to execute for each item in the sequence Example: Let’s print each name in a list of Kannada cities: cities = ["Bengaluru", "Mysuru", "Hubballi", "Mangaluru"] for city in cities: print(city) Output: Bengaluru Mysuru Hubballi Mangaluru Here, cities is a list, and the for loop iterates over each item (city) in that list. 2. Using range() with for Loops The range() function generates a sequence of numbers, which you can use in a for loop when you want to repeat a block of code a specific number of times. Syntax of range(): range(start, stop, step) start: The starting value (inclusive). stop: The ending value (exclusive). step: The increment (optional, default is 1). Example: Counting from 1 to 10 for i in range(1, 11): print(i) This loop will print the numbers from 1 to 10. Output: 1 2 3 4 5 6 7 8 9 10 Example: Counting by 2s from 1 to 10 for i in range(1, 11, 2): print(i) This loop prints only the odd numbers between 1 and 10. Output: 1 3 5 7 9 3. Looping Over Strings You can also loop over each character in a string using a for loop. Example: Printing each character in a string name = "Karnataka" for letter in name: print(letter) Output: K a r n a t a k a This loop goes through the string "Karnataka" one character at a time. 4. Nested for Loops You can also have nested for loops, which means a loop inside another loop. This is useful when working with multi-level data, like lists inside lists. Example: Multiplication Table Let’s print the multiplication table from 1 to 5 using a nested for loop. for i in range(1, 6): for j in range(1, 6): print(f"{i} x {j} = {i * j}") print() # To print an empty line after each table Output: 1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 1 x 4 = 4 1 x 5 = 5 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 2 x 4 = 8 2 x 5 = 10 ... 5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 Here, the outer loop controls the first number (i), and the inner loop controls the second number (j). Together, they generate the multiplication table. 5. Using break in a for Loop The break statement is used to exit a loop early when a certain condition is met. Example: Stop the loop when you find a specific item Let’s say you are searching for a specific city in a list: cities = ["Bengaluru", "Mysuru", "Hubballi", "Mangaluru"] for city in cities: if city == "Hubballi": print(f"Found {city}!") break print(city) In this case, the loop stops when it finds "Hubballi" and prints "Found Hubballi!". Output: Bengaluru Mysuru Found Hubballi!
To view or add a comment, sign in
-
🚀 Day 3 – Python Practice Progress( 6 of 50 questions solved) Problems I practiced today: ✔ Check if a number is even or odd ✔ Find the largest of three numbers ✔ Print numbers from 1 to N ✔ Find the sum of numbers from 1 to N ✔ Check if a number is prime ✔ Check if a string is a palindrome While solving these, I practiced using: • Conditional statements • Loops (while / for) • Input validation using try–except • String slicing (for palindrome checking) 💡 One interesting concept I explored today was Python slicing: s = "python" print(s[::-1]) This reverses the string because the step -1 makes Python traverse the sequence backwards. Small problems like these are helping me build stronger problem-solving skills in Python. Looking forward to practicing more tomorrow. #Python #DataScience #Programming 1 Check if a number is even or odd. try: num1=int(input("Enter a Number : ")) if num1%2==0: print("number is even") else: print("number is odd") except ValueError: print("invalid input. Please enter a number") 2. Find the largest of three numbers. try: num1=int(input("Enter first Number: ")) num2=int(input("Enter second Number: ")) num3=int(input("Enter third Number: ")) if num1>num2 and num2>num3: print("Larget Number is :", num1) elif num2>num3 and num2>num1: print("Largest Number is :", num2) else: print("Largest Number is :", num3) except ValueError: print("invalid Input. Please enter a number") 3 Print numbers from 1 to N try: num1=int(input("Enter a Number: ")) if num1>0: s=0 while s<=num1: print(s) s=s+1; else: p=0 while p>=num1: print(p) p=p-1; except ValueError: print("invalid input, please enter a number") 4 Find the sum of numbers from 1 to N. try: num=int(input("Enter a number : ")) if num>0: s=0 i=0 while i<=num: s=s+i; i=i+1; print(s) else: p=0 q=0 while q >=num: p=p+q; q=q-1; print(p) except ValueError: print("invalid input. Enter correct Number") Check if a number is prime. try: num=int(input("Enter a number : ")) if num>1: is_prime=True i=2 while i <num: if num%i==0: is_prime=False break i=i+1 if is_prime: print("Number is prime") else: print("Number is not prime") else: print("Enter a number greater than 1") except ValueError: print("Invalid Input. enter valid number") 6. Check if a string is a palindrome. try: num=str(input("Enter a sring:")) if num==num[::-1]: print("Palindrome") else: print("not a palindrome") except ValueError: print("invalid input. Enter a string")
To view or add a comment, sign in
-
🧙♂️ Magic Methods in Python (Dunder Methods) Python is known for its powerful and flexible object-oriented features. One of the most interesting concepts in Python is Magic Methods, also called Dunder Methods (Double Underscore Methods). Magic methods allow developers to define how objects behave with built-in operations such as addition, printing, comparison, and more. These methods always start and end with double underscores (__). Example: __init__ __str__ __add__ __len__ They are automatically called by Python when certain operations are performed. --- 🔹 Why Magic Methods are Important? Magic methods help to: ✔ Customize the behavior of objects ✔ Make classes behave like built-in types ✔ Improve code readability ✔ Implement operator overloading They allow developers to write clean, powerful, and Pythonic code. --- 🔹 Commonly Used Magic Methods 1️⃣ __init__ – Constructor This method is automatically called when an object is created. class Student: def __init__(self, name): self.name = name s = Student("Vamshi") --- 2️⃣ __str__ – String Representation Defines what should be displayed when we print the object. class Student: def __init__(self, name): self.name = name def __str__(self): return f"Student name is {self.name}" s = Student("Vamshi") print(s) --- 3️⃣ __len__ – Length of Object Allows objects to work with the len() function. class Team: def __init__(self, members): self.members = members def __len__(self): return len(self.members) t = Team(["A", "B", "C"]) print(len(t)) 4️⃣ __add__ – Operator Overloading Defines how the + operator works for objects. class Number: def __init__(self, value): self.value = value def __add__(self, other): return self.value + other.value n1 = Number(10) n2 = Number(20) print(n1 + n2) 🔹 Key Takeaway Magic methods make Python classes more powerful and flexible by allowing objects to interact naturally with Python's built-in operations. Understanding magic methods helps developers write cleaner and more advanced object-oriented programs. #Python #PythonProgramming #MagicMethods #DunderMethods #OOP #Coding #LearnPython #SoftwareDevelopment
To view or add a comment, sign in
-
-
Most people learning Python struggle with one thing: Classes. This is not due to how class definitions function or their complexity, but is mainly because they are typically explained in a complicated fashion. I recently shared an article where I break down Python classes in the simplest way possible — from basics to intuition, without unnecessary jargon. Furthermore, understanding class definitions is important in Python and as such is also a requirement when writing scalable/dependable systems. If you're learning Python or transitioning into ML, this will make things much clearer. What concept in Python took you the longest to truly understand? ♻️ Repost if you’re betting on yourself this time. ➕ Follow me, Samith Chimminiyan, for such ML-related content. Learning in public 🚀 #Python #MachineLearning #DataScience #Programming #OOP #LearnToCode #Developers
To view or add a comment, sign in
-
🐍 Python Practice – Day 3 ( 14 out of 50 questions solved) Continuing my Python learning journey and focusing on strengthening problem-solving skills through small coding exercises. 📌 Problems solved today: 🔹 Count vowels in a string 🔹 Reverse a number 🔹 Print the multiplication table of a number 🔹 Find the factorial of a number 📌 List-based problems: 🔹 Find the largest element in a list 🔹 Find the second largest number in a list 🔹 Remove duplicates from a list Each exercise helps improve my understanding of loops, conditions, lists, and basic Python logic. Consistency is the key, and I’m enjoying the process of learning step by step. Looking forward to tackling more problems tomorrow! 🚀 #Python #PythonLearning #CodingPractice Day 2 Count vowels in a string. try: word=str(input("enter a string")).lower() vowel={'a','e','i','o','u'} s=0 for i in word: if i in vowel: s=s+1 print(s) except ValueError: print("Invalid input. enter string") Reverse a number. try: num1 =str(input("Enter a number: ")) num2=num1[::-1] print(num2) except ValueError: print("invalid input. enter a number") Print multiplication table of a number. try: num=int(input("enter a number")) s=1 mult=0 while s<=10: mult=num*s s=s+1 print(mult) except ValueError: print("invalid input") Find factorial of a number. try: num=int(input("enter a number")) fact=1 while num>0: fact=fact*(num) num=num-1 print(fact) except ValueError: print("invalid input") Find the largest element in a list. try: list1=[1,2,3,4,5,6,7,8,898] print(max(list1)) except ValueError: print("error occured. Please check the code") Find the second largest number in a list. try: list1=[1,2,3,4] largest=max(list1) secondlargest=float('-inf') for i in list1: if i != largest and i >secondlargest: secondlargest=i print(secondlargest) except ValueError: print("error occured. Please check the code") Remove duplicates from a list. try: list1=[1,1,2,2,3,3,4,4,5,5,6,6,7,7,8] set1=set(list1) print(list(set1)) except ValueError: print("invalid operation")
To view or add a comment, sign in
-
🚀 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
To view or add a comment, sign in
-
📦 Understanding Functions in Python When learning Python, Functions are very important concepts. Let’s understand them in an easy way. 🔹 What is a Function? A function is a block of code that performs a specific task. It helps us avoid writing the same code again and again. 👉 Think of a function like a machine — you give input, it gives output. ✅ Why we use Functions? 1. Code reusability 2. Makes code easy to understand 3. Reduces code length 🔹 Types of Functions 1️⃣ Predefined Functions These are already available in Python. Example: print("Hello World") len("Python") Here print and len are the predefined functions. 2️⃣ User-defined Functions These are created by the programmer itself. ✨ Syntax: def function_name(parameters): # code return value ✅ Example: def add(a, b): return a + b result = add(5, 3) print(result) 🔹 Types of User-defined Functions ✔ Function without Parameters def greet(): print("Hello Vinayak") greet() ✔ Function with Parameters def greet(name): print("Hello", name) greet("Vinayak") ✔ Function with Return Value def square(num): return num * num print(square(4)) 📚If you’re also learning Python, this concept will be the foundation for writing better programs.
To view or add a comment, sign in
-
🚀 Python Session 3 – Mastering Control Flow Most beginners learn Python syntax… But the real turning point in programming is learning how to control program logic. That’s exactly what I explored in Session 3 of my Python learning journey. 🐍 These concepts are the backbone of decision-making and automation in Python. 🔎 Key Topics Covered 🧠 1. if Statement – Decision Making Allows your program to execute code only when a condition is true. Example: marks = 72 if marks >= 50: print("You passed the exam") ⚖️ 2. if-else Statement – Two Possible Outcomes Example: age = 17 if age >= 18: print("Eligible to vote") else: print("Not eligible yet") This helps programs choose between two paths. 📊 3. elif Ladder – Multiple Conditions Example: score = 85 if score >= 90: print("Grade A") elif score >= 75: print("Grade B") else: print("Grade C") Used when several conditions must be evaluated. 🔁 4. for Loop – Iteration A for loop repeats a block of code for a fixed sequence of values. Example: for i in range(5): print(i) Perfect for tasks like processing datasets or repeating operations. ⏳ 5. while Loop – Condition-Based Loop Runs as long as the condition remains true. Example: count = 1 while count <= 5: print(count) count += 1 🔄 6. for-else and while-else In Python, loops can include an else block that runs when the loop finishes normally. Example: for i in range(3): print(i) else: print("Loop completed successfully") 🧩 7. pass Statement – Placeholder Sometimes a block of code is required syntactically but not implemented yet. Example: if True: pass pass acts as a temporary placeholder while developing programs. 💡 Why These Concepts Matter Control flow helps developers: ✔ Build logical programs ✔ Automate repetitive tasks ✔ Create intelligent decision-making systems Without control statements, programs would simply run line by line without logic. Drop your answer in the comments 👇 Which concept felt the most interesting while learning Python? 1️⃣ if-else 2️⃣ elif ladder 3️⃣ for loop 4️⃣ while loop 🔄 Repost to help another learner Follow along as I continue documenting my Python learning journey step by step. #Python #LearnPython #PythonProgramming #CodingBasics #ControlFlow #ProgrammingLogic #TechLearning #CodingJourney
To view or add a comment, sign in
-
How Python Reads Your Code". It explains exactly what happens behind the scenes when Python encounters a simple line of code like r = 1 + 1: Step 1: Chopping It Up First, Python takes your line of code and breaks it down into individual, bite-sized pieces. For the equation r = 1 + 1, it specifically identifies r as the variable name, = as the assignment operator, the first 1 as the first operand, + as the addition operator, and the final 1 as the second operand. Step 2: Structuring & Trimming Once the pieces are separated, Python builds a blueprint by creating a structure that shows exactly how all of these parts connect together. To make sure it works as efficiently as possible, Python then "trims the fat" by removing any unnecessary complexity from this blueprint. Step 3: Analyzing the Ingredients Next, Python looks closely at each piece to identify its specific type—for example, recognizing that the number 1 is an "Integer". After figuring out exactly what kind of data it's holding, Python selects the correct operation (or "tool") needed to handle it. Step 4: The Final Cook Finally, Python executes the operation to process the code and produce your final result. The Process at a Glance The entire workflow boils down to four simple stages: 01 Chopping: Breaking the code into pieces. 02 Structuring: Building a logical blueprint. 03 Analyzing: Identifying data types and the right tools. 04 Executing: Running the code and producing the result.
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