Python Program

Unit-1: Python Program

Introduction & characteristic:

Python Program-এর পরিচয়:
Python Program হল একটি উচ্চ-স্তরের(HLL), interpreted প্রোগ্রামিং ভাষা যা 1991 সালে Guido van Rossum দ্বারা তৈরি করা হয়েছিল। এটি সহজ পাঠযোগ্য সিনট্যাক্স এবং দ্রুত শিক্ষণের জন্য পরিচিত।

Python-এর প্রধান বৈশিষ্ট্য:

  1. সহজ ও পাঠযোগ্য:
    Python-এর সিনট্যাক্স ইংরেজি ভাষার কাছাকাছি, যা এটিকে শিখতে ও ব্যবহার করতে সহজ করে তোলে। উদাহরণ:
   if age >= 18:
       print("You are eligible for vote")
  1. Interpreted:
    Python কোড লাইন-বাই-লাইন ব্যাখ্যা করে চালায়, যা ডিবাগিং সহজ করে।
  2. ডায়নামিক টাইপিং(Dynamic type):
    ভেরিয়েবলের ধরন আগে থেকে ঘোষণা করতে হয় না। উদাহরণ:
   x = 5  # x এখন একটি ইন্টিজার
   x = "hello"  # x এখন একটি স্ট্রিং
  1. বহুমুখী(Multipurpose):
    Python ওয়েব ডেভেলপমেন্ট, ডেটা সায়েন্স, AI, স্ক্রিপ্টিং ইত্যাদি বিভিন্ন ক্ষেত্রে ব্যবহৃত হয়।
  2. বিশাল লাইব্রেরি(huge in-built library):
    Python-এর বিশাল স্ট্যান্ডার্ড লাইব্রেরি রয়েছে, যা বিভিন্ন কাজের জন্য রেডিমেড ফাংশন সরবরাহ করে। উদাহরণ:
   import random
   print(random.randint(1, 10))  # 1 থেকে 10 এর মধ্যে একটি র‍্যানডম সংখ্যা প্রিন্ট করে
  1. প্ল্যাটফর্ম স্বাধীন(Platform Independent):
    Python কোড বিভিন্ন অপারেটিং সিস্টেমে (Windows, Linux, Mac) চালানো যায়।

এই বৈশিষ্ট্যগুলি Python-কে একটি শক্তিশালী ও জনপ্রিয় প্রোগ্রামিং ভাষা হিসেবে প্রতিষ্ঠিত করেছে।

Execution Mode:

Python-এর দুটি মূল এক্সিকিউশন মোড রয়েছে: ইন্টারেক্টিভ মোড(interactive mode) এবং স্ক্রিপ্ট মোড(Script mode)।

1. ইন্টারেক্টিভ মোড (interactive mode):

ইন্টারেক্টিভ মোডে, আপনি Python ইন্টারপ্রেটারের সাথে সরাসরি যোগাযোগ করতে পারেন।

বৈশিষ্ট্য:

  • কোড লাইন-বাই-লাইন লেখা ও চালানো যায়
  • ফলাফল তাৎক্ষণিকভাবে দেখা যায়
  • পরীক্ষা-নিরীক্ষার জন্য উপযোগী

ব্যবহার:

  • টার্মিনাল বা কমান্ড প্রম্পটে python লিখে এন্টার চাপুন
  • >>> প্রম্পট দেখা যাবে, যেখানে আপনি কোড লিখতে পারেন

উদাহরণ:

>>> print("Hello, West Bengal!")
Hello, West Bengal!
>>> 2 + 3
5

২. স্ক্রিপ্ট মোড(Script mode):

স্ক্রিপ্ট মোডে, আপনি একটি ফাইলে পুরো প্রোগ্রাম লিখে সেটি চালাতে পারেন।

বৈশিষ্ট্য:

  • বড় প্রোগ্রাম লেখার জন্য ব্যবহৃত হয়
  • কোড সংরক্ষণ ও পরে পুনরায় ব্যবহার করা যায়
  • ফাইলের এক্সটেনশন .py

ব্যবহার:

  • টেক্সট এডিটরে কোড লিখুন ও .py এক্সটেনশন দিয়ে সেভ করুন
  • টার্মিনালে python filename.py কমান্ড দিয়ে চালান

উদাহরণ:
ফাইল: hello.py

print("Hello, West Bengal!")
for i in range(5):
    print(f"Number: {i}")

টার্মিনালে:

$ python hello.py
Hello, West Bengal!
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4

উভয় মোডের তুলনা(Comparison of both mode):

  • ইন্টারেক্টিভ মোড(Interactive mode): দ্রুত পরীক্ষা-নিরীক্ষা ও শিক্ষার জন্য ভালো
  • স্ক্রিপ্ট মোড(Script mode): বড় প্রজেক্ট ও পুনঃব্যবহারযোগ্য কোডের জন্য উপযুক্ত

Python Character Set

Python-এর ক্যারেক্টার সেট হল সেই সব ক্যারেক্টার যা Python প্রোগ্রাম লেখার সময় ব্যবহার করা যায়। এগুলি নিম্নলিখিত ভাগে বিভক্ত:

1. অক্ষর (Letters):

  • ছোট হাতের ইংরেজি অক্ষর: a থেকে z
  • বড় হাতের ইংরেজি অক্ষর: A থেকে Z

উদাহরণ:

name = "Python"
CONSTANT = 100

2. সংখ্যা (Digits):

  • 0 থেকে 9

উদাহরণ:

age = 25
price = 9.99

৩. বিশেষ ক্যারেক্টার (Special Characters):

  • _ (Underscore)
  • + (plus)
  • – (minus)
  • * (product)
  • / (division)
  • % (modulus)
  • = (equal to)
  • < (less then)
  • > (greater then)
  • ( ) (Parenthesis)
  • [ ] (Square Bracket)
  • { } (Curly Bracket)
  • : (colon)
  • . (dot)
  • , (comma)
  • ; (semicolon)
  • ‘ (single quote)
  • ” (doble quote)
  • # (hash)
  • @ (at the rate)

উদাহরণ:

total = 10 + 5  # Addition
is_greater = 10 > 5  # compare
my_list = [1, 2, 3]  # list
my_dict = {"key": "value"}  # Disctionary

৪. হোয়াইটস্পেস (Whitespace):

  • স্পেস(Space)
  • ট্যাব(Tab)
  • নিউলাইন(New line)

উদাহরণ:

if x > 5:
    print("x is greater than 5")  # ইনডেন্টেশনের জন্য স্পেস ব্যবহৃত (space is used for indentation)

বিশেষ নোট:

  • Python কেস-সেনসিটিভ। অর্থাৎ, variable, Variable, এবং VARIABLE তিনটি আলাদা নাম।
  • ভেরিয়েবল নামের শুরুতে সংখ্যা ব্যবহার করা যায় না। উদাহরণ: 1variable অবৈধ, কিন্তু variable1 বৈধ।
  • বিশেষ কিছু শব্দ (যেমন if, for, while ইত্যাদি) Python-এর রিজার্ভড কীওয়ার্ড, এগুলি ভেরিয়েবল নাম হিসেবে ব্যবহার করা যায় না।

উদাহরণ:

# বৈধ নাম
my_variable = 10
userName2 = "Alice"
CONSTANT_VALUE = 3.14
# অবৈধ নাম
2ndVariable = 20  # সংখ্যা দিয়ে শুরু করা যাবে না
my-variable = 30  # হাইফেন ব্যবহার করা যাবে না

এই ক্যারেক্টার সেট ব্যবহার করে আপনি Python-এ যে কোনো প্রোগ্রাম লিখতে পারবেন।

Python টোকেন (Tokens):

Python টোকেন হল প্রোগ্রামের সবচেয়ে ছোট স্বতন্ত্র উপাদান। এগুলি পাঁচ প্রকার:

1. কীওয়ার্ড (Keyword):

  • এগুলি Python-এর সংরক্ষিত শব্দ যা নির্দিষ্ট অর্থ বহন করে।
  • উদাহরণ: if, else, for, while, def, class, import
   if True:
       print("Example of keyword")

2. আইডেন্টিফায়ার (Identifier):

  • এগুলি ব্যবহারকারী-নির্ধারিত নাম যা ভেরিয়েবল, ফাংশন, ক্লাস ইত্যাদি চিহ্নিত করে।
  • নিয়ম: অক্ষর বা আন্ডারস্কোর দিয়ে শুরু হতে হবে, সংখ্যা দিয়ে নয়।
   user_name = "Manas"  # user_name is a Identifier
   def calculate_sum():  # calculate_sum is a Identifier
       pass

