• 1
    إدخال وإخراج البيانات
    • المهام
  • 2
    الشروط
    • المهام
  • 3
    حلقة for
    • المهام
  • 4
    السلاسل النصية
    • المهام
  • 5
    حلقة while
    • المهام
  • 6
    القوائم
    • المهام
  • 7
    مصفوفات ثنائية الأبعاد
    • المهام
  • 8
    القواميس
    • المهام
  • 9
    المجموعات
    • المهام
  • 10
    الدوال والتكرار
    • المهام
  • к

درس 1. Entering and output of data

الصعوبة:

иконка человека красный иконка человека белая иконка человека зеленая Pythonlib

مسألة«مساهمة البنك»

💻 Python

تخيل أنك أتيت إلى بنك الروبل الذهبي لفتح وديعة. يعرض عليك المدير برنامجًا برسملة شهرية للفوائد. وهذا يعني أنه كل شهر تُضاف الفوائد المستحقة إلى المبلغ الأساسي للوديعة، وفي الشهر التالي سيتم احتساب الفوائد على المبلغ الجديد المتزايد.

rn

بعد عدد معين من الأشهر، ويحسب أيضًا صافي أرباحك من الوديعة. نظرًا لوجود العديد من الأرقام بعد الفاصلة العشرية، فلنأخذ فقط الجزء الصحيح من الرقم.

تنسيق الإدخال

يتلقى البرنامج ثلاث قيم كمدخلات، كل منها في سطر جديد:

rn
    rn
  1. السطر الأول: المبلغ الأولي للإيداع (يمكن أن يكون رقمًا كسريًا).
  2. rn
  3. السطر الثاني: معدل الفائدة السنوي (يمكن أن يكون رقمًا كسريًا).
  4. rn
  5. السطر الثالث: مدة الإيداع بالأشهر (رقم صحيح).
  6. rn

تنسيق الإخراج

يجب أن يعرض البرنامج سطرين:

rn
    rn
  1. في السطر الأول: النص: & nbsp; إجمالي المبلغ في الحساب: ومن ثم مسافة ثم إجمالي المبلغ (عدد صحيح). النص: & nbsp; صافي الربح: ومن ثم مسافة ثم مقدار صافي الربح (عدد صحيح).
  2. rn

مثال

إدخال

100000
12
3

إخراج

إجمالي المبلغ في الحساب: 103030.1
الربح المحقق: 3030

تلميح

Reading multiple variables from a single line

Python has a convenient way to count multiple variables in a single input() call. This is especially useful in tasks where data is served in a single line, separated by some character (most often a space).

How it works:

  1. input() reads the entire string, for example "20 30".
  2. The .split() method "cuts" this string by the specified separator (by default, by a space) and creates a list of strings: ['20', '30'].
  3. Function map(int, ...) applies the int (integer conversion) function to each element of this list. The result is a special map object.
  4. Finally, Python "unpacks" this object using the variables a and b.

Example: Input:

20 30

Reading:

a, b = map(int, input().split()) # float can be used if fractional numbers are needed
print(a, b) # outputs 20 30
print(type(a)) # outputs <class 'int'>

Useful tips:

  • If the numbers are separated not by a space, but, for example, by a comma (input: 20,30), specify this in the split() method: input().split(',').
  • Make sure that the number of variables to the left of = matches the number of values in the row. If they do not match, the program will return the error ValueError.

Three types of division

There are three different division operators in Python, and each one serves a different purpose.

  1. / Ordinary (real) division This operator always returns a fractional number (float) as a result, even if the numbers are completely divisible.

    a = 27
    b = 10
    print(a/5) # outputs 5.4
    print(b/2) # outputs 5.0 (note, not 5, but 5.0)
    
  2. // Integer division This operator performs division and discards the fractional part, returning an integer (int). It sort of answers the question "how many times does one number fit entirely into another?".

    a = 27
    print(a// 5) # outputs 5 (because 5 is placed in 27 five full times)
    
  3. % The remainder of the division (modulo division) This operator returns what is "left" after the integer division.

    a = 27
    print(a %5) # outputs 2
     Logic: the nearest number to 27 that is divisible by 5 without remainder is 25. 
    # Difference: 27-25 = 2.
    

Practical application %: The most common use of the % operator is the parity check. Any even number is divisible by 2 without remainder, and an odd number is divisible by 1.

a = 27
b = 14
print(f"Is {a} an odd number? The remainder of the division by 2: {a %2}") # outputs 1
print(f"Is {b} an even number? The remainder of the division by 2: {b %2}") # outputs 0

Exponentiation

To exponentiate a number in Python, the ** operator is used.

a = 2
b = 3
print(a**3) # outputs 8 (2 to the power of 3)
print(b**2) # outputs 9(3 to the power of 2)

Useful tips:

  • To extract the square root, you can raise the number to the power of 0.5.
    print(9**0.5) # outputs 3.0
    
  • There is also a built-in function pow(a,b) that does the same thing as a**b.
    print(pow(2, 3)) # outputs 8
    

print() function and string formatting

The print() function outputs data to the screen. Simply adding strings and variables using + is inconvenient, since numbers need to be constantly converted into strings using str(). Modern Python offers more elegant ways.

f-strings (f-strings) - recommended method: This is the most modern, fastest and most readable way. The string is preceded by the letter f, and variables or expressions are specified inside curly braces {}.

name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}")
# Output: Name: Alice, Age: 30

Advantage: you can perform operations right inside the brackets.

print(f"In a year she will be {age + 1}")
# Conclusion: In a year she will be 31

The .format() method is an older, but still relevant method: Empty curly braces {} are placed in the line, and after the line the .format() method is called, to which variables are passed.

name = "Alice"
age = 30
print("Name: {}, Age: {}".format(name, age))
# Output: Name: Alice, Age: 30

Useful tips for print():

  • Separator sep: By default, print separates its arguments with a space. This can be changed.
    print(1, 2, 3, sep="-") # outputs 1-2-3
    
  • Ending end: By default, print adds a newline after the output \n. This can also be changed so that the following print outputs continue on the same line.
    print("Hello,", end="")
    print("world!")
    # The output will be in one line: Hello, world!
    
main.py
اختبار 1
اختبار 2
اختبار 3
اختبار 4
اختبار 5
اختبار 6
اختبار 7
اختبار 8
حل المطور
# Считываем начальные данные, преобразуя их в нужные типы
initial_sum = float(input())
annual_rate = float(input())
months = int(input())

# Вычисляем месячную процентную ставку в долях от единицы
monthly_rate = annual_rate / 12 / 100

# Рассчитываем итоговую сумму по формуле сложных процентов
final_sum = initial_sum * (1 + monthly_rate) ** months

# Рассчитываем чистую прибыль
profit = final_sum - initial_sum

# Выводим результат
print("Итоговая сумма на счете:", int(final_sum))
print("Чистая прибыль:", int(profit))

🎉 تهانينا! 🎉

لقد حللت المهمة ببراعة! كان صعبًا لكنك وجدت الحل الصحيح. أنت خطوة أقرب إلى الاحتراف! استمر، كل مرحلة تجعلك أقوى.

AD

إعلان

red-snake blue-snake green-snake

جارٍ تشغيل الكود...

مساعد الذكاء الاصطناعي

مرحباً! أنا مساعدك في البرمجة. اسألني أي شيء عن Python — يمكنني شرح الدوال والطرق ومساعدتك في المهمة الحالية!