استقبال المدخلات من مستخدم البرنامج
قراءة ما يكتبه المستخدم عبر input()، ولماذا تكون المدخلات دائماً نصوصاً str، والأخطاء التي تظهر عند التحويل عبر int() و float().
- 1المشكلة
- 2الفهم
- 3أمثلة محلولة
- 4التوقع
- 5التطبيق
- 6التحدي
المشكلة التي نقوم بحلها
كل برنامج كتبناه حتى الآن كانت أرقامه وبياناته مدونة مسبقاً داخل الكود. ولتشغيله بأرقام مختلفة، كان عليك فتح الملف وتعديل الكود يدوياً.
في البرمجيات الحقيقية، لا تسير الأمور هكذا. البرنامج يسأل والمستخدم يجيب.
في بايثون، وظيفة السؤال مخصصة لدالة input(). تعلمها لا يستغرق أكثر من دقيقة، لكنها تأتي مع قاعدة ذهبية يقع فيها كل مبرمج مبتدئ: أي قيمة تُرجعها input() هي دائماً نص (str) — حتى لو قام المستخدم بكتابة رقم صحيح. عدم معرفة هذه القاعدة كفيل بتعطيل أول برنامج حسابي تبنيه.
بنهاية هذه المهمة ستكون قادراً على
- قراءة مدخلات المستخدم عبر دالة
input()مع عرض سؤال واضح - فهم سبب كون المدخلات نصوصاً (
str) دائماً - تحويل النصوص إلى أرقام عبر
int()وfloat() - التمييز بين خطأ
TypeErrorوخطأValueError - تنظيف المدخلات حتى لا تفسد المسافات الزائدة عمل برنامجك
المتطلبات المسبقة: التعامل مع النصوص — الفهرسة، التقطيع، ونصوص التنسيق.
كيف تعمل دالة input()
name = input("What is your name? ")
print(f"Hello, {name}!")شغّل الكود:
What is your name? Rafi
Hello, Rafi!حدثت ثلاثة أمور بالتسلسل: عرضت دالة input() السؤال المكتوب بين القوسين، ثم توقفت تماماً وانتظرت حتى يكتب المستخدم الإجابة ويضغط على زر Enter، ثم أرجعت ما كُتب وحفظناه في المتغير name.
هذه البرامج يجب تشغيلها داخل الطرفية. تتطلب دالةinput()تدخلاً من المستخدم في سطر الأوامر، لذا شغل الملفات دائماً عبرpython ask.pyفي طرفيتك المحلية.
مثال تطبيقي متكامل
bill.py:
# Ask for one order and print a small bill
print("--- Order entry ---")
customer = input("Customer name : ").strip().title()
item = input("Item : ").strip()
quantity = int(input("Quantity : "))
unit_price = float(input("Unit price : "))
subtotal = quantity * unit_price
tax = subtotal * 0.05
total = subtotal + tax
print()
print("--- Bill ---")
print(f"Customer : {customer}")
print(f"Item : {item} x {quantity}")
print(f"Subtotal : {subtotal:.2f}")
print(f"Tax (5%) : {tax:.2f}")
print(f"Total : {total:.2f}")--- Order entry ---
Customer name : rafi ahmed
Item : notebook
Quantity : 4
Unit price : 85.50
--- Bill ---
Customer : Rafi Ahmed
Item : notebook x 4
Subtotal : 342.00
Tax (5%) : 17.10
Total : 359.10أربعة مدخلات بأربع معالجات مختلفة: تم تنظيف الاسم وتنسيق بدايات كلماته بحروف كبيرة، وتم تنظيف اسم السلعة فقط، بينما حُوّلت الكمية إلى عدد صحيح، والسعر إلى عدد عشري.
الأخطاء الشائعة وحلولها
خطأ TypeError: can only concatenate str (not "int") to str نسيت تحويل المدخلات إلى رقم. استخدم int(input(...)) أو float(input(...)).
بدلاً من الضرب تم تكرار النص ناتج "3" * 2 هو "33". القيمة لم يتم تحويلها إلى رقم صحيح int().
خطأ ValueError: invalid literal for int() with base 10 المستخدم أدخل قيمة ليست عدداً صحيحاً (مثل نص عادي أو رقم بكسر عشري). إذا كانت الكسور ممكنة، استخدم float().
Step 4 of 6 — Predict
Check your understanding
The person types 42 and presses Enter. What does the second line print?
value = input("Number: ")
print(type(value))- A<class 'str'>
- B<class 'int'>
- C<class 'float'>
- D<class 'input'>
The person typed 3 and the program printed Doubled: 33, with no error at all. Why, and what fixes it?
qty = input("Quantity: ")
print("Doubled:", qty * 2)- A`qty` is a `str`, and multiplying text by a number repeats it — it needs `int(qty) * 2`
- BThe `print` needs a `+` instead of a comma
- CWriting `qty + qty` instead of `qty * 2` would fix it
- D`input()` cannot read numbers, so a different function is needed
What happens if the person types 12.5?
count = int(input("Count: "))
print(count + 1)- AA `ValueError` — `int()` does not accept text with a decimal point; take it with `float()` if decimals are possible
- B`count` becomes `12`, because `int()` cuts off everything after the point
- C`count` becomes `13`, because `int()` rounds to the nearest whole number
- DA `TypeError`, because the input and the variable types do not match
Answering needs an account
Sign in to check your answers
The questions are above, and working them out in your head is the part that matters. Sign in to see the answers, the explanations and the three-level hints.
دورك الآن
اكتب ملفاً باسم travel.py يسأل أربعة أسئلة ويعرض حسابات تذكرة سفر:
- اسم المسافر (منظفاً ومنسقاً)
- عدد المسافرين (عدد صحيح)
- سعر التذكرة للشخص الواحد (عدد عشري)
- نسبة الخصم المئوية (عدد عشري)
ثم اطبع السعر الإجمالي، وقيمة الخصم، والمبلغ النهائي المطلوب سداده بدقة منزلتين عشريتين.
There is more in this mission
What you read above is the complete mission — nothing was cut out of it. Pro adds:
- ما يحدث فعلياً في الكواليس — كيف ينفذ بايثون هذا الكود
- الحل الكامل للتمرين مشروحاً خطوة بخطوة
- تمارين إضافية أكثر صعوبة وتحدياً
- أسئلة المقابلات الوظيفية حول هذا الموضوع مع نموذج الإجابة
Step 6 of 6
التحدي — the chapter quiz
عشرة أسئلة متدرجة من السهل إلى الصعب. الأسئلة الأخيرة صعبة عن قصد.
Sign in to take the quiz