3. লিটারাল (Literal):

  • এগুলি ডেটার নির্দিষ্ট মান প্রকাশ করে।
  • প্রকারভেদ: সংখ্যা, স্ট্রিং, বুলিয়ান
   age = 25  # 25 একটি সংখ্যা লিটারাল(Number literal)
   name = "কমল"  # "কমল" একটি স্ট্রিং লিটারাল(String literal)
   is_student = True  # True একটি বুলিয়ান লিটারাল (Boolean literal)

4. অপারেটর (Operator):

  • এগুলি বিভিন্ন অপারেশন সম্পাদন করে যেমন গাণিতিক(mathematical), তুলনামূলক(comparison), লজিক্যাল(Logical)।
   sum = 10 + 5  # + একটি যোগ অপারেটর (arithmatic operator)
   is_greater = 10 > 5  # > একটি তুলনামূলক অপারেটর(comparison operator)
   is_valid = True and False  # and একটি লজিক্যাল অপারেটর (Logical operator)

5. পাঙ্কচুয়েটর (Punctuator):

  • এগুলি প্রোগ্রামের গঠন নির্ধারণ করে।
  • উদাহরণ: ( ), [ ], { }, :, ;, ,
   def greet(name):  # () and : punctuator
       print(f"hello, {name}!")
   fruits = ["Mango", "Banana", "Apple"]  # [] and , punctuator

উদাহরণ প্রোগ্রাম (সব ধরনের টোকেন ব্যবহার করে):

def calculate_grade(score):  # def, (), :  punctuator
    if score >= 80:  # if keyword, >= operator
        return "A"  # return keyword, "A" literal
    elif score >= 70:  # elif keyword
        return "B"
    else:  # else keyword
        return "C"
student_score = 85  # student_score আইডেন্টিফায়ার(Identifier), 85 লিটারাল(Literal)
grade = calculate_grade(student_score)  # () পাঙ্কচুয়েটর(Punctuator)
print(f"ছাত্রের গ্রেড: {grade}")  # print keyword, {} পাঙ্কচুয়েটর(punctuator)

এই প্রোগ্রামে আমরা সব ধরনের Python টোকেন ব্যবহার করেছি। কীওয়ার্ড (def, if, elif, else), আইডেন্টিফায়ার (calculate_grade, score, student_score), লিটারাল (80, 70, 85, “A”, “B”, “C”), অপারেটর (>=), এবং পাঙ্কচুয়েটর (:, (), {}) সবই এখানে ব্যবহৃত হয়েছে।

Variable [ভেরিয়েবল]:

ভেরিয়েবল হল একটি পাত্রের মতো যেখানে আপনি তথ্য সংরক্ষণ করতে পারেন। Python-এ, আপনি সহজেই ভেরিয়েবল তৈরি ও ব্যবহার করতে পারেন।

উদাহরণ:

name = "mhalder"
age = 25
print("My name is", name, "and I am", age, "years old.")

এই কোডে, name এবং age হল দুটি ভেরিয়েবল। আউটপুট হবে: My name is mhalder and I am 25 years old.

ধন্যবাদ এই গুরুত্বপূর্ণ বিষয়টি উত্থাপন করার জন্য। L-value এবং R-value ধারণাটি প্রোগ্রামিং-এর একটি মৌলিক ধারণা, যদিও Python-এ এই শব্দগুলি সরাসরি ব্যবহৃত হয় না। আসুন এই ধারণাগুলি নিয়ে আলোচনা করি।

Concept of L-value এবং R-value:

1. L-value:

  • L-value হল এমন একটি এক্সপ্রেশন যা মেমোরিতে একটি স্থান নির্দেশ করে।
  • এটি সাধারণত বাম দিকে থাকে এবং এর মান পরিবর্তন করা যায়।
  • Python-এ, ভেরিয়েবল নাম সাধারণত L-value হিসেবে কাজ করে।

2. R-value:

  • R-value হল এমন একটি এক্সপ্রেশন যা একটি মান প্রদান করে।
  • এটি সাধারণত ডান দিকে থাকে এবং এর মান পড়া যায় কিন্তু পরিবর্তন করা যায় না।

উদাহরণ:

x = 5

এখানে:

  • x হল L-value (বাম দিকে, মেমোরি লোকেশন নির্দেশ করে)
  • 5 হল R-value (ডান দিকে, একটি মান প্রদান করে)

আরও কিছু উদাহরণ:

# উদাহরণ 1
y = x + 10
# y হল L-value, (x + 10) হল R-value
# উদাহরণ 2
def get_value():
    return 20
z = get_value()
# z হল L-value, get_value() হল R-value
# উদাহরণ 3
a, b = 3, 4
# a এবং b উভয়ই L-value, 3 এবং 4 হল R-value

Python-এ L-value এবং R-value এর ব্যবহার:

1. অ্যাসাইনমেন্ট(Assignment):

   x = 10  # x হল L-value, 10 হল R-value

2. মাল্টিপল অ্যাসাইনমেন্ট(Multiple Assignment):

   a, b = 5, 6  # a এবং b হল L-value, 5 এবং 6 হল R-value

3. ফাংশন রিটার্ন(Function Return ):

   def get_coordinates():
       return 3, 4
   x, y = get_coordinates()  # x এবং y হল L-value, get_coordinates() এর রিটার্ন হল R-value

4. লিস্ট কমপ্রিহেনশন (List Comprehension):

   squares = [x**2 for x in range(5)]  # squares হল L-value, [x**2 for x in range(5)] হল R-value

বিশেষ নোট:

  • Python-এ, কিছু এক্সপ্রেশন যেমন লিস্ট স্লাইসিং(List Slicing ), L-value হিসেবে ব্যবহার করা যায়:
  my_list = [1, 2, 3, 4, 5]
  my_list[1:3] = [10, 20]  # my_list[1:3] হল L-value
  print(my_list)  # আউটপুট: [1, 10, 20, 4, 5]
  • Python-এ, সব L-value R-value হিসেবে ব্যবহার করা যায়, কিন্তু সব R-value L-value হিসেবে ব্যবহার করা যায় না।

এই ধারণাগুলি বুঝতে পারলে, আপনি Python-এ ভেরিয়েবল অ্যাসাইনমেন্ট এবং এক্সপ্রেশন মূল্যায়ন আরও ভালভাবে বুঝতে পারবেন।

Python-এ কমেন্ট ব্যবহার:

কমেন্ট হল কোডের মধ্যে লেখা টেক্সট যা Python ইন্টারপ্রেটার দ্বারা উপেক্ষা করা হয়। এগুলি কোডের ব্যাখ্যা দেওয়া, ডকুমেন্টেশন করা, বা অস্থায়ীভাবে কোড অক্ষম করার জন্য ব্যবহৃত হয়।

Python-এ দুই ধরনের কমেন্ট রয়েছে:

1. সিঙ্গল-লাইন কমেন্ট:

  • ‘#’ চিহ্ন দিয়ে শুরু হয়
  • লাইনের শেষ পর্যন্ত চলে

উদাহরণ:

# এটি একটি সিঙ্গল-লাইন কমেন্ট
print("Hello , West Bengal !")  # এটিও একটি সিঙ্গল-লাইন কমেন্ট

2. মাল্টি-লাইন কমেন্ট:

  • তিনটি উদ্ধৃতি চিহ্ন (”’ বা “””) দিয়ে শুরু ও শেষ হয়
  • একাধিক লাইন জুড়ে থাকতে পারে

উদাহরণ:

'''
এটি একটি
মাল্টি-লাইন
কমেন্ট
'''
"""
এটিও একটি
মাল্টি-লাইন
কমেন্ট
"""

Use of Comment(কমেন্টের ব্যবহার) :

1. Code Explanation(কোড ব্যাখ্যা):

# গড় নির্ণয়
average = sum(numbers) / len(numbers)

2. Function or Class Documentation(ফাংশন বা ক্লাস ডকুমেন্টেশন) :

def calculate_area(radius):
    """
    This function is used for calculate area of citcle
    Parameter:
    radius (float): বৃত্তের ব্যাসার্ধ
    Return:
    float: Area of Circle(বৃত্তের ক্ষেত্রফল)
    """
    return 3.14 * radius ** 2

3. কোড অস্থায়ীভাবে অক্ষম করা(Temporary disable):

# print("এই লাইনটি এখন কাজ করবে না")
   print("এই লাইনটি কাজ করবে")

4. TODO নোট:

