পাঠসূচি
- 1পাইথন পরিচিতি ও ইনস্টলেশন (Python Introduction & Installation)
- 2Python Variables, Datatypes & Type Casting - পাইথন ভ্যারিয়েবল ও টাইপ কাস্টিং
- 3Python Input & Output Explained - পাইথন ইনপুট ও আউটপুট
- 4Python Operators & Expressions - পাইথন অপারেটর ও এক্সপ্রেশন
- 5Python if-elif-else Conditionals - পাইথন কন্ডিশনাল স্টেটমেন্ট
- 6Python Loops: for & while Explained - পাইথন লুপস: for ও while
- 7Python Functions: def, return, arguments - পাইথন ফাংশন ও এরগুমেন্টPlanned
- 8Python List, Tuple & Set Explained - পাইথন লিস্ট, টুপল ও সেটPlanned
- 9Python Dictionary Explained - পাইথন ডিকশনারি ব্যবহারPlanned
- 10Python Strings & String Operations - পাইথন স্ট্রিং ও অপারেশনPlanned
- 11Python File Handling Tutorial - পাইথন ফাইল হ্যান্ডলিংPlanned
- 12Python Error & Exception Handling - পাইথন এক্সেপশন হ্যান্ডলিংPlanned
- 13Python Lambda, map, filter, reduce - পাইথন ল্যাম্বডা ও ফাংশনাল প্রোগ্রামিংPlanned
- 14Python OOP: Class & Object Explained - পাইথন ক্লাস ও অবজেক্টPlanned
- 15Python Inheritance & Polymorphism - পাইথন ইনহেরিটেন্স ও পলিমরফিজমPlanned
- 16Python Modules & Packages Explained - পাইথন মডিউল ও প্যাকেজPlanned
- 17Python time, datetime & calendar - পাইথন টাইম, ডেটটাইম ও ক্যালেন্ডারPlanned
- 18Python JSON Handling - পাইথন JSON ব্যবহারPlanned
- 19Python Regular Expressions - পাইথন রেগুলার এক্সপ্রেশনPlanned
- 20Python Project: Mini Console App - পাইথন প্রজেক্ট: কনসোল অ্যাপ তৈরিPlanned
Python Loops: for & while Explained - পাইথন লুপস: for ও while
Contents
1. Introduction to Loops (লুপের পরিচিতি)
প্রোগ্রামিং-এ প্রায়শই আমাদের একই কাজ একাধিকবার করার প্রয়োজন হয়। লুপ (Loop) ব্যবহার করে আমরা কোডের একটি নির্দিষ্ট অংশকে পুনরাবৃত্তিমূলকভাবে (repeatedly) চালাতে পারি। পাইথনে প্রধানত দুই ধরনের লুপ রয়েছে:
forloop: একটি নির্দিষ্ট সিকোয়েন্স (যেমন list, tuple, string, range) এর প্রতিটি আইটেমের উপর দিয়ে পুনরাবৃত্তি করার জন্য ব্যবহৃত হয়।whileloop: একটি নির্দিষ্ট শর্ত (condition) যতক্ষণTrueথাকে, ততক্ষণ পর্যন্ত কোড ব্লকটি পুনরাবৃত্তি করার জন্য ব্যবহৃত হয়।
লুপ কোডকে সংক্ষিপ্ত, পঠনযোগ্য এবং দক্ষ করে তোলে।
2. The for Loop (for লুপ)
for লুপ একটি সিকোয়েন্সের (যেমন লিস্ট, টাপল, ডিকশনারি, সেট, স্ট্রিং বা range() ফাংশন দ্বারা তৈরি সংখ্যা ক্রম) প্রতিটি আইটেমের জন্য একবার করে কোড ব্লকটি এক্সিকিউট করে।
Syntax:
for item in sequence:
# code to execute for each item
# (এই কোডটি ইনডেন্টেড থাকবে)
Examples:
a. Iterating over a List (লিস্টের উপর পুনরাবৃত্তি):
fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
print(f"I like {fruit}")
# Output:
# I like apple
# I like banana
# I like cherry
# I like date
b. Iterating over a String (স্ট্রিং-এর উপর পুনরাবৃত্তি):
message = "Hello"
for char in message:
print(char)
# Output:
# H
# e
# l
# l
# o
c. The range() Function (range() ফাংশন):
range() ফাংশন একটি নির্দিষ্ট সীমার মধ্যে সংখ্যা ক্রম তৈরি করে, যা for লুপের সাথে প্রায়শই ব্যবহৃত হয়।
range(stop): 0 থেকেstop-1পর্যন্ত সংখ্যা তৈরি করে।range(start, stop):startথেকেstop-1পর্যন্ত সংখ্যা তৈরি করে।range(start, stop, step):startথেকেstop-1পর্যন্তstepব্যবধানে সংখ্যা তৈরি করে।
# Print numbers from 0 to 4
for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4 (each on a new line)
print("---")
# Print numbers from 2 to 5
for num in range(2, 6):
print(num) # Output: 2, 3, 4, 5
print("---")
# Print even numbers from 0 to 8
for even_num in range(0, 10, 2):
print(even_num) # Output: 0, 2, 4, 6, 8
d. Iterating over a Dictionary (ডিকশনারির উপর পুনরাবৃত্তি):
person = {"name": "Alice", "age": 30, "city": "New York"}
# Iterating over keys
print("Keys:")
for key in person:
print(key) # Output: name, age, city
# Iterating over values
print("\nValues:")
for value in person.values():
print(value) # Output: Alice, 30, New York
# Iterating over key-value pairs
print("\nKey-Value pairs:")
for key, value in person.items():
print(f"{key}: {value}")
# Output:
# name: Alice
# age: 30
# city: New York
3. The while Loop (while লুপ)
while লুপ একটি নির্দিষ্ট শর্ত True থাকা পর্যন্ত কোড ব্লকটি পুনরাবৃত্তি করে। শর্তটি প্রতিটি পুনরাবৃত্তির শুরুতে পরীক্ষা করা হয়।
Syntax:
while condition:
# code to execute as long as condition is True
# (এই কোডটি ইনডেন্টেড থাকবে)
# (গুরুত্বপূর্ণ: লুপের ভেতরে শর্তকে প্রভাবিত করার মতো কোড থাকতে হবে, নতুবা অসীম লুপ তৈরি হতে পারে)
Examples:
count = 0
while count < 5:
print(f"Count is: {count}")
count += 1 # Increment count, eventually making the condition False
# Output:
# Count is: 0
# Count is: 1
# Count is: 2
# Count is: 3
# Count is: 4
print("Loop finished.")
# Example: Sum of numbers until user enters 0
_sum = 0
num = int(input("Enter a number (0 to stop): "))
while num != 0:
_sum += num
num = int(input("Enter another number (0 to stop): "))
print(f"The sum is: {_sum}")
Infinite Loop (অসীম লুপ):
যদি while লুপের শর্ত সবসময় True থাকে, তাহলে লুপটি অসীমভাবে চলতে থাকবে। এটি সাধারণত একটি প্রোগ্রামিং ত্রুটি।
# Example of an infinite loop (DO NOT RUN UNLESS YOU KNOW HOW TO STOP IT - e.g., Ctrl+C)
# while True:
# print("This will run forever!")
4. Loop Control Statements (লুপ নিয়ন্ত্রণকারী স্টেটমেন্ট)
লুপের স্বাভাবিক প্রবাহ পরিবর্তন করার জন্য পাইথনে কিছু কন্ট্রোল স্টেটমেন্ট রয়েছে:
breakstatement: লুপটিকে অবিলম্বে থামিয়ে দেয় এবং লুপের পরবর্তী কোড থেকে এক্সিকিউশন শুরু করে।continuestatement: লুপের বর্তমান পুনরাবৃত্তির বাকি অংশ এড়িয়ে যায় এবং পরবর্তী পুনরাবৃত্তি থেকে শুরু করে।passstatement: একটি null অপারেশন। যখন সিনট্যাক্টিক্যালি একটি স্টেটমেন্টের প্রয়োজন হয় কিন্তু কোনো কোড এক্সিকিউট করার প্রয়োজন হয় না, তখনpassব্যবহৃত হয়।
a. break Statement:
# Find the first number divisible by 7 in a range
for i in range(1, 20):
if i % 7 == 0:
print(f"First number divisible by 7 is: {i}")
break # Exit the loop once the number is found
print(f"Checking {i}...")
# Output:
# Checking 1...
# Checking 2...
# Checking 3...
# Checking 4...
# Checking 5...
# Checking 6...
# First number divisible by 7 is: 7
# while loop with break
secret_number = 7
attempts = 0
while attempts < 3:
guess = int(input("Guess the secret number (1-10): "))
if guess == secret_number:
print("Congratulations! You guessed it.")
break
attempts += 1
print("Wrong guess.")
else: # This else block executes if the loop completed normally (without break)
print("Sorry, you ran out of attempts.")
b. continue Statement:
# Print only odd numbers from 0 to 9
for i in range(10):
if i % 2 == 0: # If the number is even
continue # Skip the rest of the loop body for this iteration
print(i)
# Output:
# 1
# 3
# 5
# 7
# 9
# while loop with continue
num = 0
while num < 5:
num += 1
if num == 3:
print("Skipping number 3")
continue
print(f"Processing number: {num}")
# Output:
# Processing number: 1
# Processing number: 2
# Skipping number 3
# Processing number: 4
# Processing number: 5
c. pass Statement:
pass স্টেটমেন্ট কিছুই করে না। এটি একটি placeholder হিসেবে ব্যবহৃত হয় যখন সিনট্যাক্টিক্যালি একটি স্টেটমেন্টের প্রয়োজন হয় কিন্তু কোনো কোড লেখার পরিকল্পনা এখনো হয়নি।
for i in range(5):
if i == 2:
pass # Placeholder for future code, or to explicitly do nothing
else:
print(i)
# Output: 0, 1, 3, 4
def my_function():
pass # Function defined, but implementation will be added later
class MyClass:
pass # Class defined, but attributes/methods will be added later
5. The else Clause in Loops (লুপের সাথে else ক্লজ)
পাইথনে for এবং while লুপের সাথে একটি ঐচ্ছিক else ক্লজ ব্যবহার করা যায়। এই else ব্লকটি তখনই এক্সিকিউট হয় যখন লুপটি স্বাভাবিকভাবে শেষ হয় (অর্থাৎ, break স্টেটমেন্ট দ্বারা থামানো না হলে)।
for...else:
numbers = [1, 3, 5, 9]
for num in numbers:
if num % 2 == 0:
print(f"Even number found: {num}")
break
else: # Executed if the loop completes without a break
print("No even numbers found in the list.")
# Output: No even numbers found in the list.
numbers2 = [1, 3, 4, 5, 9]
for num in numbers2:
if num % 2 == 0:
print(f"Even number found: {num}")
break
else:
print("No even numbers found in the list.")
# Output: Even number found: 4
while...else:
count = 0
while count < 3:
print(f"Attempt {count + 1}")
# Simulating a task that might succeed or fail
if count == 5: # This condition will not be met, so no break
print("Task failed, breaking loop.")
break
count += 1
else: # Executed if the loop completes without a break
print("All attempts completed successfully or loop finished normally.")
# Output:
# Attempt 1
# Attempt 2
# Attempt 3
# All attempts completed successfully or loop finished normally.
6. Nested Loops (নেস্টেড লুপ)
একটি লুপের ভেতরে আরেকটি লুপ ব্যবহার করাকে নেস্টেড লুপ বলে। এটি প্রায়শই মাল্টি-ডাইমেনশনাল ডেটা স্ট্রাকচার (যেমন, লিস্টের লিস্ট, ম্যাট্রিক্স) বা জটিল পুনরাবৃত্তিমূলক কাজের জন্য ব্যবহৃত হয়।
Example:
# Printing a simple pattern
for i in range(3): # Outer loop (rows)
for j in range(2): # Inner loop (columns)
print(f"({i}, {j})")
print("---") # Separator after each row
# Output:
# (0, 0)
# (0, 1)
# ---
# (1, 0)
# (1, 1)
# ---
# (2, 0)
# (2, 1)
# ---
# Iterating through a list of lists (matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for item in row:
print(item, end=" ") # Print items in the same line, separated by space
print() # Newline after each row
# Output:
# 1 2 3
# 4 5 6
# 7 8 9
- নেস্টেড লুপ ব্যবহার করার সময়, প্রতিটি লুপের জন্য আলাদা ভ্যারিয়েবল নাম ব্যবহার করা ভালো (যেমন,
i,j,k)। - বাইরের লুপের প্রতিটি পুনরাবৃত্তির জন্য, ভেতরের লুপটি সম্পূর্ণভাবে এক্সিকিউট হয়।
Summary
forloop: সিকোয়েন্সের প্রতিটি আইটেমের জন্য পুনরাবৃত্তি করে।range()ফাংশন প্রায়শইforলুপের সাথে ব্যবহৃত হয়।whileloop: একটি শর্তTrueথাকা পর্যন্ত পুনরাবৃত্তি করে। অসীম লুপ এড়াতে শর্ত পরিবর্তন করা গুরুত্বপূর্ণ।- Loop Control Statements:
break: লুপ থেকে অবিলম্বে বেরিয়ে যায়।continue: বর্তমান পুনরাবৃত্তির বাকি অংশ এড়িয়ে পরবর্তী পুনরাবৃত্তিতে যায়।pass: একটি null অপারেশন, placeholder হিসেবে ব্যবহৃত হয়।
elseClause in Loops: লুপ স্বাভাবিকভাবে শেষ হলে (কোনোbreakছাড়া)elseব্লক এক্সিকিউট হয়।- Nested Loops: একটি লুপের ভেতরে আরেকটি লুপ, জটিল পুনরাবৃত্তিমূলক কাজের জন্য ব্যবহৃত হয়।
Homeworks
PY6H1: Multiplication Table
- ইউজারের কাছ থেকে একটি সংখ্যা (N) ইনপুট নিন।
forলুপ ব্যবহার করে সেই সংখ্যার ১ থেকে ১০ পর্যন্ত গুণনের তালিকা (multiplication table) প্রিন্ট করুন।- উদাহরণ: যদি N=5 হয়, আউটপুট হবে:
5 x 1 = 5 5 x 2 = 10 ... 5 x 10 = 50
- উদাহরণ: যদি N=5 হয়, আউটপুট হবে:
PY6H2: Sum of Numbers with while Loop
whileলুপ ব্যবহার করে ১ থেকে একটি নির্দিষ্ট সংখ্যা N পর্যন্ত (N এর অন্তর্ভুক্ত) সকল সংখ্যার যোগফল নির্ণয় করুন। N এর মান হার্ডকোড করতে পারেন (যেমন, N=100) অথবা ইউজারের কাছ থেকে ইনপুট নিতে পারেন।
PY6H3: Guess the Number Game (Advanced)
- কম্পিউটার একটি ১ থেকে ১০০ এর মধ্যে একটি গোপন সংখ্যা
random.randint(1, 100)ব্যবহার করে তৈরি করবে (এর জন্যimport randomকরতে হবে)। - ইউজারকে সংখ্যাটি অনুমান করার জন্য ৭টি সুযোগ দিন।
- প্রতিটি অনুমানের পর, ইউজারকে বলুন তার অনুমানটি খুব বেশি (too high), খুব কম (too low), নাকি সঠিক।
- যদি ইউজার সঠিক সংখ্যা অনুমান করে, অভিনন্দন বার্তা দেখান এবং লুপ
breakকরুন। - যদি ৭টি চেষ্টার পরও ইউজার সঠিক সংখ্যা অনুমান করতে না পারে, তাহলে গোপন সংখ্যাটি দেখিয়ে দিন।
whileলুপ এবংbreakস্টেটমেন্ট ব্যবহার করুন। লুপেরelseক্লজ ব্যবহার করে দেখতে পারেন যদি ইউজার সব চেষ্টা শেষ করে ফেলে।
PY6H4: Print Patterns
- নেস্টেড
forলুপ ব্যবহার করে নিচের প্যাটার্নগুলো প্রিন্ট করুন:- Pattern 1:
* * * * * * * * * * * * * * * - Pattern 2 (Optional - একটু কঠিন):
* * * * * * * * * * * * * * *
- Pattern 1:
PY6H5: Prime Number Checker
- ইউজারের কাছ থেকে একটি পূর্ণসংখ্যা (N > 1) ইনপুট নিন।
- সংখ্যাটি মৌলিক (Prime) কিনা তা পরীক্ষা করুন। একটি সংখ্যা মৌলিক হয় যদি এটি শুধুমাত্র ১ এবং নিজেকে দিয়েই বিভাজ্য হয়।
forলুপ ব্যবহার করে ২ থেকে N-1 পর্যন্ত সংখ্যা দিয়ে N কে ভাগ করার চেষ্টা করুন। যদি কোনো সংখ্যা দ্বারা N বিভাজ্য হয়, তাহলে এটি মৌলিক নয় (breakকরতে পারেন)।- লুপের
elseক্লজ ব্যবহার করে মৌলিক কিনা তা নির্ধারণ করুন (যদি লুপbreakছাড়া শেষ হয়, তাহলে সংখ্যাটি মৌলিক)।
কোনো ভুল পেয়েছেন? LinkedIn-এ জানান।