# TODO: এখানে ইউজার ইনপুট যাচাই করার কোড যোগ করতে হবে

5. কোডের সেকশন ভাগ করা (Divide Section of code):

###################
# ডেটা প্রস্তুতকরণ #
###################
# কোড এখানে...
###################
# মডেল প্রশিক্ষণ   #
###################
# কোড এখানে...

Advantage(কমেন্ট ব্যবহারের সুবিধা):

  • কোড বোঝা ও রক্ষণাবেক্ষণ সহজ হয়
  • টিম সদস্যদের মধ্যে সহযোগিতা বাড়ে
  • ভবিষ্যতে নিজের কোড বুঝতে সাহায্য করে
  • ডকুমেন্টেশন তৈরিতে সহায়ক

Cautions (সতর্কতা):

  • অতিরিক্ত বা অপ্রয়োজনীয় কমেন্ট এড়িয়ে চলুন
  • কমেন্ট সর্বদা আপ-টু-ডেট রাখুন, অন্যথায় ভুল তথ্য দিতে পারে
Practice Python-1Practice Python

Knowledge Data Type:

Python-এ বিভিন্ন ধরনের ডেটা আছে। তিনটি মৌলিক ডেটা টাইপ হল:

  1. স্ট্রিং (string): টেক্সট ডেটা
  2. ইন্টিজার (integer): পূর্ণসংখ্যা
  3. ফ্লোট (float): দশমিক সংখ্যা

উদাহরণ:

text = "This is a string"
number = 42
decimal = 3.14
print(type(text))
print(type(number))
print(type(decimal))

এই কোডের আউটপুট হবে:

<class 'str'>
<class 'int'>
<class 'float'>

type() ফাংশন ব্যবহার করে আমরা কোনো ভেরিয়েবলের ডেটা টাইপ [data type of Variable] জানতে পারি।

1. সংখ্যা (Number):

a) ইন্টিজার (Integer):
– পূর্ণসংখ্যা
– উদাহরণ: x = 5

b) ফ্লোটিং পয়েন্ট (Floating Point):
– দশমিক সংখ্যা
– উদাহরণ: y = 3.14

c) কমপ্লেক্স (Complex):
– বাস্তব ও কাল্পনিক অংশ সহ সংখ্যা
– উদাহরণ: z = 2 + 3j

2. বুলিয়ান (Boolean):

  • সত্য বা মিথ্যা মান
  • উদাহরণ: is_student = True

3. সিকোয়েন্স (Sequence):

a) স্ট্রিং (String):
– টেক্সট ডেটা
– উদাহরণ: name = "Manas"

b) লিস্ট (List):
– পরিবর্তনযোগ্য ক্রমিক আইটেম(sequence item and also changable)
– উদাহরণ: fruits = ["Mango", "Banana", "Apple"]

c) টিউপল (Tuple):
– অপরিবর্তনীয় ক্রমিক আইটেম ((sequence itembut not changable))
– উদাহরণ: coordinates = (3, 4)

4. None :

  • শূন্য বা অনুপস্থিত মান
  • উদাহরণ: result = None

5. ম্যাপিং (Mapping):

ডিকশনারি (Dictionary):

  • Pair of Key-value)
  • Example: person = {"name": "Manas", "age": 40}

6. পরিবর্তনযোগ্য (Mutable) ও অপরিবর্তনীয় (Immutable) ডেটা টাইপ:

a) পরিবর্তনযোগ্য (Mutable):
– List
– Dictionary
– Set

b) অপরিবর্তনীয় (Immutable):
– Integer
– Float
– complex
– string
– Tuple

Example :

# Numeric
integer_num = 10
float_num = 3.14
complex_num = 2 + 3j
print(f"Integer: {integer_num}, Float: {float_num}, Complex: {complex_num}")

# Boolean(বুলিয়ান)
is_python_fun = True
print(f"Is Python fun ? {is_python_fun}")

# Sequence(সিকোয়েন্স)
text = "WestBengal"
fruits = ["Mango", "Orange", "Banana"]
point = (10, 20)
print(f"Text: {text}")
print(f"List of fruit: {fruits}")
print(f"Co-ordinate: {point}")

# None
result = None
print(f"Result: {result}")

# Mapping (Dictionary)
person = {
    "Name": "Manas",
    "Age": 30,
    "Occupation": "Teacher"
}
print(f"person Information: {person}")

# Mutable and Immutable
mutable_list = [1, 2, 3]
immutable_tuple = (1, 2, 3)
mutable_list[0] = 10  # এটি কাজ করবে
# immutable_tuple[0] = 10  # এটি ত্রুটি দেখাবে
print(f"Mutable List: {mutable_list}")
print(f"Immutable list: {immutable_tuple}")

এই প্রোগ্রামটি চালালে আপনি বিভিন্ন ডেটা টাইপের ব্যবহার ও আচরণ দেখতে পাবেন।

বিশেষ নোট:

  • পরিবর্তনযোগ্য (Mutable) ডেটা টাইপের মান পরিবর্তন করা যায়।
  • অপরিবর্তনীয় (Immutable) ডেটা টাইপের মান পরিবর্তন করা যায় না। নতুন মান অ্যাসাইন করলে নতুন অবজেক্ট তৈরি হয়।

Operator in Python:

Python-এ বিভিন্ন ধরনের অপারেটর রয়েছে। আসুন আমরা প্রধান কয়েকটি দেখি:

1. গাণিতিক অপারেটর(Arithmatic Operator):

   a, b = 10, 3
   print(a + b)  # যোগ: 13
   print(a - b)  # বিয়োগ: 7
   print(a * b)  # গুণ: 30
   print(a / b)  # ভাগ: 3.3333...
   print(a // b) # পূর্ণ ভাগফল: 3
   print(a % b)  # ভাগশেষ: 1
   print(a ** b) # এক্সপোনেন্ট: 1000

2. তুলনামূলক অপারেটর(Comparison Operator):

   x, y = 5, 7
   print(x == y) # সমান: False
   print(x != y) # সমান নয়: True
   print(x < y)  # ছোট: True
   print(x > y)  # বড়: False
   print(x <= y) # ছোট বা সমান: True
   print(x >= y) # বড় বা সমান: False

3. লজিক্যাল অপারেটর(Logical Operator):

   p, q = True, False
   print(p and q) # AND: False
   print(p or q)  # OR: True
   print(not p)   # NOT: False

4. অ্যাসাইনমেন্ট অপারেটর(assignment Operator):

   x = 10
   x += 5  # x = x + 5
   print(x)  # 15
   x *= 2  # x = x * 2
   print(x)  # 30

5. আইডেনটিটি অপারেটর(Identity Operator):

   a = [1, 2, 3]
   b = [1, 2, 3]
   c = a
   print(a is b)  # False (ভিন্ন অবজেক্ট)
   print(a is c)  # True (একই অবজেক্ট)

6. সদস্যপদ অপারেটর(Membership Operator):

   fruits = ["Mango", "Banana", "Apple"]
   print("Mango" in fruits)     # True
   print("Grapes" not in fruits)  # True

Expression, Statement, Type Conversion and I/O:

1. Expression & Statement এক্সপ্রেশন ও স্টেটমেন্ট:

  • এক্সপ্রেশন: মান প্রদানকারী কোডের অংশ।
  • স্টেটমেন্ট: একটি সম্পূর্ণ কোড লাইন যা কোনো কাজ সম্পাদন করে। উদাহরণ:
   x = 5  # একটি স্টেটমেন্ট
   y = x + 3  # 'x + 3' হল একটি এক্সপ্রেশন, পুরো লাইনটি একটি স্টেটমেন্ট

2. অপারেটরের অগ্রাধিকার(Operator Precedence):
Python-এ অপারেটরের একটি নির্দিষ্ট অগ্রাধিকার ক্রম রয়েছে। উদাহরণস্বরূপ:

  • এক্সপোনেনশিয়েশন (*) > গুণ () > যোগ (+) উদাহরণ:
   result = 2 + 3 * 4 ** 2  # 4**2 প্রথমে, তারপর 3 দিয়ে গুণ, অবশেষে 2 যোগ
   print(result)  # 50

3. এক্সপ্রেশন মূল্যায়ন:
Python এক্সপ্রেশনগুলি বাম থেকে ডানে মূল্যায়ন করে, অপারেটর অগ্রাধিকার অনুসরণ করে।

4. Type Conversion (টাইপ কনভার্শন):
a) স্পষ্ট (Explicit) কনভার্শন:
python x = int("5") # স্ট্রিং থেকে ইন্টিজার y = float("3.14") # স্ট্রিং থেকে ফ্লোট z = str(42) # ইন্টিজার থেকে স্ট্রিং

b) অন্তর্নিহিত (Implicit) কনভার্শন:
python x = 5 + 3.14 # ইন্টিজার স্বয়ংক্রিয়ভাবে ফ্লোটে রূপান্তরিত হয় print(x) # 8.14

5. Input/Output :
a) Input:
python name = input("What is your name? ") age = int(input("How Old are you? "))

b) Output:
python print(f"Hello, {name}! your age {age} years।")

উদাহরণ প্রোগ্রাম:

# ব্যবহারকারীর কাছ থেকে দুটি সংখ্যা নিন এবং তাদের যোগফল, বিয়োগফল, গুণফল ও ভাগফল প্রদর্শন করুন
# ইনপুট নেওয়া
num1 = float(input("Input first number: "))
num2 = float(input("Input Second number: "))
# গণনা
sum_result = num1 + num2
diff_result = num1 - num2
product_result = num1 * num2
division_result = num1 / num2 if num2 != 0 else "অসংজ্ঞায়িত (0 দিয়ে ভাগ করা যায় না)"
# ফলাফল প্রদর্শন
print(f"nফলাফল:")
print(f"Addition: {sum_result}")
print(f"Substarction: {diff_result}")
print(f"Multiplication: {product_result}")
print(f"Division: {division_result}")
# টাইপ কনভার্শন এর উদাহরণ
print(f"n Type of num1 : {type(num1)}")
int_num1 = int(num1)
print(f"Type of int(num1) : {type(int_num1)}")

এই প্রোগ্রামে আমরা নিম্নলিখিত বিষয়গুলি দেখতে পাই:

  1. input() ফাংশন ব্যবহার করে ইউজার ইনপুট নেওয়া
  2. স্ট্রিং থেকে ফ্লোটে টাইপ কনভার্শন (float(input()))
  3. গাণিতিক অপারেশন (যোগ, বিয়োগ, গুণ, ভাগ)
  4. কন্ডিশনাল এক্সপ্রেশন (x if condition else y)
  5. f-string ব্যবহার করে ফরম্যাটেড আউটপুট
  6. type() ফাংশন ব্যবহার করে ভেরিয়েবলের টাইপ চেক করা
  7. ফ্লোট থেকে ইন্টিজারে স্পষ্ট টাইপ কনভার্শন
Practice PythonTry Python onlinePractice Python

Error in Python

Python-এ মূলত তিন ধরনের ত্রুটি রয়েছে:

1. সিনট্যাক্স ত্রুটি (Syntax Errors):

  • এগুলি Python-এর নিয়ম লঙ্ঘন করার কারণে হয়।
  • প্রোগ্রাম রান করার আগেই ধরা পড়ে। উদাহরণ:
   # Syntax Error
   print "Hello, West Bengal"  # সঠিক হবে: print("Hello, West Bengal")
   if x = 5:  # সঠিক হবে: if x == 5:
       print(x)

2. Logical Errors(লজিক্যাল ত্রুটি):

  • এগুলি প্রোগ্রামের যুক্তিতে ভুল থাকার কারণে হয়।
  • প্রোগ্রাম রান হয়, কিন্তু ভুল ফলাফল দেয়।
  • এগুলি খুঁজে বের করা কঠিন হতে পারে। উদাহরণ:
# Logical Error
x = float(input('Enter a number: '))
y = float(input('Enter a number: '))
z = x+y/2
print('The average of the two numbers you have entered is:' ,  z)

3. Runtime Errors(রানটাইম ত্রুটি ):

  • এগুলি প্রোগ্রাম চলাকালীন সময়ে ঘটে।
  • অনেক সময় এগুলিকে এক্সেপশন (Exception) বলা হয়। উদাহরণ:
   # রানটাইম ত্রুটি
   numbers = [1, 2, 3]
   print(numbers[3])  # IndexError: list index out of range
   x = 10
   y = 0
   print(x / y)  # ZeroDivisionError: division by zero

Error Handling:
Python-এ tryexcept ব্লক ব্যবহার করে রানটাইম ত্রুটি নিয়ন্ত্রণ করা যায়:

try:
    x = 10
    y = 0
    result = x / y
    print(result)
except ZeroDivisionError:
    print("Can not divided by zero")

Example:

def divide_numbers(a, b):
    try:
        result = a / b
        return result
    except ZeroDivisionError:
        return "Can not divided by zero"
    except TypeError:
        return "Can not divided by anything other then number"
# Test Case
print(divide_numbers(10, 2))  # সঠিক ফলাফল: 5.0
print(divide_numbers(10, 0))  # শূন্য দিয়ে ভাগ
print(divide_numbers(10, "2"))  # টাইপ ত্রুটি
# Example of Logical Error
def calculate_discount(price, discount_percentage):
    discount = price * (discount_percentage / 100)
    return price - discount  # no logical error, but if you write 'price + discount' then error will come
print(calculate_discount(100, 20))  # সঠিক ফলাফল: 80.0
# Example of Syntax error
# if price < 0
#     print("Price will not negative")

মনে রাখবেন:

  1. Syntax Error এড়াতে সতর্কতার সাথে কোড লিখুন।
  2. Logical Error এড়াতে আপনার কোড ভালভাবে পরীক্ষা করুন।
  3. Runtime Error নিয়ন্ত্রণের জন্য tryexcept ব্যবহার করুন।

Flow of Control(নিয়ন্ত্রণ প্রবাহ):

1. Use of Indentation (ইনডেনটেশনের ব্যবহার):
Python-এ নিয়ন্ত্রণ প্রবাহ নির্ধারণ করতে ইনডেনটেশন (indentation) ব্যবহার করা হয়। এটি কোডের গঠন ও পঠনযোগ্যতা বজায় রাখে।

Example:

   if True:
       print("This line is indentend")
       print("This is also Indented")
   print("This line is not Indented")

2. ক্রমিক প্রবাহ (Sequential Flow):
কোড সাধারণত উপর থেকে নিচে, বাম থেকে ডানে ক্রমানুসারে চলে।

উদাহরণ:

   print("First Line")
   print("Second Line")
   print("Third Line")

3. শর্তসাপেক্ষ প্রবাহ (Conditional Flow):
ifelifelse ব্যবহার করে শর্তসাপেক্ষ প্রবাহ নিয়ন্ত্রণ করা হয়।

Example

   age = 20
   if age < 18:
       print("You are under 18")
   elif age >= 18 and age < 60:
       print("You are Adult")
   else:
       print("You are aged")

4. পুনরাবৃত্তিমূলক প্রবাহ (Iterative Flow):
forwhile লুপ ব্যবহার করে পুনরাবৃত্তিমূলক প্রবাহ নিয়ন্ত্রণ করা হয়।

a) for লুপ:

   fruits = ["Mango", "banana", "Grapes"]
   for fruit in fruits:
       print(f" I like {fruit} ")

b) while লুপ:

   count = 0
   while count < 5:
       print(f"present number: {count}")
       count += 1

Example

def print_multiplication_table(n):
    print(f"Multiplication Table of {n} :")
    for i in range(1, 11):
        print(f"{n} x {i} = {n*i}")
def check_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True
# Main program
while True:
    choice = input("What is your choice? (1: Multiplication Table, 2: check Prime number, 3: Program close): ")
    if choice == '1':
        n = int(input("Which number’s multiplication table do you want to see? "))
        print_multiplication_table(n)
    elif choice == '2':
        num = int(input("Enter number to check Prime number? "))
        if check_prime(num):
            print(f"{num} is prime number")
        else:
            print(f"{num} is not prime number")
    elif choice == '3':
        print("Than you for use this program।")
        break
    else:
        print("Try againt!!")
    print()  # Print Blank Line (একটি খালি লাইন প্রিন্ট)

এই প্রোগ্রামে আমরা দেখতে পাচ্ছি:

  1. Sequential Flow (ক্রমিক প্রবাহ): কোড উপর থেকে নিচে চলছে।
  2. Conditional Flow(শর্তসাপেক্ষ প্রবাহ): if, elif, else ব্যবহার করে বিভিন্ন পছন্দ নিয়ন্ত্রণ করা হচ্ছে।
  3. Iterative flow(পুনরাবৃত্তিমূলক প্রবাহ):
  • while লুপ ব্যবহার করে প্রোগ্রাম চালু রাখা হচ্ছে।
  • for লুপ ব্যবহার করে নামতা প্রিন্ট ও মৌলিক সংখ্যা যাচাই করা হচ্ছে।
  1. Function: print_multiplication_table()check_prime() ফাংশন ব্যবহার করে কোড পুনঃব্যবহার করা হচ্ছে।
  2. Indentation: প্রতিটি ব্লকের জন্য সঠিক ইনডেনটেশন ব্যবহার করা হয়েছে।

Conditional Statement

শর্তাধীন বিবৃতি প্রোগ্রামে সিদ্ধান্ত গ্রহণ করতে সাহায্য করে। Python এ শর্তাধীন বিবৃতি ব্যবহার করে আমরা বিভিন্ন শর্ত অনুযায়ী কোডের বিভিন্ন অংশ চালাতে পারি। নিচে বিভিন্ন ধরনের শর্তাধীন বিবৃতি এবং তাদের ব্যবহার সম্পর্কে আলোচনা করা হলো:

1. if statement

if statement ব্যবহার করে আমরা একটি শর্ত চেক করতে পারি। যদি শর্তটি সত্য হয়, তাহলে নির্দিষ্ট কোড ব্লকটি চালানো হবে।

উদাহরণ:

number = 10
if number > 0:
    print("Number is positive.")

2. if-else statement

if-else বিবৃতি ব্যবহার করে আমরা একটি শর্ত সত্য না হলে অন্য একটি কোড ব্লক চালাতে পারি।

উদাহরণ:

number = -5
if number > 0:
    print("Number is positive.")
else:
    print("Number is not positive.")

3. if-elif-else Statement

Some Simple Example

Write a program to find Absolute Value
number = -10

if number < 0:
    absolute_value = -number
else:
    absolute_value = number

print("Absolute value:", absolute_value)
Write a program to arrange three number in sorted order(Ascending order)
a = 5 ; b = 2 ; c = 8
if a <= b and a <= c:
    if b <= c:
        print("Sorted order:", a, b, c)
    else:
        print("Sorted order:", a, c, b)
elif b <= a and b <= c:
    if a <= c:
        print("Sorted order:", b, a, c)
    else:
        print("Sorted order:", b, c, a)
else:
    if a <= b:
        print("Sorted order:", c, a, b)
    else:
        print("Sorted order:", c, b, a)
Write a program to check Divisibility of number
number = 15
divisor = 5

if number % divisor == 0:
    print(f"{number} is divisible by {divisor}.")
else:
    print(f"{number} is not divisible by {divisor}.")

Iterative Statement

Iterative statement এমন একটি প্রোগ্রামিং কনস্ট্রাক্ট যা একটি নির্দিষ্ট কোড ব্লক বারবার চালাতে দেয় যতক্ষণ না একটি নির্দিষ্ট শর্ত পূরণ হয়। Iteration এর মাধ্যমে আমরা প্রোগ্রামে পুনরাবৃত্তিমূলক কাজগুলো সহজে করতে পারি। Python এ প্রধানত দুটি ধরনের iterative statement আছে: for loop এবং while loop।

1. for Loop and range()

for লুপ এবং range() ফাংশন ব্যবহার করে নির্দিষ্ট সংখ্যক বার লুপ চালানো যায়।

Example: Summation of Series

Let’s calculate the sum of the first 10 natural numbers.

sum = 0
for i in range(1, 11):
    sum += i
print("Sum of first 10 natural numbers:", sum)

2. while Loop

while লুপ একটি শর্ত সত্য থাকা পর্যন্ত কোড ব্লক চালায়।

Example: Finding Factorial

Let’s find the factorial of a positive number.

number = 5
factorial = 1
i = 1

while i <= number:
    factorial *= i
    i += 1

print(f"Factorial of {number} is {factorial}")

3. break and continue Statements

break লুপ সম্পূর্ণরূপে বন্ধ করতে ব্যবহৃত হয়, এবং continue বর্তমান ইটারেশন বাদ দিয়ে পরবর্তী ইটারেশনে যেতে ব্যবহৃত হয়।

Example: Using break and continue

Let’s print numbers from 1 to 10, but skip 5 and stop at 8.

for i in range(1, 11):
    if i == 5:
        continue
    if i == 8:
        break
    print(i)

4. Nested Loops

নেস্টেড লুপ ব্যবহার করে আমরা লুপের ভিতরে আরেকটি লুপ চালাতে পারি।

Suggested Program

Example: Generating Pattern
rows = 5
for i in range(1, rows + 1):
    for j in range(1, i + 1):
        print("*", end=" ")
    print()
Calculate the sum of a series, such as 1 + 2 + 3 + … + n.
n = 10
sum = 0
for i in range(1, n + 1):
    sum += i
print(f"Sum of series 1 to {n} is {sum}")
Calculate the factorial of a number using a for loop.
number = 5
factorial = 1

for i in range(1, number + 1):
    factorial *= i

print(f"Factorial of {number} is {factorial}")

Strings

Introduction:
Python-এ স্ট্রিং হল অপরিবর্তনীয় (immutable) অক্ষরের ক্রম। এগুলি সিঙ্গল কোট (”) বা ডাবল কোট (“”) দিয়ে লেখা হয়।

উদাহরণ:

   s1 = 'Hello'
   s2 = "Bengal"

2. String Operation:

a) সংযুক্তিকরণ (Concatenation):
python full_greeting = s1 + ' ' + s2 print(full_greeting) # Hello Bengal

b) পুনরাবৃত্তি (Repetition):
python repeated = s1 * 3 print(repeated) # HelloHelloHello

c) সদস্যপদ (Membership):
python print('lo' in s1) # True print('gal' in s2) # True

d) স্লাইসিং (Slicing):
python print(s2[0:3]) # Ben print(s2[::-1]) # lagneb (উল্টো)

3. লুপ ব্যবহার করে স্ট্রিং ট্রাভার্স (Traverse string using loop):

   for char in s1:
       print(char)

৪. বিল্ট-ইন ফাংশন/মেথড(Built-in Function and Method):

   text = "python programming"
   print(len(text))              # 19 (দৈর্ঘ্য)
   print(text.capitalize())      # Python programming
   print(text.title())           # Python Programming
   print(text.lower())           # python programming
   print(text.upper())           # PYTHON PROGRAMMING
   print(text.count('p'))        # 2 ('p' এর সংখ্যা)
   print(text.find('gram'))      # 11 (অবস্থান)
   print(text.index('gram'))     # 11 (অবস্থান, না পেলে ValueError)
   print(text.endswith('ming'))  # True
   print(text.startswith('py'))  # True
   print(text.isalnum())         # False (শুধু অক্ষর ও সংখ্যা নয়)
   print(text.isalpha())         # False (শুধু অক্ষর নয়)
   print(text.isdigit())         # False (শুধু সংখ্যা নয়)
   print(text.islower())         # True (সব ছোট হাতের)
   print(text.isupper())         # False (সব বড় হাতের নয়)
   print(text.isspace())         # False (শুধু স্পেস নয়)
   print(text.lstrip(' p'))       # 
   print(text.rstrip('g'))       # 
   print(text.strip('p'))        # 
   print(text.replace('python', 'Java'))  # Java programming
   print('-'.join(['a', 'b', 'c']))  # a-b-c
   print(text.partition(' '))    # ('python', ' ', 'programming')
   print(text.split())           # ['python', 'programming']

অনুশীলনী প্রোগ্রাম:
নিচের প্রোগ্রামটি লিখুন ও চালান। এটি বিভিন্ন স্ট্রিং অপারেশন ও মেথড ব্যবহার করে:

def analyze_text(text):
    print(f"Main Text: {text}")
    print(f"Length: {len(text)}")
    print(f"Uppercase: {text.upper()}")
    print(f"Lowercase: {text.lower()}")
    print(f"Number of word: {len(text.split())}")
    print(f"Number of letter 'a': {text.count('a')}")
    print(f"First position of  'a' : {text.find('a')}")
    print(f"Capital of first letter of every word: {text.title()}")
    print(f"'is started with Python' {text.startswith('Python')}")
    print(f"Omit space: {text.replace(' ', '')}")
    words = text.split()
    print(f"Reverse Word: {' '.join(words[::-1])}")
# টেস্ট(Text)
sample_text = "Python is a powerful programming language"
analyze_text(sample_text)
# ব্যবহারকারীর ইনপুট (User Input)
user_text = input("nwrite your own text: ")
analyze_text(user_text)

এই প্রোগ্রামটি চালিয়ে দেখুন। এটি আপনাকে Python-এ স্ট্রিং ম্যানিপুলেশনের বিভিন্ন দিক সম্পর্কে একটি ভাল ধারণা দেবে। প্রোগ্রামটি প্রথমে একটি নমুনা টেক্সট নিয়ে কাজ করে, তারপর ব্যবহারকারীর দেওয়া টেক্সট নিয়ে একই বিশ্লেষণ করে।

মনে রাখবেন:

  1. Python-এ স্ট্রিং অপরিবর্তনীয় (immutable)। যখন আপনি একটি স্ট্রিং পরিবর্তন করেন, আসলে একটি নতুন স্ট্রিং তৈরি হয়।
  2. স্ট্রিং ইনডেক্সিং 0 থেকে শুরু হয়।
  3. নেগেটিভ ইনডেক্সিং দিয়ে স্ট্রিংয়ের শেষ থেকে অ্যাক্সেস করা যায়।
Practice Python-1Practice Python

List (লিস্ট ):

লিস্ট হল Python-এর একটি গুরুত্বপূর্ণ ডেটা স্ট্রাকচার। এটি একাধিক আইটেম একসাথে সংরক্ষণ করতে ব্যবহৃত হয়।

এই মেথডগুলো Python এ লিস্টের সাথে কাজ করতে অত্যন্ত সহায়ক। প্রতিটি মেথডের নিজস্ব ব্যবহার এবং প্রয়োজনীয়তা রয়েছে, যা লিস্টের ডেটা পরিচালনা করতে সাহায্য করে।

উদাহরণ:

fruits = ["Mango", "Banana", "Apple", "Grape"]
print(fruits[0])  # প্রথম আইটেম প্রিন্ট করে

এই কোডের আউটপুট হবে:
Mango
4
[“Mango”, “Banana”, “Apple”, “Grape”, “Orange”]

List এ ব্যবহৃত বিভিন্ন function গুলি হল-

1. append()

লিস্টের শেষে একটি আইটেম যোগ করতে ব্যবহৃত হয়।

উদাহরণ:

fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)  # Output: ['apple', 'banana', 'cherry']

2. extend()

একটি লিস্টের শেষে অন্য একটি লিস্টের সব আইটেম যোগ করতে ব্যবহৃত হয় ।

উদাহরণ:

fruits = ["apple", "banana"]
more_fruits = ["cherry", "orange"]
fruits.extend(more_fruits)
print(fruits)  # Output: ['apple', 'banana', 'cherry', 'orange']

3. insert()

নির্দিষ্ট অবস্থানে একটি আইটেম যোগ করতে ব্যবহৃত হয়।

উদাহরণ:

fruits = ["apple", "banana"]
fruits.insert(1, "cherry")
print(fruits)  # Output: ['apple', 'cherry', 'banana']

4. remove()

নির্দিষ্ট মানের প্রথম উপস্থিতি মুছে ফেলতে ব্যবহৃত হয়।

উদাহরণ:

num = [10,20,30,20,40]
fruits.remove(20)
print(num)  # Output: [10,30,20,40]

5. pop()

নির্দিষ্ট অবস্থানের আইটেম মুছে ফেলে এবং তা রিটার্ন করে। ডিফল্টভাবে শেষ আইটেম মুছে ফেলে।

উদাহরণ:

fruits = ["apple", "banana", "cherry"]
popped_item = fruits.pop()
print(popped_item)  # Output: 'cherry'
print(fruits)       # Output: ['apple', 'banana']

6. clear()

লিস্টের সব আইটেম মুছে ফেলে।

উদাহরণ:

fruits = ["apple", "banana", "cherry"]
fruits.clear()
print(fruits)  # Output: []

7. index()

নির্দিষ্ট মানের প্রথম উপস্থিতির ইন্ডেক্স রিটার্ন করে।

উদাহরণ:

fruits = ["apple", "banana", "cherry"]
index = fruits.index("banana")
print(index)  # Output: 1

8. count()

নির্দিষ্ট মানের উপস্থিতির সংখ্যা রিটার্ন করে।

উদাহরণ:

fruits = ["apple", "banana", "cherry", "banana"]
count = fruits.count("banana")
print(count)  # Output: 2

9. sort()

লিস্টকে ক্রম অনুযায়ী সাজায়। ডিফল্টভাবে এটি আসেন্ডিং অর্ডারে সাজায়।

উদাহরণ:

numbers = [3, 1, 4, 1, 5]
numbers.sort()
print(numbers)  # Output: [1, 1, 3, 4, 5]

10. reverse()

লিস্টের আইটেমগুলোর ক্রম উল্টে দেয়।

উদাহরণ:

fruits = ["apple", "banana", "cherry"]
fruits.reverse()
print(fruits)  # Output: ['cherry', 'banana', 'apple']

11. copy()

লিস্টের একটি কপি তৈরি করে।

উদাহরণ:

fruits = ["apple", "banana", "cherry"]
fruits_copy = fruits.copy()
print(fruits_copy)  # Output: ['apple', 'banana', 'cherry']

Tuples

Tuple একটি অপরিবর্তনীয় (immutable) ডেটা স্ট্রাকচার যা Python এ বিভিন্ন ধরনের ডেটা সংরক্ষণ করতে ব্যবহৃত হয়। Tuple সাধারণত রাউন্ড ব্র্যাকেট () দিয়ে ডিফাইন করা হয় এবং এর মধ্যে থাকা আইটেমগুলো কমা , দিয়ে আলাদা করা হয়।

Example:

my_tuple = (1, 2, 3, "apple", "banana")

Indexing

Tuple এর প্রতিটি আইটেমের একটি নির্দিষ্ট ইন্ডেক্স থাকে, যা 0 থেকে শুরু হয়। ইন্ডেক্স ব্যবহার করে আমরা নির্দিষ্ট আইটেম অ্যাক্সেস করতে পারি।

Example:

print(my_tuple[0])  # Output: 1
print(my_tuple[3])  # Output: apple

Tuple Operations

1. Concatenation

দুটি বা ততোধিক tuple একত্রিত করতে + অপারেটর ব্যবহার করা হয়।

Example:

tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
result = tuple1 + tuple2
print(result)  # Output: (1, 2, 3, 4, 5, 6)

2. Repetition

একটি tuple কে নির্দিষ্ট সংখ্যক বার পুনরাবৃত্তি করতে * অপারেটর ব্যবহার করা হয়।

Example:

tuple1 = (1, 2, 3)
result = tuple1 * 2
print(result)  # Output: (1, 2, 3, 1, 2, 3)

3. Membership

একটি নির্দিষ্ট আইটেম tuple এ আছে কিনা তা চেক করতে in এবং not in অপারেটর ব্যবহার করা হয়।

Example:

print(2 in my_tuple)  # Output: True
print("orange" not in my_tuple)  # Output: True

4. Slicing

Tuple এর একটি অংশ বের করতে slicing ব্যবহার করা হয়।

Example:

print(my_tuple[1:4])  # Output: (2, 3, 'apple')

4. Built-in Functions/Methods

  • len(): Tuple এর দৈর্ঘ্য রিটার্ন করে।
  print(len(my_tuple))  # Output: 5
  • tuple(): একটি iterable কে tuple এ রূপান্তর করে।
  list1 = [1, 2, 3]
  tuple1 = tuple(list1)
  print(tuple1)  # Output: (1, 2, 3)
  • count(): Tuple এ নির্দিষ্ট আইটেমের উপস্থিতির সংখ্যা রিটার্ন করে।
  print(my_tuple.count(2))  # Output: 1
  • index(): Tuple এ নির্দিষ্ট আইটেমের প্রথম উপস্থিতির ইন্ডেক্স রিটার্ন করে।
  print(my_tuple.index("apple"))  # Output: 3
  • sorted(): Tuple এর আইটেমগুলোকে সাজানো লিস্ট হিসেবে রিটার্ন করে।
  numbers = (3, 1, 2)
  print(sorted(numbers))  # Output: [1, 2, 3]
  • min(): Tuple এর সর্বনিম্ন মান রিটার্ন করে।
  print(min(numbers))  # Output: 1
  • max(): Tuple এর সর্বোচ্চ মান রিটার্ন করে।
  print(max(numbers))  # Output: 3
  • sum(): Tuple এর সব সংখ্যার যোগফল রিটার্ন করে।
  print(sum(numbers))  # Output: 6

Tuple Assignment

Tuple assignment ব্যবহার করে একাধিক ভেরিয়েবলে একসাথে মান অ্যাসাইন করা যায়।

Example:

a, b, c = (1, 2, 3)
print(a, b, c)  # Output: 1 2 3

Nested Tuple

Tuple এর মধ্যে আরেকটি tuple রাখা যায়, যা nested tuple হিসেবে পরিচিত।

Example:

nested_tuple = (1, 2, (3, 4), 5)
print(nested_tuple[2])  # Output: (3, 4)
print(nested_tuple[2][1])  # Output: 4

এই বিষয়গুলো Python এ tuple এর বিভিন্ন ব্যবহারিক প্রয়োগ এবং ক্ষমতা প্রদর্শন করে। Tuple এর অপরিবর্তনীয়তা এবং বিভিন্ন অপারেশন প্রোগ্রামিং এ কার্যকরী ডেটা ম্যানেজমেন্টে সহায়ক।

Introduction to Dictionaries

Python এ ডিকশনারি একটি পরিবর্তনযোগ্য (mutable) ডেটা স্ট্রাকচার যা কী-ভ্যালু (key-value) পেয়ার সংরক্ষণ করে। ডিকশনারি সাধারণত কার্লি ব্র্যাকেট {} দিয়ে ডিফাইন করা হয় এবং প্রতিটি আইটেম একটি কী এবং তার সাথে সংশ্লিষ্ট ভ্যালু নিয়ে গঠিত।

Example:

student = {
    "name": "Ram",
    "age": 20,
    "major": "Computer Science"
}

Accessing Items in a Dictionary

ডিকশনারির আইটেম অ্যাক্সেস করতে কী ব্যবহার করা হয়।

Example:

print(student["name"])  # Output:Ram

Mutability of a Dictionary

ডিকশনারি পরিবর্তনযোগ্য, অর্থাৎ আমরা নতুন আইটেম যোগ করতে, বিদ্যমান আইটেম পরিবর্তন করতে এবং মুছে ফেলতে পারি।

Adding a New Item

Example:

student["university"] = "XYZ University"
print(student)

Modifying an Existing Item

Example:

student["age"] = 21
print(student)

Traversing a Dictionary

ডিকশনারির প্রতিটি আইটেমের উপর ইটারেট করতে for লুপ ব্যবহার করা হয়।

Example:

for key, value in student.items():
    print(key, ":", value)

Built-in Functions/Methods

  • len(): ডিকশনারির আইটেম সংখ্যা রিটার্ন করে।
  print(len(student))  # Output: 4
  • dict(): একটি নতুন ডিকশনারি তৈরি করে।
  new_dict = dict(name="Karim", age=22)
  print(new_dict)
  • keys(): ডিকশনারির সব কী রিটার্ন করে(return all the key)।
  print(student.keys())
  • values(): ডিকশনারির সব ভ্যালু রিটার্ন করে(return all the values)।
  print(student.values())
  • items(): ডিকশনারির সব কী-ভ্যালু পেয়ার রিটার্ন করে(return all the key and value pair)।
  print(student.items())
  • get(): নির্দিষ্ট কী এর ভ্যালু রিটার্ন করে, যদি কী না থাকে তাহলে ডিফল্ট ভ্যালু রিটার্ন করে।
  print(student.get("name"))  # Output: Rahim
  print(student.get("grade", "Not Found"))  # Output: Not Found
  • update(): ডিকশনারিতে নতুন আইটেম যোগ করে বা বিদ্যমান আইটেম আপডেট করে।
  student.update({"grade": "A", "age": 22})
  print(student)
  • del : নির্দিষ্ট আইটেম মুছে ফেলে।
  del student["major"]
  print(student)
  • clear(): ডিকশনারির সব আইটেম মুছে ফেলে।
  student.clear()
  print(student)  # Output: {}
  • fromkeys(): নির্দিষ্ট কী এর জন্য একটি নতুন ডিকশনারি তৈরি করে।
  keys = ["name", "age"]
  new_dict = dict.fromkeys(keys, "Unknown")
  print(new_dict)
  • copy(): ডিকশনারির একটি কপি তৈরি করে।
  student_copy = student.copy()
  print(student_copy)
  • pop(): নির্দিষ্ট কী এর আইটেম মুছে ফেলে এবং তার ভ্যালু রিটার্ন করে।
  age = student.pop("age")
  print(age)
  • popitem(): শেষ আইটেম মুছে ফেলে এবং তা রিটার্ন করে।
  item = student.popitem()
  print(item)
  • setdefault(): নির্দিষ্ট কী এর ভ্যালু রিটার্ন করে, যদি কী না থাকে তাহলে নতুন কী-ভ্যালু পেয়ার যোগ করে।
  grade = student.setdefault("grade", "B")
  print(grade)
  • max() এবং min(): ডিকশনারির সর্বোচ্চ এবং সর্বনিম্ন কী রিটার্ন করে।
  print(max(student))  # Output: name (based on alphabetical order)
  print(min(student))  # Output: age
  • sorted(): ডিকশনারির কী গুলো সাজানো লিস্ট হিসেবে রিটার্ন করে।
  print(sorted(student))  # Output: ['age', 'grade', 'name']

এই ফাংশন এবং মেথডগুলো Python এ ডিকশনারির সাথে কাজ করতে অত্যন্ত সহায়ক। প্রতিটি মেথডের নিজস্ব ব্যবহার এবং প্রয়োজনীয়তা রয়েছে, যা ডিকশনারির ডেটা পরিচালনা করতে সাহায্য করে।

Python Module

মডিউল হল Python ফাইল যা বিভিন্ন ফাংশন, ক্লাস এবং ভেরিয়েবল ধারণ করে। এগুলি কোড পুনঃব্যবহার ও সংগঠনে সাহায্য করে।

1. মডিউল ইম্পোর্ট করা(Import Module):

a) ‘import’ স্টেটমেন্ট ব্যবহার:
python import math print(math.pi) # 3.141592653589793

b) ‘from’ স্টেটমেন্ট ব্যবহার:
python from math import sqrt print(sqrt(16)) # 4.0

2. math Module:

import math
print(math.pi)  # 3.141592653589793
print(math.e)   # 2.718281828459045
print(math.sqrt(25))  # 5.0
print(math.ceil(4.3))  # 5
print(math.floor(4.7))  # 4
print(math.pow(2, 3))  # 8.0
print(math.fabs(-5))  # 5.0
print(math.sin(math.pi/2))  # 1.0
print(math.cos(0))  # 1.0
print(math.tan(math.pi/4))  # 0.9999999999999999

3. random Module:

import random
print(random.random())  # 0 থেকে 1 এর মধ্যে একটি এলোমেলো সংখ্যা
print(random.randint(1, 10))  # 1 থেকে 10 এর মধ্যে একটি এলোমেলো পূর্ণসংখ্যা
print(random.randrange(0, 101, 5))  # 0 থেকে 100 এর মধ্যে 5 এর গুণিতক

4. statistics Module:

import statistics
data = [1, 2, 3, 4, 5, 5, 6, 7]
print(statistics.mean(data))   # Mean(গড়): 4.125
print(statistics.median(data)) # Median(মধ্যমা): 4.5
print(statistics.mode(data))   # Mode(প্রচুরক): 5

অনুশীলনী প্রোগ্রাম(Practice):
নিচের প্রোগ্রামটি লিখুন ও চালান। এটি বিভিন্ন মডিউল ব্যবহার করে একটি ছোট গণিত ও পরিসংখ্যান গেম তৈরি করে:

import math
import random
import statistics
def generate_question():
    operations = ['+', '-', '*', '/']
    num1 = random.randint(1, 20)
    num2 = random.randint(1, 20)
    operation = random.choice(operations)
    if operation == '+':
        answer = num1 + num2
    elif operation == '-':
        answer = num1 - num2
    elif operation == '*':
        answer = num1 * num2
    else:
        num1 = num1 * num2  
        answer = num1 // num2
    return f"{num1} {operation} {num2}", answer
def play_math_game():
    scores = []
    for _ in range(5):
        question, correct_answer = generate_question()
        user_answer = float(input(f"Question: {question} = "))
        if math.isclose(user_answer, correct_answer, rel_tol=1e-9):
            print("right!")
            scores.append(1)
        else:
            print(f"wrong। Correct answer was {correct_answer}")
            scores.append(0)
    return scores
def analyze_scores(scores):
    print(f"n Your score: {sum(scores)} / 5")
    print(f"Average Score: {statistics.mean(scores)}")
    print(f"Median Score: {statistics.median(scores)}")
    if len(scores) > 1:
        print(f"Standard deviation: {statistics.stdev(scores)}")
print("Welcome to math Puzzle")
scores = play_math_game()
analyze_scores(scores)
print("nBonus: Test your luck")
lucky_number = random.randint(1, 100)
guess = int(input("Guess 1 number from 1 to 10 "))
if guess == lucky_number:
    print("Congratulation! You are right !")
else:
    print(f"Sorry right number was {lucky_number}")

এই প্রোগ্রামে আমরা দেখতে পাচ্ছি:

  1. math মডিউল থেকে isclose() ফাংশন ব্যবহার করে ফ্লোটিং পয়েন্ট সংখ্যার তুলনা করা হচ্ছে।
  2. random মডিউল ব্যবহার করে এলোমেলো প্রশ্ন ও সংখ্যা তৈরি করা হচ্ছে।
  3. statistics মডিউল ব্যবহার করে স্কোরের বিশ্লেষণ করা হচ্ছে।

এই প্রোগ্রামটি চালিয়ে দেখুন। এটি আপনাকে Python-এ বিভিন্ন মডিউলের ব্যবহার সম্পর্কে একটি ভাল ধারণা দেবে।

মনে রাখবেন:

  1. মডিউল ব্যবহার করলে কোড পুনঃব্যবহার ও সংগঠন সহজ হয়।
  2. Python-এর স্ট্যান্ডার্ড লাইব্রেরিতে অনেক উপযোগী মডিউল রয়েছে।
  3. নিজের মডিউলও তৈরি করা যায়।

ফাংশন (Function):

ফাংশন হল কোডের একটি পুনঃব্যবহারযোগ্য ব্লক যা একটি নির্দিষ্ট কাজ সম্পাদন করে। এটি আপনার কোডকে সংগঠিত ও পুনঃব্যবহারযোগ্য করে তোলে।

উদাহরণ:

def greet(name):
    return f"hello, {name}! How are you?"
print(greet("Manas"))
print(greet("Halder"))

এই কোডের আউটপুট হবে:
hello Manas! How are you?
hello Halder! How are you?

এখানে:

  1. def কীওয়ার্ড দিয়ে ফাংশন সংজ্ঞায়িত(function defined) করা হয়।
  2. greet হল ফাংশনের নাম।(name of the function)
  3. name হল প্যারামিটার যা ফাংশনে পাঠানো হয়।(Parameter of function)
  4. return কীওয়ার্ড ফাংশনের ফলাফল ফেরত দেয়। (result return )

আরেকটি উদাহরণ:

def add(a, b):
    return a + b
result = add(5, 3)
print(result)  # আউটপুট হবে: 8

এই ফাংশন দুটি সংখ্যা যোগ করে এবং ফলাফল ফেরত দেয়।

এই ফাংশন দুটি সংখ্যা যোগ করে এবং ফলাফল ফেরত দেয়।

Practice Python-1Python Exercise

Exception Handling

1. Introduction:
Exception Handling হল এমন একটি পদ্ধতি যা প্রোগ্রাম চলাকালীন উদ্ভূত ত্রুটি বা অপ্রত্যাশিত পরিস্থিতি নিয়ন্ত্রণ করতে সাহায্য করে। এটি প্রোগ্রামকে নিরাপদে ও সুন্দরভাবে ত্রুটি সামাল দিতে সাহায্য করে।

2. try-except-finally ব্লক ব্যবহার করে Exception Handling:

a) try block:
এই ব্লকে সেই কোড লেখা হয় যেখানে Exception ঘটতে পারে।

b) except block:
যদি try ব্লকে কোনো Exception ঘটে, তবে এই ব্লক কার্যকর হয়। এখানে Exception হ্যান্ডল করার কোড লেখা হয়।

c) finally ব্লক:
এই ব্লকের কোড সবসময় চলবে, Exception ঘটুক বা না ঘটুক।

উদাহরণ:

try:
    x = int(input("Enter number: "))
    result = 10 / x
    print(f"Result: {result}")
except ValueError:
    print("Sorry give me valid number")
except ZeroDivisionError:
    print("Sorry Can not divide by Zero")
except Exception as e:
    print(f"Unexpected error: {e}")
finally:
    print("Program End")

3. বিভিন্ন ধরনের Exception:

  • ValueError: অবৈধ মান ব্যবহার করা হলে
  • ZeroDivisionError: শূন্য দিয়ে ভাগ করার চেষ্টা করলে
  • TypeError: ভুল টাইপের ডেটা ব্যবহার করা হলে
  • FileNotFoundError: ফাইল খুঁজে না পেলে
  • IndexError: লিস্ট বা টিউপলের অবৈধ ইনডেক্স ব্যবহার করলে

4. নিজস্ব Exception তৈরি (Own exception create):

class CustomError(Exception):
    pass
def check_age(age):
    if age < 0:
        raise CustomError("বয়স ঋণাত্মক হতে পারে না")
try:
    user_age = int(input("আপনার বয়স দিন: "))
    check_age(user_age)
    print(f"আপনার বয়স {user_age}")
except CustomError as e:
    print(f"ত্রুটি: {e}")

অনুশীলনী প্রোগ্রাম(Practice):
নিচের প্রোগ্রামটি লিখুন ও চালান। এটি Exception Handling ব্যবহার করে একটি সাধারণ ক্যালকুলেটর তৈরি করে:

def calculator():
    operations = {
        '+': lambda x, y: x + y,
        '-': lambda x, y: x - y,
        '*': lambda x, y: x * y,
        '/': lambda x, y: x / y
    }
    while True:
        try:
            num1 = float(input("First Number: "))
            num2 = float(input("Second Number "))
            operation = input("Select you operation (+, -, *, /): ")
            if operation not in operations:
                raise ValueError("Valid Operation")
            result = operations[operation](num1, num2)
            print(f"Result: {result}")
        except ValueError as ve:
            print(f"Error: {ve}। Kindly provide right number or operation")
        except ZeroDivisionError:
            print("Error: Can not Divide by Zero ")
        except Exception as e:
            print(f"Unexpected Error Occured: {e}")
        finally:
            choice = input("you want to calculate again? (yes/no): ")
            if choice.lower() != 'Yes':
                print("Thank you for using calculator")
                break
calculator()

এই প্রোগ্রামে আমরা দেখতে পাচ্ছি:

  1. বিভিন্ন ধরনের Exception হ্যান্ডল করা হচ্ছে (ValueError, ZeroDivisionError)।
  2. নিজস্ব Exception তৈরি করা হয়েছে (অবৈধ অপারেশনের জন্য ValueError raise করা)।
  3. finally ব্লক ব্যবহার করে প্রতিবার গণনার পর ব্যবহারকারীর পছন্দ জানা হচ্ছে।

এই প্রোগ্রামটি চালিয়ে দেখুন এবং বিভিন্ন ইনপুট দিয়ে পরীক্ষা করুন। এটি আপনাকে Python-এ Exception Handling সম্পর্কে একটি ভাল ধারণা দেবে।

মনে রাখবেন:

  1. Exception Handling প্রোগ্রামকে আরও রোবাস্ট ও ব্যবহারকারী-বান্ধব করে।
  2. সবসময় সুনির্দিষ্ট Exception ধরার চেষ্টা করুন, সাধারণ Exception ব্যবহার করা এড়িয়ে চলুন।
  3. finally ব্লক ব্যবহার করে নিশ্চিত করুন যে গুরুত্বপূর্ণ কাজগুলি (যেমন ফাইল বন্ধ করা) সম্পন্ন হয়।

ক্লাস ও অবজেক্ট (Class and Object):

অবজেক্ট-ওরিয়েন্টেড প্রোগ্রামিং-এর মূল ধারণা হল ক্লাস ও অবজেক্ট। ক্লাস হল একটি টেমপ্লেট, আর অবজেক্ট হল সেই টেমপ্লেট থেকে তৈরি একটি বাস্তব উদাহরণ।

উদাহরণ:

class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model
    def display_info(self):
        return f"এটি একটি {self.brand} {self.model}"
my_car = Car("BMW", "Mercedes")
print(my_car.display_info())

এই কোডের আউটপুট হবে:
BMW , Mercedes

এখানে:

  1. Car একটি ক্লাস।
  2. __init__ হল একটি বিশেষ মেথড যা অবজেক্ট তৈরির সময় কল হয়।
  3. self রিফার করে অবজেক্ট নিজেকে।
  4. my_car হল Car ক্লাসের একটি অবজেক্ট।

আরেকটি উদাহরণ:

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height
    def area(self):
        return self.width * self.height
rect = Rectangle(5, 3)
print(f"আয়তক্ষেত্রের ক্ষেত্রফল: {rect.area()}")

এই কোড আয়তক্ষেত্রের ক্ষেত্রফল গণনা করে।

Practice Python-1Python Exercise

Leave a Comment

Index