From a3b0585374d69e392fdb724bde30bc4048358d31 Mon Sep 17 00:00:00 2001 From: Simon Shine Date: Wed, 12 Feb 2020 04:54:36 +0100 Subject: Rename Python 3 markdown files into 'python' ``` for f in $(find . -iname "*python3*" | grep -vE 'git'); do fnew=$(echo "$f" | sed 's/python3/python/') git mv "$f" "$fnew" done --- ar-ar/python-ar.html.markdown | 1019 +++++++++++++++++++++++++++++++++++++++ ar-ar/python3-ar.html.markdown | 1019 --------------------------------------- cs-cz/python.html.markdown | 647 +++++++++++++++++++++++++ cs-cz/python3.html.markdown | 647 ------------------------- de-de/python-de.html.markdown | 655 +++++++++++++++++++++++++ de-de/python3-de.html.markdown | 655 ------------------------- el-gr/python-gr.html.markdown | 1031 +++++++++++++++++++++++++++++++++++++++ el-gr/python3-gr.html.markdown | 1031 --------------------------------------- es-es/python-es.html.markdown | 577 ++++++++++++++++++++++ es-es/python3-es.html.markdown | 577 ---------------------- fr-fr/python-fr.html.markdown | 732 ++++++++++++++++++++++++++++ fr-fr/python3-fr.html.markdown | 732 ---------------------------- it-it/python-it.html.markdown | 1016 +++++++++++++++++++++++++++++++++++++++ it-it/python3-it.html.markdown | 1016 --------------------------------------- ja-jp/python-jp.html.markdown | 1008 ++++++++++++++++++++++++++++++++++++++ ja-jp/python3-jp.html.markdown | 1008 -------------------------------------- pt-br/python-pt.html.markdown | 746 ++++++++++++++++++++++++++++ pt-br/python3-pt.html.markdown | 746 ---------------------------- python.html.markdown | 1042 ++++++++++++++++++++++++++++++++++++++++ python3.html.markdown | 1042 ---------------------------------------- ru-ru/python-ru.html.markdown | 651 +++++++++++++++++++++++++ ru-ru/python3-ru.html.markdown | 651 ------------------------- tr-tr/python-tr.html.markdown | 640 ++++++++++++++++++++++++ tr-tr/python3-tr.html.markdown | 640 ------------------------ vi-vn/python-vi.html.markdown | 914 +++++++++++++++++++++++++++++++++++ vi-vn/python3-vi.html.markdown | 914 ----------------------------------- zh-cn/python-cn.html.markdown | 632 ++++++++++++++++++++++++ zh-cn/python3-cn.html.markdown | 632 ------------------------ 28 files changed, 11310 insertions(+), 11310 deletions(-) create mode 100644 ar-ar/python-ar.html.markdown delete mode 100644 ar-ar/python3-ar.html.markdown create mode 100644 cs-cz/python.html.markdown delete mode 100644 cs-cz/python3.html.markdown create mode 100644 de-de/python-de.html.markdown delete mode 100644 de-de/python3-de.html.markdown create mode 100644 el-gr/python-gr.html.markdown delete mode 100644 el-gr/python3-gr.html.markdown create mode 100644 es-es/python-es.html.markdown delete mode 100644 es-es/python3-es.html.markdown create mode 100644 fr-fr/python-fr.html.markdown delete mode 100644 fr-fr/python3-fr.html.markdown create mode 100644 it-it/python-it.html.markdown delete mode 100644 it-it/python3-it.html.markdown create mode 100644 ja-jp/python-jp.html.markdown delete mode 100644 ja-jp/python3-jp.html.markdown create mode 100644 pt-br/python-pt.html.markdown delete mode 100644 pt-br/python3-pt.html.markdown create mode 100644 python.html.markdown delete mode 100644 python3.html.markdown create mode 100644 ru-ru/python-ru.html.markdown delete mode 100644 ru-ru/python3-ru.html.markdown create mode 100644 tr-tr/python-tr.html.markdown delete mode 100644 tr-tr/python3-tr.html.markdown create mode 100644 vi-vn/python-vi.html.markdown delete mode 100644 vi-vn/python3-vi.html.markdown create mode 100644 zh-cn/python-cn.html.markdown delete mode 100644 zh-cn/python3-cn.html.markdown diff --git a/ar-ar/python-ar.html.markdown b/ar-ar/python-ar.html.markdown new file mode 100644 index 00000000..e1a12690 --- /dev/null +++ b/ar-ar/python-ar.html.markdown @@ -0,0 +1,1019 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["evuez", "http://github.com/evuez"] + - ["Rommel Martinez", "https://ebzzry.io"] + - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] +translators: + - ["Ahmad Hegazy", "https://github.com/ahegazy"] +lang: ar-ar +filename: learnpython3-ar.py +--- + +لقد أُنشئت لغة البايثون بواسطة جايدو ڤان روسم في بداية التسعينات. هي الأن أحد أشهر اللغات الموجودة. +لقد أحببت لغة البايثون بسبب وضوحها. هي في الأساس عبارة عن سودوكود قابل للتنفيذ. + +ردود أفعالكم عن المقال مُقدرة بشدة. يمكنكم التواصل مع الكاتب الاساسي من خلال [@louiedinh](http://twitter.com/louiedinh) أو louiedinh [at] [google's email service] + +ملحوظة: هذا المقال يُطبق على بايثون 3 فقط. راجع المقال [هنا](http://learnxinyminutes.com/docs/python/) إذا أردت تعلم لغة البايثون نسخة 2.7 الأقدم + +```python + +# تعليق من سطر واحد يبدأ برمز الرقم. + +""" يمكن كتابة تعليق يتكون من أكثر من سطر + باستخدام ثلاثة علامات " + ، وعادة يُستخدم في كتابة التوثيقات. +""" + +#################################################### +## 1. أنواع البيانات البدائية والعمليات +#################################################### + +# لديك أرقام +3 # => 3 + +# العمليات الحسابية هي ما تتوقعه +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 + +# نتائج قسمة الأرقام الصحيحية تُقرب للأصغر سواءًا كانت الأرقام موجبة أو سالبة. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # يعمل في حالة الكسور أيضا +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# ناتج القسمة هو دائما كسر +10.0 / 3 # => 3.3333333333333335 + +# عملية باقي القسمة +7 % 3 # => 1 + +# الأُس (س ** ص، رفع س لقوى ص) +2**3 # => 8 + +# أفرض ترتيب العمليات الحسابية بالأقواس +(1 + 3) * 2 # => 8 + +# القيم الثنائية هي المعروفة عموما (ﻻحظ: تكبير أول حرف) +True +False + +# أنفي بـ (not) +not True # => False +not False # => True + +# العمليات على القيم الثنائية +# ﻻحظ ﻻيهم حالة الحرف (كبير أو صغير) في "and" و "or" +True and False # => False +False or True # => True + +# True و False هما في الواقع 1 و 0 لكن بمسميات مختلفة +True + True # => 2 +True * 8 # => 8 +False - 5 # => -5 + +# عمليات المقارنة تنظر الي القيمة الرقمية لل True وال False +0 == False # => True +1 == True # => True +2 == True # => False +-5 != False # => True + +# عند استخدام المنطق الثنائي على القيم الصحيحة يتم تحويلهم الي قيم ثنائية لإجرات العمليات عليهم، لكن قيمهم الأصلية تعود +# ﻻ تخلط بين bool(قيمة صحيحة) و العمليات المنطقية الثناية and/or (&,|) +bool(0) # => False +bool(4) # => True +bool(-6) # => True +0 and 2 # => 0 +-5 or 0 # => -5 + +# مقارنة التساوي ب == +1 == 1 # => True +2 == 1 # => False + +# مقارنة الاختلاف ب != +1 != 1 # => False +2 != 1 # => True + +# مقارنات أخرى +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# لمعرفة هل القيمة في نطاق معين +1 < 2 and 2 < 3 # => True +2 < 3 and 3 < 2 # => False + +# التسلسل يجعلها تبدو أجمل +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (is مقابل ==) is تتحق من أن المتغيرين يشيران إلي نفس العنصر, +# لكن == تتحقق من أن العنصرين المُشار اليهما بالمتغيرين لهما نفس القيمة. +a = [1, 2, 3, 4] # اجعل a تشير إلي قائمة جديدة, [1, 2, 3, 4] +b = a # اجعل a تُشير الي ما تُشير إليه b +b is a # => True, a و b يُشيران إلي نفس العنصر +b == a # => True, قيمة عنصر a و b متساوية +b = [1, 2, 3, 4] # اجعل b تشير الي قائمة جديدة , [1, 2, 3, 4] +b is a # => False, a و b do ﻻ يشيران إلي نفس العنصر +b == a # => True, قيمة عنصر a و b متساوية + +# يمكنك إنشاء الكلمات (تسلسلات الحروف) عن طريق " أو ' +"This is a string." +'This is also a string.' + +# يمكنك جمع هذا النوع أيضا! لكن حاول ألا تفعل هذا. +"Hello " + "world!" # => "Hello world!" +# يمكنك الربط بين الكلمات بدون استخدام '+' (لكن ليس المتغيرات) +"Hello " "world!" # => "Hello world!" + +# يمكنك معاملة الكلمات كقائمة من الحروف +"This is a string"[0] # => 'T' + +# يمكنك معرفة طول الكلمة +len("This is a string") # => 16 + +# .format يمكنك استخدامها لبناء الجمل بشكل معين, مثل هذا: +"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" + +# يمكنك تكرار معاملات بناء الجملة لتقليل الكتابة. +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# يمكنك استخدام الكلمات المفتاحية إذا لم تُرد العد. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" + +# إذا كان كود بايثون 3 الخاص بك يحتاج لبايثون 2.5 أو نسخة أقدم +# يمكنك استخدام أسلوب بناء الجمل القديم: +"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" + +# يمكنك أبضا بناء الجمل باستخدام f-strings أو حروف بناء الجمل (في بايثون 3.6 فما فوق) +name = "Reiko" +f"She said her name is {name}." # => "She said her name is Reiko" +# يمكنك ببساطة وضع أي كود بايثون داخل أقواس وستقوم بإخراج الجملة. +f"{name} is {len(name)} characters long." + + +# None عبارة عن كائن +None # => None + +# ﻻ تستخدم رمز المساواة "==" لمقارنة العناصر ب None +# استخدم is بدلا منه. يقوم بالتحقق من مساواة هوية العنصر +"etc" is None # => False +None is None # => True + +# None, 0, قوائم/جمل/قواميس/صفوف فارغة كلها تُترجم إلي False. +# كل القيم الأخرى True. +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False +bool(()) # => False + +#################################################### +## 2. المتغيرات والمجموعات +#################################################### + +# بايثون لديها دالة عرض "print" +print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! + +# الافتراضي دالة print تطبع سطر جديد في النهاية. +# استخدم المعامل end لتغيير أخر الجملة المعروضة. +print("Hello, World", end="!") # => Hello, World! + +# طريقة بسيطة لطلب مدخل من الطرفية +input_string_var = input("Enter some data: ") # يقوم بإعادة البيانات ك "string" +# لاحظ: في النسخ القديمة من بايثون، دالة input() كان اسمها raw_input() + +# ﻻ يوجد تعريفات للمتغيرات، يتم تعيين قيمة المتغير مباشرة. +# العٌرف تسمية المتغيرات حروف_صغيرة_مع_خطوط_سُفلية +some_var = 5 +some_var # => 5 + +# محاولة استخدام متغير غير مُعين يعتبر خطأ +# إقرأ جزء 3.مسار التحكم لمعرفة المزيد عن التحكم في الأخطاء +some_unknown_var # يعرض خطأ NameError + +# يمكن استخدام if كتعبير واحد +# مساوِ للتعبير الأتي في لغة السي '?:' عملية ثلاثية +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# القوائم تحفظ المتسلسلات +li = [] +# يمكنك البدأ بقائمة مليئة +other_li = [4, 5, 6] + +# إضافة بيانات لأخر القائمة عن طريق append +li.append(1) # li is now [1] +li.append(2) # li is now [1, 2] +li.append(4) # li is now [1, 2, 4] +li.append(3) # li is now [1, 2, 4, 3] +# حذف أخر عنصر في القائمة عن طريق pop +li.pop() # => 3 and li is now [1, 2, 4] +# هيا نعيده ثانية +li.append(3) # li is now [1, 2, 4, 3] again. + +# يمكنك الوصول لعناصر القائمة كما تفعل في ال array +# Access a list like you would any array +li[0] # => 1 +# للوصول لأخر عنصر +li[-1] # => 3 + +# محاولة الوصول لعنصر خارج نطاق القائمة يعتبر خطأ: IndexError +li[4] # يعرض خطأ IndexError + +# يمكنك النظر للنطاقات باستخدام تركيب التقطيع +# مؤشر/رقم/فهرس البداية مُضمن، مؤشر النهاية ﻻ +# (لمحبي الرياضيات هو نطاق مفتوح/مغلق) +li[1:3] # => [2, 4] +# إحذف أول عنصر ثم إعرض القائمة +li[2:] # => [4, 3] +# إحذف أخر عنصر ثم إعرض القائمة +li[:3] # => [1, 2, 4] +# حدد عنصر ثم إحذف الذي يليه ثم حدد عنصر وهكذا +li[::2] # =>[1, 4] +# اعرض نسخة معكوسة من القائمة +li[::-1] # => [3, 4, 2, 1] +# إستخدم أي تجميعة من الطرق المذكورة لعمل تقطيعات متقدمة +# li[start:end:step] + +# عمل نسخة من طبقة واحدة باستخدم التقطيع +li2 = li[:] # => li2 = [1, 2, 4, 3] لكن عند عمل(li2 is li) سينتج False. + +# إمسح أي عنصر من القائمة باستخدام "del" +del li[2] # li is now [1, 2, 3] + +# إمسح أول ظهور لقيمة. +li.remove(2) # li is now [1, 3] +li.remove(2) # يعرض خطأ ValueError لأن 2 غير موجود في القائمة + +# أضف عنصر في خانة معينة +li.insert(1, 2) # li is now [1, 2, 3] مرة أخرى + +# أحصل على مؤشر/رقم لأول ظهور للقيمة +li.index(2) # => 1 +li.index(4) # يعرض خطأ ValueError لأن 4 غير موجودة في القائمة + +# يمكنك جمع قوائم +# لاحظ: لا يتم تعديل قيمة li و other_li +li + other_li # => [1, 2, 3, 4, 5, 6] + +# إستخدم دالة "extend()" لربط القوائم +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] + +# راجع وجود قيمة في القائمة باستخدام "in" +1 in li # => True + +# إحصل على طول القائمة باستخدام دالة "len()" +len(li) # => 6 + + +# الصفوف تشبه القوائم لكنها غير قابلة للتغيير. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # يعرض خطأ TypeError + +# لاحظ أن صف طوله عنصر واحد يحتاج لإضافة فاصلة "," بعد أخر عنصر +# لكن الصفوف من أي طول أخر، حتى صفر لا تحتاج. +type((1)) # => +type((1,)) # => +type(()) # => + +# يمكنك عمل معظم عمليات القوائم على الصفوف. +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# يمكنك تفريغ الصفوف (أو القوائم) في متغيرات +a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +# يمكنك أيضا عمل تفريغ واسع +a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4 +# الصفوف تُنشأ تلقائيا إذا تركت الأقواس +d, e, f = 4, 5, 6 # تم توسعة الصف 4, 5 ,6 في المتغيرات d, e, f +# بالترتيب حيث d = 4, e = 5 و f = 6 +# الأن إنظر إلي مدى سهولة التبديل بين قيم متغيرين +e, d = d, e # d is now 5 and e is now 4 + + +# القواميس تُخزن خرائط من المفتاح للقيمة +empty_dict = {} +# هذا قاموس مملوء +filled_dict = {"one": 1, "two": 2, "three": 3} + +# لاحظ أن القواميس يجب أن تكون أنواع غير قابلة للتغيير. +# هذا للتأكد من أن المفتاح يمكن تحويله لقيمة ثابتة للوصول السريع. +# الأنواع الغير قابلة للتغير تتضمن: الأرقام الصحيحة، الكسور، الكلمات، الصفوف. +invalid_dict = {[1,2,3]: "123"} # =>يعرض خطأ TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # القيم يمكن أن تكون من أي نوع. + +# يمكنك البحث عن قيمة باستخدام [] +filled_dict["one"] # => 1 + +# يمكنك الحصول على كل المفاتيح باستخدام "keys()". +# نحتاج لإرسالها لدالة list() لتحويلها لقائمة. سنتعلم هذا لاحقًا +# لاحظ - لنسخ بايثون قبل 3.7، ترتيب مفاتيح القاموس غير مضمون. نتائجك +# يمكن ألا تساوي المثال بالأسفل. مع ذلك، من أول بايثون 3.7، +# عناصر القاموس تحتفظ بالترتيب الذي تم إضافة المفاتيح به في القاموس. +list(filled_dict.keys()) # => ["three", "two", "one"] in Python <3.7 +list(filled_dict.keys()) # => ["one", "two", "three"] in Python 3.7+ + +# يمكنك الحصول على كل القيم باستخدام "values()". +# مرة أخرى نستخدم list() للحصول عليها كقائمة. +# نفس الكلام السابق بخصوص ترتيب المفاتيح +list(filled_dict.values()) # => [3, 2, 1] in Python <3.7 +list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+ + +# إفحص للتأكد من وجود مغتاح في القاموس باستخدام "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# البحث عن مفتاح غير موجود يعرض خطأ KeyError +filled_dict["four"] # KeyError + +# استخدم "get()" لتجنب الخطأ KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# دالة get تدعم إدخال قيمة افتراضية عند عدم وجود البحث +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# "setdefault()" تقوم بإدخال قيمة جديدة في القاموس في حالة عدم وجود المفتاح فقط. +filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 + +# إضافة عنصر للقاموس +filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} +filled_dict["four"] = 4 # طريقة أخرى للإضافة + +# مسح المفاتيح من القاموس باستخدام del +del filled_dict["one"] # Removes the key "one" from filled dict + +# من بايثون 3.5 فما فوق يمكنك أيضا استخدام خيارات تفريغ إضافية +{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} +{'a': 1, **{'a': 2}} # => {'a': 2} + + +# المجموعات تُخزن .. مجموعات +empty_set = set() +# .تهيئة مجموعة بمجموعة قيم. نعم، تشبه قليلا تهيئة القاموس. أسف +some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} + +# مثل مفتاح القاموس، عناصر المجموعة يجب أن تكون غير قابلة للتغيير. +invalid_set = {[1], 1} # => يعرض خطأ TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# إضافة عنصر أخر للمجموعة +filled_set = some_set +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} +# المجموعات لا يمكن أن تحتوي على عناصر مكررة +filled_set.add(5) # it remains as before {1, 2, 3, 4, 5} + +# تقاطع مجموعتين باستخدام & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# اتحاد مجموعتين باستخدام | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# الفرق بين مجموعتين باستخدام - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# الفروق بين مجموعتين باستخدام ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# لفحص هل المجموعة على اليسار مجموعة عُليا للمجموعة على اليمين (تحتوي على كل عناصرها) +{1, 2} >= {1, 2, 3} # => False + +# لفحص هل المجموعة على اليسار مجموعة فرعية من المجموعة على اليمين +{1, 2} <= {1, 2, 3} # => True + +# للتأكد من وجود عن في مجموعة استخدم in +2 in filled_set # => True +10 in filled_set # => False + + + +#################################################### +## 3. مسار التحكم والعمليات التكرارية #Control Flow and Iterables +#################################################### + +# هيا ننشيء متغير +some_var = 5 + +# الأن الأمر if. الفجوات (المسافات قبل الأوامر) مهمة في البايثون! +# العُرف استخدام أربع مسافات. ليس تبويب. +# هذا السطر البرمجي يطبع "some_var is smaller than 10" +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # This elif clause is optional. + print("some_var is smaller than 10.") +else: # This is optional too. + print("some_var is indeed 10.") + + +""" +For عبارة عن حلقات تدور حول عناصر قوائم +:ثم تطبع + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # يمكنك استخدام format() لترجمة كلمات بشكل معين. + print("{} is a mammal".format(animal)) + +""" +"range(number)" يقوم بإعادة مجموعة من الأرقام يمكن الدوران حولها +من الصفر إلي رقم معين +ثم يطبع: + 0 + 1 + 2 + 3 +""" + +for i in range(4): + print(i) + +""" +"range(lower, upper)" يقوم بإعادة مجموعة من الأرقام يمكن الدوران حولها من القيمة السُفلى +lower حتى القيمة العُليا upper +ثم يطبع: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(lower, upper, step)" يقوم بإعادة مجموعة من الأرقام يمكن الدوران حولها من القيمة السُفلى +lower حتى القيمة العُليا upper، ثم يقوم بالزيادة قيمة الstep. +إذا لم تُحدد ال step, القيمة الأفتراضية 1. +ثم يطبع: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) + +""" +While هي عبارة عن حلقات تدور حتى عدم تحقق شرط معين. +وتطبع: + 0 + 1 + 2 + 3 +""" +x = 0 for +while x < 4: + print(x) + x += 1 # اختصار ل x = x + 1 + +# يمكنك التحكم في الأخطاء والاستثناءات باستخدام مجموعة try/except +try: + # استخدم "raise" لرفع خطأ. + raise IndexError("This is an index error") +except IndexError as e: + pass # Pass: هو مجرد أمر ﻻ تفعل شيء. عادة تقوم بتصحيح الخطأ هنا. +except (TypeError, NameError): + pass # يمكنك التحكم في أكثر من خطأ في نفس الوقت، إذا أقتضت الضرورة +else: # فقرة اختيارية في مجموعة try/except. يجب أن يتبع جميع مجموعات معارضة الأخطاء + print("All good!") # تُنفذ في حالة أن السطور البرمجية داخل ال try لم ترفع أي خطأ +finally: # تُنفذ في كل الحالات + print("We can clean up resources here") + +# بدلا من مجموعة try/finally لتنظيف الموارد يمكنك استخدام سطر with +with open("myfile.txt") as f: + for line in f: + print(line) + +# يتيح البايثون تجريد أساسي يسمى المُكرَر. +# المُكرٍَر عبارة عن متغير يمكن التعامل معه كسلسلة. +# الكائن الذي يعود من دالة نطاق، يسمى المُكرَر. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => dict_keys(['one', 'two', 'three']) +# هذا عبارة عن متغير يعرض عناصر مفاتيح المُكرَر. + +# يمكننا الدوران حوله. +for i in our_iterable: + print(i) # Prints one, two, three + +# مع ذلك ﻻ يمكننا الوصول للعناصر بالمؤشر. +our_iterable[1] # يرفع خطأ TypeError + +# المُكرَر هو عبارة عن عنصر يعلم كيفية إنشاء مُكرِر +our_iterator = iter(our_iterable) + +# المُكرِر هو عبارة عن عنصر يمكنه تذكر الحالة أثناء مرورنا بعناصره. +# يمكننا الحصول على العنصر التالي عن طريق "next()" +next(our_iterator) # => "one" + +# يحفظ الحالة أثناء الدوران. +next(our_iterator) # => "two" +next(our_iterator) # => "three" + +# بعد عرض المُكرِر كل عناصره، يرفع استثناء StopIteration +next(our_iterator) # يرفع StopIteration + +# يمكنك الحصول على كل عناصر المُكرر بمناداة دالة list() عليه. +list(filled_dict.keys()) # => Returns ["one", "two", "three"] + + +#################################################### +## 4. الدوال +#################################################### + +# إستخدم "def" لإنشاء دوال جديدة. +def add(x, y): + print("x is {} and y is {}".format(x, y)) + return x + y # يمكنك إرجاع قيمة من الدالة بسطر return + +# مناداة دوال بمعطيات +add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 + +# طريقة أخرى لمناداة دوال باستخدام كلمات مفتاحية. +add(y=6, x=5) # الكلمة المفتاحية يمكن أن تُعطى بأي ترتيب. + +# يمكنك تعريف دوال تأخذ عدد متغير من المُعطيات + +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# يمكنك تعريف دوال تأخذ عدد متغير من الكلمات المفتاحية كمعطيات أيضا. +def keyword_args(**kwargs): + return kwargs + +# هيا ننادي على الدالة لنرى ماذا سيحدث +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# يمكنك فعل الأثنين معًا في نفس الوقت، إذا أردت +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# عندما تنادي على دوال، يمكنك عمل عكس المعطيات/المفاتيح! +# استخدم * لتوسعة الصفوف، واستخدم ** لتوسعة المفاتيح. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # مساوٍ ل all_the_args(1, 2, 3, 4) +all_the_args(**kwargs) # مساوٍ ل to all_the_args(a=3, b=4) +all_the_args(*args, **kwargs) # مساوٍ ل to all_the_args(1, 2, 3, 4, a=3, b=4) + +# يقوم بإعادة مجموعة من القيم (بتعيين الصفوف) +def swap(x, y): + return y, x # يقوم بإعادة مجموعة من القيم على شكل صفوف بدون الأقواس + # (لاحظ: الأقواس حُذفت لكن يمكن إضافتها) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # مرة أخرى الأقواس حُذفت لكن يمكن إضافتها. + +# مجال الدالة +x = 5 + +def set_x(num): + # المتغير المحلي x ليس هو المتغير العام x + x = num # => 43 + print(x) # => 43 + +def set_global_x(num): + global x + print(x) # => 5 + x = num #المتغير العام x الأن مساوٍ ل 6 + print(x) # => 6 + +set_x(43) +set_global_x(6) + + +# بايثون تدعم دوال الفئة أولية [first class functions] (أي أنه يمكن إرسال الدوال كمعطيات لدوال أخرى) +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# يوجد أيضا دوال مجهولة +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# يوجد دوال مدمجة من درجة أعلى +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] + +list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] + +# يمكن إشتمال القوائم على خرائط وفلاتر حسنة الشكل +# هذه القوائم تحفظ المُخرج كقائمة والتي بدورها يمكن أن تكون قائمة مداخلة +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# يمكنك بناء مجموعات وقواميس على هذا المنوال أيضا +{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +## 5. الوحدات البرمجية (الموديولات) +#################################################### + +# يمكنك استدعاء موديولات +import math +print(math.sqrt(16)) # => 4.0 + +# يمكنك استدعاء دالة معينة من موديول +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# يمكنك استدعاء كل الدوال من مديول. +# تحذير: هذا الفعل غير موصى به +from math import * + +# يمكنك تصغير اسم موديول +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# موديولات البايثون عبارة عن ملفات بايثون عادية. +# يمكنك كتابة الموديولات الخاصة بك, واستدعاها. +# اسم الموديول يكون نفس اسم الملف. + +# يمكنك معرفة أي الدوال والصفات مُعرفة في الموديول. +import math +dir(math) + +# إذا كان لديك سكربت بايثون يسمى math.py +# في نفس المجلد الموجود به السكربت الخاص بك، الملف الخاص بك math.py +# سَيُستدعى بدلا من موديول البايثون بنفس الاسم +# هذا يحدث لأن المجلدات المحلية لديها أولوية عن مكتبات البايثون المُدمجة + + +#################################################### +## 6. الفئات/القوالب (الكلاسات) +#################################################### + +# نستخدم السطر البرمجي "class" لإنشاء قالب +class Human: + + # صفة القالب. مشتركة بين كل نسخ القالب + species = "H. sapiens" + + # مُهيئ إبتدائي، يُنادى عليه عندما يتم استدعاء القالب. + # لاحظ أن الشرطة السٌفلية المُكررة مرتين __ قبل وبعد الاسم تُعبر عن الكائنات + # أو الصفات المُستخدمة عن طريق بايثون لكنها تعيش في مساحة تحكم المُستخدم. + # العمليات -الدوال- (أو الكائنات أو الصفات) مثل: __init__, __str__,__repr__ ألخ. + # تُسمى عمليات خاصة (أو أحيانا تسمى عمليات سحرية أو dunder methods) + # يجب عليك ألا تُسمي مثل هذه الاسماء بنفسك. + def __init__(self, name): + # ساوِ المُعطى بالصفة name الخاصة بهذه النسخة من القالب. + self.name = name + + # هيئ الصفة + self._age = 0 + + # عملية/دالة خاصة بنسخة القالب. كل العمليات تأخذ "self" كأول مُعطى + # An instance method. All methods take "self" as the first argument + def say(self, msg): + print("{name}: {message}".format(name=self.name, message=msg)) + + # عملية أخرى خاصة بنسخة القالب. + def sing(self): + return 'yo... yo... microphone check... one two... one two...' + + # عمليات القالب مشتركة بين كل أجزاء القالب + # يتم مناداتهم عن طريق جعل القالب المُنادي أول معطى + # They are called with the calling class as the first argument + @classmethod + def get_species(cls): + return cls.species + + # تُنادى العملية الثابتة بدون قالب أو نسخة قالب + @staticmethod + def grunt(): + return "*grunt*" + + # الخاصية تشبه تماما إمر الطلب + # تُحَوِل العملية age() إلي صفة مقروءة فقط بنفس الاسم. + # ﻻ حاجة لكتابة أوامر طلب أو تهيئة + @property + def age(self): + return self._age + + # هذا يتيح تهيئة الخاصية + @age.setter + def age(self, age): + self._age = age + + # هذا يتيح حذف الخاصية + @age.deleter + def age(self): + del self._age + + +# عندما يقرأ مُترجم البايثون ملف مصدري يقوم بتنفيذ كل الكود. +# فحص ال __name__ يجعل هذا الجزء من الكود يُنَفَذ فقط +# في حالة أن هذا الموديول هو البرنامج الرئيسي +if __name__ == '__main__': + # Instantiate a class + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # i و j نُسخ من النوع Human, أول بكلمات أخرى: هما كائنات للقالب Human + + # نادي على عملية القالب + i.say(i.get_species()) # "Ian: H. sapiens" + # عدل الخاصية المُشتركة + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # نادي على العملية الثابتة + print(Human.grunt()) # => "*grunt*" + + # لا يمكن مناداة العملية الثابتة من نسخة الكائن + # لأن i.grunt() سيقوم تلقائيا بوضع "self" (الكائن i) كمُعطى للعملية + print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given + + # حدًث الخاصية لهذه النسخة + i.age = 42 + # أحصل على الخاصية + i.say(i.age) # => "Ian: 42" + j.say(j.age) # => "Joel: 0" + # إحذف الخاصية + del i.age + # i.age # => سوف يرفع استثناء AttributeError + + +#################################################### +## 6.1 الإرث +#################################################### + +# الإرث يتيح لقالب ابن أن يُعَرف ويرث بعض عمليات/دوال ومتغيرات القالب الأب. + +# باستخدام القالب Human المُعَرف بالأعلى كأساس أو كقالب أب، +# يمكننا تعريف قالب ابن،Superhero ، يرث متغيرات القالب مثل "species", "name", و "age"، +# وأيضا العمليات، مثل "sing", "grunt" +# من القالب Human، لكنه أيضا لديه خواصه الفريدة + +# للاستفادة من التقطيع بالملف يمكنك وضع القوالب بالأعلى في ملفاتهم الخاصة، +# مثلا، human.py + +# لاستيراد دالة من ملف أخر استخدم الطريقة التالية +# from "اسم الملف بدون مُلحق" import "اسم الدالة أو القالب" + +from human import Human + +# حدد القالب/ات الأب كمُعطى أثناء تعريف القالب. +class Superhero(Human): + + # إذا أردت أن يرث القالب الابن كل تعريفات القالب الأب بدون تعديل + # يمكنك استخدام الكلمة المفتاحية "pass" (بدون شيء أخر) + # لكن في هذه الحالة تم أهمالها لإنشاء قالب ابن فريد: + # pass + + # القوالب الابن يمكنها تعديل صفات القوالب الأب + species = 'Superhuman' + + # القوالب الابن ترث تلقائيا عمليات الإنشاء الخاصة بالقالب الأب بالإضافة إلي مُعطياتهم + # لكن يمكن أيضا تعريف مُعطيات إضافية أو تعريفات + # وتعديل العمليات مثل منشيء القالب. + # هذا المُنشيء يرث المُعطى "name" من القالب "Human" + # ويضيف المعطيات"superpower" و "movies": + def __init__(self, name, movie=False, + superpowers=["super strength", "bulletproofing"]): + + # إضافة صفة جديدة للقالب + self.fictional = True + self.movie = movie + # كن على علم بالقيم الافتراضية المتغيرة، حيث أن القيم الافتراضية تُشارك + self.superpowers = superpowers + + # الدالة "super" تتيح لك الوصول لعمليات القالب الأب + # التي تم تغييرها عن طريق الابن، في هذه الحالة، العملية __init__< + # هذا السطر يُنادي على منشيء القالب الأب. + super().__init__(name) + + # تعديل العملية sing + def sing(self): + return 'Dun, dun, DUN!' + + # إضافة عملية جديدة للنسخة + def boast(self): + for power in self.superpowers: + print("I wield the power of {pow}!".format(pow=power)) + + +if __name__ == '__main__': + sup = Superhero(name="Tick") + + # فحص نوع النسخة + if isinstance(sup, Human): + print('I am human') + if type(sup) is Superhero: + print('I am a superhero') + + # إحصل على ترتيب قرار البحث للعملية (Method Resolution search Order) المُستخدمة بواسطة العمليات getattr() و super() + # هذه الصفة ديناميكية ويمكن أن تُحَدًث. + print(Superhero.__mro__) # => (, + # => , ) + + # نادي العملية الأب لكن استخدم صفات القالب الخاص بها. + print(sup.get_species()) # => Superhuman + + # نادي العملية المُعدلة. + print(sup.sing()) # => Dun, dun, DUN! + + # نادي العملية من القالب Human + sup.say('Spoon') # => Tick: Spoon + + # نادي عملية موجودة فقط في Superhero + sup.boast() # => I wield the power of super strength! + # => I wield the power of bulletproofing! + + # وَرَثَ صفات القالب + sup.age = 31 + print(sup.age) # => 31 + + # صفة موجودة فقط في القالب Superhero + print('Am I Oscar eligible? ' + str(sup.movie)) + +#################################################### +## 6.2 الإرث المُتعدد +#################################################### + +# تعريف قالب أخرA +# bat.py +class Bat: + + species = 'Baty' + + def __init__(self, can_fly=True): + self.fly = can_fly + + # هذا القالب لديه عملية تسمى say + def say(self, msg): + msg = '... ... ...' + return msg + + # ولديه عمليته الخاصة به أيضا + def sonar(self): + return '))) ... (((' + +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) + +# تعريف قالب أخر يرث من Superhero و Bat +# superhero.py +from superhero import Superhero +from bat import Bat + +# عَرٍف Batman كقالب ابن يرث من كلا من Superhero و Bat +class Batman(Superhero, Bat): + + def __init__(self, *args, **kwargs): + # عادة لكي ترث صفة يجد أن تنادي على super: + # super(Batman, self).__init__(*args, **kwargs) + # لكننا في هذه الحالة نتعامل مع إرث متعدد هنا، و super() + # تعمل فقط مع القالب التالي في قائمة ال MRO. + # لذا بدلا من ذلك ننادي على __init__ صراحة لكل الأباء. + # استخدام *args و **kwargs يتيح طريقة نظيفة لتمرير المعطيات. + # لكل أب "تقشير طبقة من البصل". + Superhero.__init__(self, 'anonymous', movie=True, + superpowers=['Wealthy'], *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # تعديل قيمة الصفة name + self.name = 'Sad Affleck' + + def sing(self): + return 'nan nan nan nan nan batman!' + + +if __name__ == '__main__': + sup = Batman() + + # إحصل على ترتيب قرار البحث للعملية (Method Resolution search Order) المُستخدمة بواسطة العمليات getattr() و super() + # هذه الصفة ديناميكية ويمكن أن تُحَدًث. + print(Batman.__mro__) # => (, + # => , + # => , + # => , ) + + # نادي على العملية الخاصة بالأب لكن استخدم الصفات الخاصة بالقالب الابن + print(sup.get_species()) # => Superhuman + + # نادي على العملية المُعدلة + print(sup.sing()) # => nan nan nan nan nan batman! + + # نادي على العملية من القالب Human, لأن الترتيب في الأرث مهم. + sup.say('I agree') # => Sad Affleck: I agree + + # نادي على العملية الموجودة فقط في القالب الأب الثاني + print(sup.sonar()) # => ))) ... ((( + + # الصفة الموروثة من القالب الأب + sup.age = 100 + print(sup.age) # => 100 + + # الصفة الموروثة من القالب الأب الثاني، الذي تم تعديل قيمته الافتراضية + print('Can I fly? ' + str(sup.fly)) # => Can I fly? False + + + +#################################################### +## 7. مُتَقدم +#################################################### + +# المولدات تُساعدك على كتابة كود كسول. +def double_numbers(iterable): + for i in iterable: + yield i + i + +# المولدات فعالة من حيث الذاكرة، لأنها تُحمٍل الذاكرة بالبيانات التي تحتاج +# لإجراء العملية عليها في الخطوة التالية في المُكَرِر. +# هذا يتيح إجراء عمليات على قيم كبيرة ممنوعة في حالات أخرى. +# ﻻحظ: `range` بديل ل `xrange` في بايثون 3. +for i in double_numbers(range(1, 900000000)): # `range` is a generator. + print(i) + if i >= 30: + break + +# كما يمكنك إنشاء قوائم اشتمال، يمكنك إنشاء مولدات اشتمال أيضا +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # prints -1 -2 -3 -4 -5 to console/terminal + +# يمكنك أيضا تغيير نوع مولد الاشتمال مباشرة إلي قائمة +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + + +# المُحسنات +# في هذا المثال الدالة`beg` تُغلف الدالة `say`. +# إذا كانت say_please تساوي True +# إذا ستُغير الرسالة الراجعة من الدالة +from functools import wraps + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # Can you buy me a beer? +print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( +``` + +## جاهز للمزيد? + +### مجانا عبر الانترنت + +* [أتمتتة المهمات المُملة عبر بايثون](https://automatetheboringstuff.com) +* [أفكار لمشروعات بلغة البايثون](http://pythonpracticeprojects.com) +* [التوثيقات الرسمية](http://docs.python.org/3/) +* [دليل المُسافر لبايثون](http://docs.python-guide.org/en/latest/) +* [دورة بايثون](http://www.python-course.eu/index.php) +* [أولى الخطوات مع بايثون](https://realpython.com/learn/python-first-steps/) +* [قائمة مُختارة من إطارات عمل بايثون الرائعة, المكتبات والبرمجيات](https://github.com/vinta/awesome-python) +* [ثلاثون خاصية وخدعة للغة البايثون ربما لم تعرف بها](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [الدليل الرسمي لنمط البايثون](https://www.python.org/dev/peps/pep-0008/) +* [بايثون 3 دوائر علوم الحاسب](http://cscircles.cemc.uwaterloo.ca/) +* [غُص في بايثون 3](http://www.diveintopython3.net/index.html) +* [دورة سريعة في البايثون للعلماء](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/ar-ar/python3-ar.html.markdown b/ar-ar/python3-ar.html.markdown deleted file mode 100644 index e1a12690..00000000 --- a/ar-ar/python3-ar.html.markdown +++ /dev/null @@ -1,1019 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] - - ["evuez", "http://github.com/evuez"] - - ["Rommel Martinez", "https://ebzzry.io"] - - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] -translators: - - ["Ahmad Hegazy", "https://github.com/ahegazy"] -lang: ar-ar -filename: learnpython3-ar.py ---- - -لقد أُنشئت لغة البايثون بواسطة جايدو ڤان روسم في بداية التسعينات. هي الأن أحد أشهر اللغات الموجودة. -لقد أحببت لغة البايثون بسبب وضوحها. هي في الأساس عبارة عن سودوكود قابل للتنفيذ. - -ردود أفعالكم عن المقال مُقدرة بشدة. يمكنكم التواصل مع الكاتب الاساسي من خلال [@louiedinh](http://twitter.com/louiedinh) أو louiedinh [at] [google's email service] - -ملحوظة: هذا المقال يُطبق على بايثون 3 فقط. راجع المقال [هنا](http://learnxinyminutes.com/docs/python/) إذا أردت تعلم لغة البايثون نسخة 2.7 الأقدم - -```python - -# تعليق من سطر واحد يبدأ برمز الرقم. - -""" يمكن كتابة تعليق يتكون من أكثر من سطر - باستخدام ثلاثة علامات " - ، وعادة يُستخدم في كتابة التوثيقات. -""" - -#################################################### -## 1. أنواع البيانات البدائية والعمليات -#################################################### - -# لديك أرقام -3 # => 3 - -# العمليات الحسابية هي ما تتوقعه -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7.0 - -# نتائج قسمة الأرقام الصحيحية تُقرب للأصغر سواءًا كانت الأرقام موجبة أو سالبة. -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # يعمل في حالة الكسور أيضا --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# ناتج القسمة هو دائما كسر -10.0 / 3 # => 3.3333333333333335 - -# عملية باقي القسمة -7 % 3 # => 1 - -# الأُس (س ** ص، رفع س لقوى ص) -2**3 # => 8 - -# أفرض ترتيب العمليات الحسابية بالأقواس -(1 + 3) * 2 # => 8 - -# القيم الثنائية هي المعروفة عموما (ﻻحظ: تكبير أول حرف) -True -False - -# أنفي بـ (not) -not True # => False -not False # => True - -# العمليات على القيم الثنائية -# ﻻحظ ﻻيهم حالة الحرف (كبير أو صغير) في "and" و "or" -True and False # => False -False or True # => True - -# True و False هما في الواقع 1 و 0 لكن بمسميات مختلفة -True + True # => 2 -True * 8 # => 8 -False - 5 # => -5 - -# عمليات المقارنة تنظر الي القيمة الرقمية لل True وال False -0 == False # => True -1 == True # => True -2 == True # => False --5 != False # => True - -# عند استخدام المنطق الثنائي على القيم الصحيحة يتم تحويلهم الي قيم ثنائية لإجرات العمليات عليهم، لكن قيمهم الأصلية تعود -# ﻻ تخلط بين bool(قيمة صحيحة) و العمليات المنطقية الثناية and/or (&,|) -bool(0) # => False -bool(4) # => True -bool(-6) # => True -0 and 2 # => 0 --5 or 0 # => -5 - -# مقارنة التساوي ب == -1 == 1 # => True -2 == 1 # => False - -# مقارنة الاختلاف ب != -1 != 1 # => False -2 != 1 # => True - -# مقارنات أخرى -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# لمعرفة هل القيمة في نطاق معين -1 < 2 and 2 < 3 # => True -2 < 3 and 3 < 2 # => False - -# التسلسل يجعلها تبدو أجمل -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# (is مقابل ==) is تتحق من أن المتغيرين يشيران إلي نفس العنصر, -# لكن == تتحقق من أن العنصرين المُشار اليهما بالمتغيرين لهما نفس القيمة. -a = [1, 2, 3, 4] # اجعل a تشير إلي قائمة جديدة, [1, 2, 3, 4] -b = a # اجعل a تُشير الي ما تُشير إليه b -b is a # => True, a و b يُشيران إلي نفس العنصر -b == a # => True, قيمة عنصر a و b متساوية -b = [1, 2, 3, 4] # اجعل b تشير الي قائمة جديدة , [1, 2, 3, 4] -b is a # => False, a و b do ﻻ يشيران إلي نفس العنصر -b == a # => True, قيمة عنصر a و b متساوية - -# يمكنك إنشاء الكلمات (تسلسلات الحروف) عن طريق " أو ' -"This is a string." -'This is also a string.' - -# يمكنك جمع هذا النوع أيضا! لكن حاول ألا تفعل هذا. -"Hello " + "world!" # => "Hello world!" -# يمكنك الربط بين الكلمات بدون استخدام '+' (لكن ليس المتغيرات) -"Hello " "world!" # => "Hello world!" - -# يمكنك معاملة الكلمات كقائمة من الحروف -"This is a string"[0] # => 'T' - -# يمكنك معرفة طول الكلمة -len("This is a string") # => 16 - -# .format يمكنك استخدامها لبناء الجمل بشكل معين, مثل هذا: -"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" - -# يمكنك تكرار معاملات بناء الجملة لتقليل الكتابة. -"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" - -# يمكنك استخدام الكلمات المفتاحية إذا لم تُرد العد. -"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" - -# إذا كان كود بايثون 3 الخاص بك يحتاج لبايثون 2.5 أو نسخة أقدم -# يمكنك استخدام أسلوب بناء الجمل القديم: -"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" - -# يمكنك أبضا بناء الجمل باستخدام f-strings أو حروف بناء الجمل (في بايثون 3.6 فما فوق) -name = "Reiko" -f"She said her name is {name}." # => "She said her name is Reiko" -# يمكنك ببساطة وضع أي كود بايثون داخل أقواس وستقوم بإخراج الجملة. -f"{name} is {len(name)} characters long." - - -# None عبارة عن كائن -None # => None - -# ﻻ تستخدم رمز المساواة "==" لمقارنة العناصر ب None -# استخدم is بدلا منه. يقوم بالتحقق من مساواة هوية العنصر -"etc" is None # => False -None is None # => True - -# None, 0, قوائم/جمل/قواميس/صفوف فارغة كلها تُترجم إلي False. -# كل القيم الأخرى True. -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False -bool(()) # => False - -#################################################### -## 2. المتغيرات والمجموعات -#################################################### - -# بايثون لديها دالة عرض "print" -print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! - -# الافتراضي دالة print تطبع سطر جديد في النهاية. -# استخدم المعامل end لتغيير أخر الجملة المعروضة. -print("Hello, World", end="!") # => Hello, World! - -# طريقة بسيطة لطلب مدخل من الطرفية -input_string_var = input("Enter some data: ") # يقوم بإعادة البيانات ك "string" -# لاحظ: في النسخ القديمة من بايثون، دالة input() كان اسمها raw_input() - -# ﻻ يوجد تعريفات للمتغيرات، يتم تعيين قيمة المتغير مباشرة. -# العٌرف تسمية المتغيرات حروف_صغيرة_مع_خطوط_سُفلية -some_var = 5 -some_var # => 5 - -# محاولة استخدام متغير غير مُعين يعتبر خطأ -# إقرأ جزء 3.مسار التحكم لمعرفة المزيد عن التحكم في الأخطاء -some_unknown_var # يعرض خطأ NameError - -# يمكن استخدام if كتعبير واحد -# مساوِ للتعبير الأتي في لغة السي '?:' عملية ثلاثية -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# القوائم تحفظ المتسلسلات -li = [] -# يمكنك البدأ بقائمة مليئة -other_li = [4, 5, 6] - -# إضافة بيانات لأخر القائمة عن طريق append -li.append(1) # li is now [1] -li.append(2) # li is now [1, 2] -li.append(4) # li is now [1, 2, 4] -li.append(3) # li is now [1, 2, 4, 3] -# حذف أخر عنصر في القائمة عن طريق pop -li.pop() # => 3 and li is now [1, 2, 4] -# هيا نعيده ثانية -li.append(3) # li is now [1, 2, 4, 3] again. - -# يمكنك الوصول لعناصر القائمة كما تفعل في ال array -# Access a list like you would any array -li[0] # => 1 -# للوصول لأخر عنصر -li[-1] # => 3 - -# محاولة الوصول لعنصر خارج نطاق القائمة يعتبر خطأ: IndexError -li[4] # يعرض خطأ IndexError - -# يمكنك النظر للنطاقات باستخدام تركيب التقطيع -# مؤشر/رقم/فهرس البداية مُضمن، مؤشر النهاية ﻻ -# (لمحبي الرياضيات هو نطاق مفتوح/مغلق) -li[1:3] # => [2, 4] -# إحذف أول عنصر ثم إعرض القائمة -li[2:] # => [4, 3] -# إحذف أخر عنصر ثم إعرض القائمة -li[:3] # => [1, 2, 4] -# حدد عنصر ثم إحذف الذي يليه ثم حدد عنصر وهكذا -li[::2] # =>[1, 4] -# اعرض نسخة معكوسة من القائمة -li[::-1] # => [3, 4, 2, 1] -# إستخدم أي تجميعة من الطرق المذكورة لعمل تقطيعات متقدمة -# li[start:end:step] - -# عمل نسخة من طبقة واحدة باستخدم التقطيع -li2 = li[:] # => li2 = [1, 2, 4, 3] لكن عند عمل(li2 is li) سينتج False. - -# إمسح أي عنصر من القائمة باستخدام "del" -del li[2] # li is now [1, 2, 3] - -# إمسح أول ظهور لقيمة. -li.remove(2) # li is now [1, 3] -li.remove(2) # يعرض خطأ ValueError لأن 2 غير موجود في القائمة - -# أضف عنصر في خانة معينة -li.insert(1, 2) # li is now [1, 2, 3] مرة أخرى - -# أحصل على مؤشر/رقم لأول ظهور للقيمة -li.index(2) # => 1 -li.index(4) # يعرض خطأ ValueError لأن 4 غير موجودة في القائمة - -# يمكنك جمع قوائم -# لاحظ: لا يتم تعديل قيمة li و other_li -li + other_li # => [1, 2, 3, 4, 5, 6] - -# إستخدم دالة "extend()" لربط القوائم -li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] - -# راجع وجود قيمة في القائمة باستخدام "in" -1 in li # => True - -# إحصل على طول القائمة باستخدام دالة "len()" -len(li) # => 6 - - -# الصفوف تشبه القوائم لكنها غير قابلة للتغيير. -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # يعرض خطأ TypeError - -# لاحظ أن صف طوله عنصر واحد يحتاج لإضافة فاصلة "," بعد أخر عنصر -# لكن الصفوف من أي طول أخر، حتى صفر لا تحتاج. -type((1)) # => -type((1,)) # => -type(()) # => - -# يمكنك عمل معظم عمليات القوائم على الصفوف. -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# يمكنك تفريغ الصفوف (أو القوائم) في متغيرات -a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 -# يمكنك أيضا عمل تفريغ واسع -a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4 -# الصفوف تُنشأ تلقائيا إذا تركت الأقواس -d, e, f = 4, 5, 6 # تم توسعة الصف 4, 5 ,6 في المتغيرات d, e, f -# بالترتيب حيث d = 4, e = 5 و f = 6 -# الأن إنظر إلي مدى سهولة التبديل بين قيم متغيرين -e, d = d, e # d is now 5 and e is now 4 - - -# القواميس تُخزن خرائط من المفتاح للقيمة -empty_dict = {} -# هذا قاموس مملوء -filled_dict = {"one": 1, "two": 2, "three": 3} - -# لاحظ أن القواميس يجب أن تكون أنواع غير قابلة للتغيير. -# هذا للتأكد من أن المفتاح يمكن تحويله لقيمة ثابتة للوصول السريع. -# الأنواع الغير قابلة للتغير تتضمن: الأرقام الصحيحة، الكسور، الكلمات، الصفوف. -invalid_dict = {[1,2,3]: "123"} # =>يعرض خطأ TypeError: unhashable type: 'list' -valid_dict = {(1,2,3):[1,2,3]} # القيم يمكن أن تكون من أي نوع. - -# يمكنك البحث عن قيمة باستخدام [] -filled_dict["one"] # => 1 - -# يمكنك الحصول على كل المفاتيح باستخدام "keys()". -# نحتاج لإرسالها لدالة list() لتحويلها لقائمة. سنتعلم هذا لاحقًا -# لاحظ - لنسخ بايثون قبل 3.7، ترتيب مفاتيح القاموس غير مضمون. نتائجك -# يمكن ألا تساوي المثال بالأسفل. مع ذلك، من أول بايثون 3.7، -# عناصر القاموس تحتفظ بالترتيب الذي تم إضافة المفاتيح به في القاموس. -list(filled_dict.keys()) # => ["three", "two", "one"] in Python <3.7 -list(filled_dict.keys()) # => ["one", "two", "three"] in Python 3.7+ - -# يمكنك الحصول على كل القيم باستخدام "values()". -# مرة أخرى نستخدم list() للحصول عليها كقائمة. -# نفس الكلام السابق بخصوص ترتيب المفاتيح -list(filled_dict.values()) # => [3, 2, 1] in Python <3.7 -list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+ - -# إفحص للتأكد من وجود مغتاح في القاموس باستخدام "in" -"one" in filled_dict # => True -1 in filled_dict # => False - -# البحث عن مفتاح غير موجود يعرض خطأ KeyError -filled_dict["four"] # KeyError - -# استخدم "get()" لتجنب الخطأ KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# دالة get تدعم إدخال قيمة افتراضية عند عدم وجود البحث -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 - -# "setdefault()" تقوم بإدخال قيمة جديدة في القاموس في حالة عدم وجود المفتاح فقط. -filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 - -# إضافة عنصر للقاموس -filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} -filled_dict["four"] = 4 # طريقة أخرى للإضافة - -# مسح المفاتيح من القاموس باستخدام del -del filled_dict["one"] # Removes the key "one" from filled dict - -# من بايثون 3.5 فما فوق يمكنك أيضا استخدام خيارات تفريغ إضافية -{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} -{'a': 1, **{'a': 2}} # => {'a': 2} - - -# المجموعات تُخزن .. مجموعات -empty_set = set() -# .تهيئة مجموعة بمجموعة قيم. نعم، تشبه قليلا تهيئة القاموس. أسف -some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} - -# مثل مفتاح القاموس، عناصر المجموعة يجب أن تكون غير قابلة للتغيير. -invalid_set = {[1], 1} # => يعرض خطأ TypeError: unhashable type: 'list' -valid_set = {(1,), 1} - -# إضافة عنصر أخر للمجموعة -filled_set = some_set -filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} -# المجموعات لا يمكن أن تحتوي على عناصر مكررة -filled_set.add(5) # it remains as before {1, 2, 3, 4, 5} - -# تقاطع مجموعتين باستخدام & -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# اتحاد مجموعتين باستخدام | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# الفرق بين مجموعتين باستخدام - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# الفروق بين مجموعتين باستخدام ^ -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# لفحص هل المجموعة على اليسار مجموعة عُليا للمجموعة على اليمين (تحتوي على كل عناصرها) -{1, 2} >= {1, 2, 3} # => False - -# لفحص هل المجموعة على اليسار مجموعة فرعية من المجموعة على اليمين -{1, 2} <= {1, 2, 3} # => True - -# للتأكد من وجود عن في مجموعة استخدم in -2 in filled_set # => True -10 in filled_set # => False - - - -#################################################### -## 3. مسار التحكم والعمليات التكرارية #Control Flow and Iterables -#################################################### - -# هيا ننشيء متغير -some_var = 5 - -# الأن الأمر if. الفجوات (المسافات قبل الأوامر) مهمة في البايثون! -# العُرف استخدام أربع مسافات. ليس تبويب. -# هذا السطر البرمجي يطبع "some_var is smaller than 10" -if some_var > 10: - print("some_var is totally bigger than 10.") -elif some_var < 10: # This elif clause is optional. - print("some_var is smaller than 10.") -else: # This is optional too. - print("some_var is indeed 10.") - - -""" -For عبارة عن حلقات تدور حول عناصر قوائم -:ثم تطبع - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - # يمكنك استخدام format() لترجمة كلمات بشكل معين. - print("{} is a mammal".format(animal)) - -""" -"range(number)" يقوم بإعادة مجموعة من الأرقام يمكن الدوران حولها -من الصفر إلي رقم معين -ثم يطبع: - 0 - 1 - 2 - 3 -""" - -for i in range(4): - print(i) - -""" -"range(lower, upper)" يقوم بإعادة مجموعة من الأرقام يمكن الدوران حولها من القيمة السُفلى -lower حتى القيمة العُليا upper -ثم يطبع: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -"range(lower, upper, step)" يقوم بإعادة مجموعة من الأرقام يمكن الدوران حولها من القيمة السُفلى -lower حتى القيمة العُليا upper، ثم يقوم بالزيادة قيمة الstep. -إذا لم تُحدد ال step, القيمة الأفتراضية 1. -ثم يطبع: - 4 - 6 -""" -for i in range(4, 8, 2): - print(i) - -""" -While هي عبارة عن حلقات تدور حتى عدم تحقق شرط معين. -وتطبع: - 0 - 1 - 2 - 3 -""" -x = 0 for -while x < 4: - print(x) - x += 1 # اختصار ل x = x + 1 - -# يمكنك التحكم في الأخطاء والاستثناءات باستخدام مجموعة try/except -try: - # استخدم "raise" لرفع خطأ. - raise IndexError("This is an index error") -except IndexError as e: - pass # Pass: هو مجرد أمر ﻻ تفعل شيء. عادة تقوم بتصحيح الخطأ هنا. -except (TypeError, NameError): - pass # يمكنك التحكم في أكثر من خطأ في نفس الوقت، إذا أقتضت الضرورة -else: # فقرة اختيارية في مجموعة try/except. يجب أن يتبع جميع مجموعات معارضة الأخطاء - print("All good!") # تُنفذ في حالة أن السطور البرمجية داخل ال try لم ترفع أي خطأ -finally: # تُنفذ في كل الحالات - print("We can clean up resources here") - -# بدلا من مجموعة try/finally لتنظيف الموارد يمكنك استخدام سطر with -with open("myfile.txt") as f: - for line in f: - print(line) - -# يتيح البايثون تجريد أساسي يسمى المُكرَر. -# المُكرٍَر عبارة عن متغير يمكن التعامل معه كسلسلة. -# الكائن الذي يعود من دالة نطاق، يسمى المُكرَر. - -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) # => dict_keys(['one', 'two', 'three']) -# هذا عبارة عن متغير يعرض عناصر مفاتيح المُكرَر. - -# يمكننا الدوران حوله. -for i in our_iterable: - print(i) # Prints one, two, three - -# مع ذلك ﻻ يمكننا الوصول للعناصر بالمؤشر. -our_iterable[1] # يرفع خطأ TypeError - -# المُكرَر هو عبارة عن عنصر يعلم كيفية إنشاء مُكرِر -our_iterator = iter(our_iterable) - -# المُكرِر هو عبارة عن عنصر يمكنه تذكر الحالة أثناء مرورنا بعناصره. -# يمكننا الحصول على العنصر التالي عن طريق "next()" -next(our_iterator) # => "one" - -# يحفظ الحالة أثناء الدوران. -next(our_iterator) # => "two" -next(our_iterator) # => "three" - -# بعد عرض المُكرِر كل عناصره، يرفع استثناء StopIteration -next(our_iterator) # يرفع StopIteration - -# يمكنك الحصول على كل عناصر المُكرر بمناداة دالة list() عليه. -list(filled_dict.keys()) # => Returns ["one", "two", "three"] - - -#################################################### -## 4. الدوال -#################################################### - -# إستخدم "def" لإنشاء دوال جديدة. -def add(x, y): - print("x is {} and y is {}".format(x, y)) - return x + y # يمكنك إرجاع قيمة من الدالة بسطر return - -# مناداة دوال بمعطيات -add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 - -# طريقة أخرى لمناداة دوال باستخدام كلمات مفتاحية. -add(y=6, x=5) # الكلمة المفتاحية يمكن أن تُعطى بأي ترتيب. - -# يمكنك تعريف دوال تأخذ عدد متغير من المُعطيات - -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - -# يمكنك تعريف دوال تأخذ عدد متغير من الكلمات المفتاحية كمعطيات أيضا. -def keyword_args(**kwargs): - return kwargs - -# هيا ننادي على الدالة لنرى ماذا سيحدث -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# يمكنك فعل الأثنين معًا في نفس الوقت، إذا أردت -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) prints: - (1, 2) - {"a": 3, "b": 4} -""" - -# عندما تنادي على دوال، يمكنك عمل عكس المعطيات/المفاتيح! -# استخدم * لتوسعة الصفوف، واستخدم ** لتوسعة المفاتيح. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # مساوٍ ل all_the_args(1, 2, 3, 4) -all_the_args(**kwargs) # مساوٍ ل to all_the_args(a=3, b=4) -all_the_args(*args, **kwargs) # مساوٍ ل to all_the_args(1, 2, 3, 4, a=3, b=4) - -# يقوم بإعادة مجموعة من القيم (بتعيين الصفوف) -def swap(x, y): - return y, x # يقوم بإعادة مجموعة من القيم على شكل صفوف بدون الأقواس - # (لاحظ: الأقواس حُذفت لكن يمكن إضافتها) - -x = 1 -y = 2 -x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # مرة أخرى الأقواس حُذفت لكن يمكن إضافتها. - -# مجال الدالة -x = 5 - -def set_x(num): - # المتغير المحلي x ليس هو المتغير العام x - x = num # => 43 - print(x) # => 43 - -def set_global_x(num): - global x - print(x) # => 5 - x = num #المتغير العام x الأن مساوٍ ل 6 - print(x) # => 6 - -set_x(43) -set_global_x(6) - - -# بايثون تدعم دوال الفئة أولية [first class functions] (أي أنه يمكن إرسال الدوال كمعطيات لدوال أخرى) -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# يوجد أيضا دوال مجهولة -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# يوجد دوال مدمجة من درجة أعلى -list(map(add_10, [1, 2, 3])) # => [11, 12, 13] -list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] - -list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] - -# يمكن إشتمال القوائم على خرائط وفلاتر حسنة الشكل -# هذه القوائم تحفظ المُخرج كقائمة والتي بدورها يمكن أن تكون قائمة مداخلة -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -# يمكنك بناء مجموعات وقواميس على هذا المنوال أيضا -{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} -{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} - - -#################################################### -## 5. الوحدات البرمجية (الموديولات) -#################################################### - -# يمكنك استدعاء موديولات -import math -print(math.sqrt(16)) # => 4.0 - -# يمكنك استدعاء دالة معينة من موديول -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# يمكنك استدعاء كل الدوال من مديول. -# تحذير: هذا الفعل غير موصى به -from math import * - -# يمكنك تصغير اسم موديول -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# موديولات البايثون عبارة عن ملفات بايثون عادية. -# يمكنك كتابة الموديولات الخاصة بك, واستدعاها. -# اسم الموديول يكون نفس اسم الملف. - -# يمكنك معرفة أي الدوال والصفات مُعرفة في الموديول. -import math -dir(math) - -# إذا كان لديك سكربت بايثون يسمى math.py -# في نفس المجلد الموجود به السكربت الخاص بك، الملف الخاص بك math.py -# سَيُستدعى بدلا من موديول البايثون بنفس الاسم -# هذا يحدث لأن المجلدات المحلية لديها أولوية عن مكتبات البايثون المُدمجة - - -#################################################### -## 6. الفئات/القوالب (الكلاسات) -#################################################### - -# نستخدم السطر البرمجي "class" لإنشاء قالب -class Human: - - # صفة القالب. مشتركة بين كل نسخ القالب - species = "H. sapiens" - - # مُهيئ إبتدائي، يُنادى عليه عندما يتم استدعاء القالب. - # لاحظ أن الشرطة السٌفلية المُكررة مرتين __ قبل وبعد الاسم تُعبر عن الكائنات - # أو الصفات المُستخدمة عن طريق بايثون لكنها تعيش في مساحة تحكم المُستخدم. - # العمليات -الدوال- (أو الكائنات أو الصفات) مثل: __init__, __str__,__repr__ ألخ. - # تُسمى عمليات خاصة (أو أحيانا تسمى عمليات سحرية أو dunder methods) - # يجب عليك ألا تُسمي مثل هذه الاسماء بنفسك. - def __init__(self, name): - # ساوِ المُعطى بالصفة name الخاصة بهذه النسخة من القالب. - self.name = name - - # هيئ الصفة - self._age = 0 - - # عملية/دالة خاصة بنسخة القالب. كل العمليات تأخذ "self" كأول مُعطى - # An instance method. All methods take "self" as the first argument - def say(self, msg): - print("{name}: {message}".format(name=self.name, message=msg)) - - # عملية أخرى خاصة بنسخة القالب. - def sing(self): - return 'yo... yo... microphone check... one two... one two...' - - # عمليات القالب مشتركة بين كل أجزاء القالب - # يتم مناداتهم عن طريق جعل القالب المُنادي أول معطى - # They are called with the calling class as the first argument - @classmethod - def get_species(cls): - return cls.species - - # تُنادى العملية الثابتة بدون قالب أو نسخة قالب - @staticmethod - def grunt(): - return "*grunt*" - - # الخاصية تشبه تماما إمر الطلب - # تُحَوِل العملية age() إلي صفة مقروءة فقط بنفس الاسم. - # ﻻ حاجة لكتابة أوامر طلب أو تهيئة - @property - def age(self): - return self._age - - # هذا يتيح تهيئة الخاصية - @age.setter - def age(self, age): - self._age = age - - # هذا يتيح حذف الخاصية - @age.deleter - def age(self): - del self._age - - -# عندما يقرأ مُترجم البايثون ملف مصدري يقوم بتنفيذ كل الكود. -# فحص ال __name__ يجعل هذا الجزء من الكود يُنَفَذ فقط -# في حالة أن هذا الموديول هو البرنامج الرئيسي -if __name__ == '__main__': - # Instantiate a class - i = Human(name="Ian") - i.say("hi") # "Ian: hi" - j = Human("Joel") - j.say("hello") # "Joel: hello" - # i و j نُسخ من النوع Human, أول بكلمات أخرى: هما كائنات للقالب Human - - # نادي على عملية القالب - i.say(i.get_species()) # "Ian: H. sapiens" - # عدل الخاصية المُشتركة - Human.species = "H. neanderthalensis" - i.say(i.get_species()) # => "Ian: H. neanderthalensis" - j.say(j.get_species()) # => "Joel: H. neanderthalensis" - - # نادي على العملية الثابتة - print(Human.grunt()) # => "*grunt*" - - # لا يمكن مناداة العملية الثابتة من نسخة الكائن - # لأن i.grunt() سيقوم تلقائيا بوضع "self" (الكائن i) كمُعطى للعملية - print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given - - # حدًث الخاصية لهذه النسخة - i.age = 42 - # أحصل على الخاصية - i.say(i.age) # => "Ian: 42" - j.say(j.age) # => "Joel: 0" - # إحذف الخاصية - del i.age - # i.age # => سوف يرفع استثناء AttributeError - - -#################################################### -## 6.1 الإرث -#################################################### - -# الإرث يتيح لقالب ابن أن يُعَرف ويرث بعض عمليات/دوال ومتغيرات القالب الأب. - -# باستخدام القالب Human المُعَرف بالأعلى كأساس أو كقالب أب، -# يمكننا تعريف قالب ابن،Superhero ، يرث متغيرات القالب مثل "species", "name", و "age"، -# وأيضا العمليات، مثل "sing", "grunt" -# من القالب Human، لكنه أيضا لديه خواصه الفريدة - -# للاستفادة من التقطيع بالملف يمكنك وضع القوالب بالأعلى في ملفاتهم الخاصة، -# مثلا، human.py - -# لاستيراد دالة من ملف أخر استخدم الطريقة التالية -# from "اسم الملف بدون مُلحق" import "اسم الدالة أو القالب" - -from human import Human - -# حدد القالب/ات الأب كمُعطى أثناء تعريف القالب. -class Superhero(Human): - - # إذا أردت أن يرث القالب الابن كل تعريفات القالب الأب بدون تعديل - # يمكنك استخدام الكلمة المفتاحية "pass" (بدون شيء أخر) - # لكن في هذه الحالة تم أهمالها لإنشاء قالب ابن فريد: - # pass - - # القوالب الابن يمكنها تعديل صفات القوالب الأب - species = 'Superhuman' - - # القوالب الابن ترث تلقائيا عمليات الإنشاء الخاصة بالقالب الأب بالإضافة إلي مُعطياتهم - # لكن يمكن أيضا تعريف مُعطيات إضافية أو تعريفات - # وتعديل العمليات مثل منشيء القالب. - # هذا المُنشيء يرث المُعطى "name" من القالب "Human" - # ويضيف المعطيات"superpower" و "movies": - def __init__(self, name, movie=False, - superpowers=["super strength", "bulletproofing"]): - - # إضافة صفة جديدة للقالب - self.fictional = True - self.movie = movie - # كن على علم بالقيم الافتراضية المتغيرة، حيث أن القيم الافتراضية تُشارك - self.superpowers = superpowers - - # الدالة "super" تتيح لك الوصول لعمليات القالب الأب - # التي تم تغييرها عن طريق الابن، في هذه الحالة، العملية __init__< - # هذا السطر يُنادي على منشيء القالب الأب. - super().__init__(name) - - # تعديل العملية sing - def sing(self): - return 'Dun, dun, DUN!' - - # إضافة عملية جديدة للنسخة - def boast(self): - for power in self.superpowers: - print("I wield the power of {pow}!".format(pow=power)) - - -if __name__ == '__main__': - sup = Superhero(name="Tick") - - # فحص نوع النسخة - if isinstance(sup, Human): - print('I am human') - if type(sup) is Superhero: - print('I am a superhero') - - # إحصل على ترتيب قرار البحث للعملية (Method Resolution search Order) المُستخدمة بواسطة العمليات getattr() و super() - # هذه الصفة ديناميكية ويمكن أن تُحَدًث. - print(Superhero.__mro__) # => (, - # => , ) - - # نادي العملية الأب لكن استخدم صفات القالب الخاص بها. - print(sup.get_species()) # => Superhuman - - # نادي العملية المُعدلة. - print(sup.sing()) # => Dun, dun, DUN! - - # نادي العملية من القالب Human - sup.say('Spoon') # => Tick: Spoon - - # نادي عملية موجودة فقط في Superhero - sup.boast() # => I wield the power of super strength! - # => I wield the power of bulletproofing! - - # وَرَثَ صفات القالب - sup.age = 31 - print(sup.age) # => 31 - - # صفة موجودة فقط في القالب Superhero - print('Am I Oscar eligible? ' + str(sup.movie)) - -#################################################### -## 6.2 الإرث المُتعدد -#################################################### - -# تعريف قالب أخرA -# bat.py -class Bat: - - species = 'Baty' - - def __init__(self, can_fly=True): - self.fly = can_fly - - # هذا القالب لديه عملية تسمى say - def say(self, msg): - msg = '... ... ...' - return msg - - # ولديه عمليته الخاصة به أيضا - def sonar(self): - return '))) ... (((' - -if __name__ == '__main__': - b = Bat() - print(b.say('hello')) - print(b.fly) - -# تعريف قالب أخر يرث من Superhero و Bat -# superhero.py -from superhero import Superhero -from bat import Bat - -# عَرٍف Batman كقالب ابن يرث من كلا من Superhero و Bat -class Batman(Superhero, Bat): - - def __init__(self, *args, **kwargs): - # عادة لكي ترث صفة يجد أن تنادي على super: - # super(Batman, self).__init__(*args, **kwargs) - # لكننا في هذه الحالة نتعامل مع إرث متعدد هنا، و super() - # تعمل فقط مع القالب التالي في قائمة ال MRO. - # لذا بدلا من ذلك ننادي على __init__ صراحة لكل الأباء. - # استخدام *args و **kwargs يتيح طريقة نظيفة لتمرير المعطيات. - # لكل أب "تقشير طبقة من البصل". - Superhero.__init__(self, 'anonymous', movie=True, - superpowers=['Wealthy'], *args, **kwargs) - Bat.__init__(self, *args, can_fly=False, **kwargs) - # تعديل قيمة الصفة name - self.name = 'Sad Affleck' - - def sing(self): - return 'nan nan nan nan nan batman!' - - -if __name__ == '__main__': - sup = Batman() - - # إحصل على ترتيب قرار البحث للعملية (Method Resolution search Order) المُستخدمة بواسطة العمليات getattr() و super() - # هذه الصفة ديناميكية ويمكن أن تُحَدًث. - print(Batman.__mro__) # => (, - # => , - # => , - # => , ) - - # نادي على العملية الخاصة بالأب لكن استخدم الصفات الخاصة بالقالب الابن - print(sup.get_species()) # => Superhuman - - # نادي على العملية المُعدلة - print(sup.sing()) # => nan nan nan nan nan batman! - - # نادي على العملية من القالب Human, لأن الترتيب في الأرث مهم. - sup.say('I agree') # => Sad Affleck: I agree - - # نادي على العملية الموجودة فقط في القالب الأب الثاني - print(sup.sonar()) # => ))) ... ((( - - # الصفة الموروثة من القالب الأب - sup.age = 100 - print(sup.age) # => 100 - - # الصفة الموروثة من القالب الأب الثاني، الذي تم تعديل قيمته الافتراضية - print('Can I fly? ' + str(sup.fly)) # => Can I fly? False - - - -#################################################### -## 7. مُتَقدم -#################################################### - -# المولدات تُساعدك على كتابة كود كسول. -def double_numbers(iterable): - for i in iterable: - yield i + i - -# المولدات فعالة من حيث الذاكرة، لأنها تُحمٍل الذاكرة بالبيانات التي تحتاج -# لإجراء العملية عليها في الخطوة التالية في المُكَرِر. -# هذا يتيح إجراء عمليات على قيم كبيرة ممنوعة في حالات أخرى. -# ﻻحظ: `range` بديل ل `xrange` في بايثون 3. -for i in double_numbers(range(1, 900000000)): # `range` is a generator. - print(i) - if i >= 30: - break - -# كما يمكنك إنشاء قوائم اشتمال، يمكنك إنشاء مولدات اشتمال أيضا -values = (-x for x in [1,2,3,4,5]) -for x in values: - print(x) # prints -1 -2 -3 -4 -5 to console/terminal - -# يمكنك أيضا تغيير نوع مولد الاشتمال مباشرة إلي قائمة -values = (-x for x in [1,2,3,4,5]) -gen_to_list = list(values) -print(gen_to_list) # => [-1, -2, -3, -4, -5] - - -# المُحسنات -# في هذا المثال الدالة`beg` تُغلف الدالة `say`. -# إذا كانت say_please تساوي True -# إذا ستُغير الرسالة الراجعة من الدالة -from functools import wraps - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please - - -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( -``` - -## جاهز للمزيد? - -### مجانا عبر الانترنت - -* [أتمتتة المهمات المُملة عبر بايثون](https://automatetheboringstuff.com) -* [أفكار لمشروعات بلغة البايثون](http://pythonpracticeprojects.com) -* [التوثيقات الرسمية](http://docs.python.org/3/) -* [دليل المُسافر لبايثون](http://docs.python-guide.org/en/latest/) -* [دورة بايثون](http://www.python-course.eu/index.php) -* [أولى الخطوات مع بايثون](https://realpython.com/learn/python-first-steps/) -* [قائمة مُختارة من إطارات عمل بايثون الرائعة, المكتبات والبرمجيات](https://github.com/vinta/awesome-python) -* [ثلاثون خاصية وخدعة للغة البايثون ربما لم تعرف بها](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) -* [الدليل الرسمي لنمط البايثون](https://www.python.org/dev/peps/pep-0008/) -* [بايثون 3 دوائر علوم الحاسب](http://cscircles.cemc.uwaterloo.ca/) -* [غُص في بايثون 3](http://www.diveintopython3.net/index.html) -* [دورة سريعة في البايثون للعلماء](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/cs-cz/python.html.markdown b/cs-cz/python.html.markdown new file mode 100644 index 00000000..bd3690a8 --- /dev/null +++ b/cs-cz/python.html.markdown @@ -0,0 +1,647 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Tomáš Bedřich", "http://tbedrich.cz"] +translators: + - ["Tomáš Bedřich", "http://tbedrich.cz"] +filename: learnpython3-cz.py +lang: cs-cz +--- + +Python byl vytvořen Guidem Van Rossum v raných 90. letech. Nyní je jedním z nejpopulárnějších jazyků. +Zamiloval jsem si Python pro jeho syntaktickou čistotu - je to vlastně spustitelný pseudokód. + +Vaše zpětná vazba je vítána! Můžete mě zastihnout na [@louiedinh](http://twitter.com/louiedinh) nebo louiedinh [at] [email od googlu] anglicky, +autora českého překladu pak na [@tbedrich](http://twitter.com/tbedrich) nebo ja [at] tbedrich.cz + +Poznámka: Tento článek je zaměřen na Python 3. Zde se můžete [naučit starší Python 2.7](http://learnxinyminutes.com/docs/python/). + +```python + +# Jednořádkový komentář začíná křížkem + +""" Víceřádkové komentáře používají tři uvozovky nebo apostrofy + a jsou často využívány jako dokumentační komentáře k metodám +""" + +#################################################### +## 1. Primitivní datové typy a operátory +#################################################### + +# Čísla +3 # => 3 + +# Aritmetické operace se chovají běžným způsobem +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Až na dělení, které vrací desetinné číslo +35 / 5 # => 7.0 + +# Při celočíselném dělení je desetinná část oříznuta (pro kladná i záporná čísla) +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # celočíselně dělit lze i desetinným číslem +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Pokud použijete desetinné číslo, výsledek je jím také +3 * 2.0 # => 6.0 + +# Modulo +7 % 3 # => 1 + +# Mocnění (x na y-tou) +2**4 # => 16 + +# Pro vynucení priority použijte závorky +(1 + 3) * 2 # => 8 + +# Logické hodnoty +True +False + +# Negace se provádí pomocí not +not True # => False +not False # => True + +# Logické operátory +# U operátorů záleží na velikosti písmen +True and False # => False +False or True # => True + +# Používání logických operátorů s čísly +0 and 2 # => 0 +-5 or 0 # => -5 + +# Při porovnání s boolean hodnotou nepoužívejte operátor rovnosti "==". +# Stejně jako u hodnoty None. +# Viz PEP8: https://www.python.org/dev/peps/pep-0008/ +0 is False # => True +2 is True # => False +1 is True # => True + +# Rovnost je == +1 == 1 # => True +2 == 1 # => False + +# Nerovnost je != +1 != 1 # => False +2 != 1 # => True + +# Další porovnání +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Porovnání se dají řetězit! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + + +# Řetězce používají " nebo ' a mohou obsahovat unicode znaky +"Toto je řetězec." +'Toto je také řetězec.' + +# Řetězce se také dají slučovat +"Hello " + "world!" # => "Hello world!" +# Dají se spojovat i bez '+' +"Hello " "world!" # => "Hello world!" + +# Řetězec lze považovat za seznam znaků +"Toto je řetězec"[0] # => 'T' + +# .format lze použít ke skládání řetězců +"{} mohou být {}".format("řetězce", "skládány") + +# Formátovací argumenty můžete opakovat +"{0} {1} stříkaček stříkalo přes {0} {1} střech".format("tři sta třicet tři", "stříbrných") +# => "tři sta třicet tři stříbrných stříkaček stříkalo přes tři sta třicet tři stříbrných střech" + +# Pokud nechcete počítat, můžete použít pojmenované argumenty +"{jmeno} si dal {jidlo}".format(jmeno="Franta", jidlo="guláš") # => "Franta si dal guláš" + +# Pokud zároveň potřebujete podporovat Python 2.5 a nižší, můžete použít starší způsob formátování +"%s se dají %s jako v %s" % ("řetězce", "skládat", "jazyce C") + + +# None je objekt (jinde NULL, nil, ...) +None # => None + +# Pokud porovnáváte něco s None, nepoužívejte operátor rovnosti "==", +# použijte raději operátor "is", který testuje identitu. +"něco" is None # => False +None is None # => True + +# None, 0, a prázdný řetězec/seznam/N-tice/slovník/množina se vyhodnotí jako False +# Vše ostatní se vyhodnotí jako True +bool(0) # => False +bool("") # => False +bool([]) # => False +bool(tuple()) # => False +bool({}) # => False +bool(set()) # => False + + +#################################################### +## 2. Proměnné a kolekce +#################################################### + +# Python má funkci print +print("Jsem 3. Python 3.") + +# Proměnné není třeba deklarovat před přiřazením +# Konvence je používat male_pismo_s_podtrzitky +nazev_promenne = 5 +nazev_promenne # => 5 +# Názvy proměnných mohou obsahovat i unicode znaky, ale nedělejte to. +# Viz PEP 3131 -- Supporting Non-ASCII Identifiers: +# https://www.python.org/dev/peps/pep-3131/ +název_proměnné = 5 + +# Přístup k předtím nedefinované proměnné vyvolá výjimku +# Odchytávání vyjímek - viz další kapitola +neznama_promenna # Vyhodí NameError + +# Seznam se používá pro ukládání sekvencí +sez = [] +# Lze ho rovnou naplnit +jiny_seznam = [4, 5, 6] + +# Na konec seznamu se přidává pomocí append +sez.append(1) # sez je nyní [1] +sez.append(2) # sez je nyní [1, 2] +sez.append(4) # sez je nyní [1, 2, 4] +sez.append(3) # sez je nyní [1, 2, 4, 3] +# Z konce se odebírá se pomocí pop +sez.pop() # => 3 a sez je nyní [1, 2, 4] +# Vložme trojku zpátky +sez.append(3) # sez je nyní znovu [1, 2, 4, 3] + +# Přístup k prvkům funguje jako v poli +sez[0] # => 1 +# Mínus počítá odzadu (-1 je poslední prvek) +sez[-1] # => 3 + +# Přístup mimo seznam vyhodí IndexError +sez[4] # Vyhodí IndexError + +# Pomocí řezů lze ze seznamu vybírat různé intervaly +# (pro matematiky: jedná se o uzavřený/otevřený interval) +sez[1:3] # => [2, 4] +# Odříznutí začátku +sez[2:] # => [4, 3] +# Odříznutí konce +sez[:3] # => [1, 2, 4] +# Vybrání každého druhého prvku +sez[::2] # =>[1, 4] +# Vrácení seznamu v opačném pořadí +sez[::-1] # => [3, 4, 2, 1] +# Lze použít jakoukoliv kombinaci parametrů pro vytvoření složitějšího řezu +# sez[zacatek:konec:krok] + +# Odebírat prvky ze seznamu lze pomocí del +del sez[2] # sez je nyní [1, 2, 3] + +# Seznamy můžete slučovat +# Hodnoty sez a jiny_seznam přitom nejsou změněny +sez + jiny_seznam # => [1, 2, 3, 4, 5, 6] + +# Spojit seznamy lze pomocí extend +sez.extend(jiny_seznam) # sez je nyní [1, 2, 3, 4, 5, 6] + +# Kontrola, jestli prvek v seznamu existuje, se provádí pomocí in +1 in sez # => True + +# Délku seznamu lze zjistit pomocí len +len(sez) # => 6 + + +# N-tice je jako seznam, ale je neměnná +ntice = (1, 2, 3) +ntice[0] # => 1 +ntice[0] = 3 # Vyhodí TypeError + +# S n-ticemi lze dělat většinu operací, jako se seznamy +len(ntice) # => 3 +ntice + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +ntice[:2] # => (1, 2) +2 in ntice # => True + +# N-tice (nebo seznamy) lze rozbalit do proměnných jedním přiřazením +a, b, c = (1, 2, 3) # a je nyní 1, b je nyní 2 a c je nyní 3 +# N-tice jsou vytvářeny automaticky, když vynecháte závorky +d, e, f = 4, 5, 6 +# Prohození proměnných je tak velmi snadné +e, d = d, e # d je nyní 5, e je nyní 4 + + +# Slovníky ukládají klíče a hodnoty +prazdny_slovnik = {} +# Lze je také rovnou naplnit +slovnik = {"jedna": 1, "dva": 2, "tři": 3} + +# Přistupovat k hodnotám lze pomocí [] +slovnik["jedna"] # => 1 + +# Všechny klíče dostaneme pomocí keys() jako iterovatelný objekt. Nyní ještě +# potřebujeme obalit volání v list(), abychom dostali seznam. To rozebereme +# později. Pozor, že jakékoliv pořadí klíčů není garantováno - může být různé. +list(slovnik.keys()) # => ["dva", "jedna", "tři"] + +# Všechny hodnoty opět jako iterovatelný objekt získáme pomocí values(). Opět +# tedy potřebujeme použít list(), abychom dostali seznam. Stejně jako +# v předchozím případě, pořadí není garantováno a může být různé +list(slovnik.values()) # => [3, 2, 1] + +# Operátorem in se lze dotázat na přítomnost klíče +"jedna" in slovnik # => True +1 in slovnik # => False + +# Přístup k neexistujícímu klíči vyhodí KeyError +slovnik["čtyři"] # Vyhodí KeyError + +# Metoda get() funguje podobně jako [], ale vrátí None místo vyhození KeyError +slovnik.get("jedna") # => 1 +slovnik.get("čtyři") # => None +# Metodě get() lze předat i výchozí hodnotu místo None +slovnik.get("jedna", 4) # => 1 +slovnik.get("čtyři", 4) # => 4 + +# metoda setdefault() vloží prvek do slovníku pouze pokud tam takový klíč není +slovnik.setdefault("pět", 5) # slovnik["pět"] je nastaven na 5 +slovnik.setdefault("pět", 6) # slovnik["pět"] je pořád 5 + +# Přidání nové hodnoty do slovníku +slovnik["čtyři"] = 4 +# Hromadně aktualizovat nebo přidat data lze pomocí update(), parametrem je opět slovník +slovnik.update({"čtyři": 4}) # slovnik je nyní {"jedna": 1, "dva": 2, "tři": 3, "čtyři": 4, "pět": 5} + +# Odebírat ze slovníku dle klíče lze pomocí del +del slovnik["jedna"] # odebere klíč "jedna" ze slovnik + + +# Množiny ukládají ... překvapivě množiny +prazdna_mnozina = set() +# Také je lze rovnou naplnit. A ano, budou se vám plést se slovníky. Bohužel. +mnozina = {1, 1, 2, 2, 3, 4} # mnozina je nyní {1, 2, 3, 4} + +# Přidání položky do množiny +mnozina.add(5) # mnozina je nyní {1, 2, 3, 4, 5} + +# Průnik lze udělat pomocí operátoru & +jina_mnozina = {3, 4, 5, 6} +mnozina & jina_mnozina # => {3, 4, 5} + +# Sjednocení pomocí operátoru | +mnozina | jina_mnozina # => {1, 2, 3, 4, 5, 6} + +# Rozdíl pomocí operátoru - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Operátorem in se lze dotázat na přítomnost prvku v množině +2 in mnozina # => True +9 in mnozina # => False + + +#################################################### +## 3. Řízení toku programu, cykly +#################################################### + +# Vytvořme si proměnnou +promenna = 5 + +# Takto vypadá podmínka. Na odsazení v Pythonu záleží! +# Vypíše "proměnná je menší než 10". +if promenna > 10: + print("proměnná je velká jak Rusko") +elif promenna < 10: # Část elif je nepovinná + print("proměnná je menší než 10") +else: # Část else je také nepovinná + print("proměnná je právě 10") + + +""" +Smyčka for umí iterovat (nejen) přes seznamy +vypíše: + pes je savec + kočka je savec + myš je savec +""" +for zvire in ["pes", "kočka", "myš"]: + # Můžete použít formát pro složení řetězce + print("{} je savec".format(zvire)) + +""" +range(cislo) vrací iterovatelný objekt čísel od 0 do cislo +vypíše: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +range(spodni_limit, horni_limit) vrací iterovatelný objekt čísel mezi limity +vypíše: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +Smyčka while se opakuje, dokud je podmínka splněna. +vypíše: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Zkrácený zápis x = x + 1. Pozor, žádné x++ neexisuje. + + +# Výjimky lze ošetřit pomocí bloku try/except(/else/finally) +try: + # Pro vyhození výjimky použijte raise + raise IndexError("Přistoupil jste k neexistujícímu prvku v seznamu.") +except IndexError as e: + print("Nastala chyba: {}".format(e)) + # Vypíše: Nastala chyba: Přistoupil jste k neexistujícímu prvku v seznamu. +except (TypeError, NameError): # Více výjimek lze zachytit najednou + pass # Pass znamená nedělej nic - nepříliš vhodný způsob ošetření chyb +else: # Volitelný blok else musí být až za bloky except + print("OK!") # Vypíše OK! v případě, že nenastala žádná výjimka +finally: # Blok finally se spustí nakonec za všech okolností + print("Uvolníme zdroje, uzavřeme soubory...") + +# Místo try/finally lze použít with pro automatické uvolnění zdrojů +with open("soubor.txt") as soubor: + for radka in soubor: + print(radka) + +# Python běžně používá iterovatelné objekty, což je prakticky cokoliv, +# co lze považovat za sekvenci. Například to, co vrací metoda range(), +# nebo otevřený soubor, jsou iterovatelné objekty. + +slovnik = {"jedna": 1, "dva": 2, "tři": 3} +iterovatelny_objekt = slovnik.keys() +print(iterovatelny_objekt) # => dict_keys(["jedna", "dva", "tři"]). Toto je iterovatelný objekt. + +# Můžeme použít cyklus for na jeho projití +for klic in iterovatelny_objekt: + print(klic) # vypíše postupně: jedna, dva, tři + +# Ale nelze přistupovat k prvkům pod jejich indexem +iterovatelny_objekt[1] # Vyhodí TypeError + +# Všechny položky iterovatelného objektu lze získat jako seznam pomocí list() +list(slovnik.keys()) # => ["jedna", "dva", "tři"] + +# Z iterovatelného objektu lze vytvořit iterátor +iterator = iter(iterovatelny_objekt) + +# Iterátor je objekt, který si pamatuje stav v rámci svého iterovatelného objektu +# Další hodnotu dostaneme voláním next() +next(iterator) # => "jedna" + +# Iterátor si udržuje svůj stav v mezi jednotlivými voláními next() +next(iterator) # => "dva" +next(iterator) # => "tři" + +# Jakmile interátor vrátí všechna svá data, vyhodí výjimku StopIteration +next(iterator) # Vyhodí StopIteration + + +#################################################### +## 4. Funkce +#################################################### + +# Pro vytvoření nové funkce použijte klíčové slovo def +def secist(x, y): + print("x je {} a y je {}".format(x, y)) + return x + y # Hodnoty se vrací pomocí return + +# Volání funkce s parametry +secist(5, 6) # => Vypíše "x je 5 a y je 6" a vrátí 11 + +# Jiný způsob, jak volat funkci, je použít pojmenované argumenty +secist(y=6, x=5) # Pojmenované argumenty můžete předat v libovolném pořadí + +# Lze definovat funkce s proměnným počtem (pozičních) argumentů +def vrat_argumenty(*argumenty): + return argumenty + +vrat_argumenty(1, 2, 3) # => (1, 2, 3) + +# Lze definovat také funkce s proměnným počtem pojmenovaných argumentů +def vrat_pojmenovane_argumenty(**pojmenovane_argumenty): + return pojmenovane_argumenty + +vrat_pojmenovane_argumenty(kdo="se bojí", nesmi="do lesa") +# => {"kdo": "se bojí", "nesmi": "do lesa"} + + +# Pokud chcete, lze použít obojí najednou +# Konvence je používat pro tyto účely názvy *args a **kwargs +def vypis_vse(*args, **kwargs): + print(args, kwargs) # print() vypíše všechny své parametry oddělené mezerou + +vypis_vse(1, 2, a=3, b=4) # Vypíše: (1, 2) {"a": 3, "b": 4} + +# * nebo ** lze použít k rozbalení N-tic nebo slovníků! +ntice = (1, 2, 3, 4) +slovnik = {"a": 3, "b": 4} +vypis_vse(ntice) # Vyhodnotí se jako vypis_vse((1, 2, 3, 4)) – jeden parametr, N-tice +vypis_vse(*ntice) # Vyhodnotí se jako vypis_vse(1, 2, 3, 4) +vypis_vse(**slovnik) # Vyhodnotí se jako vypis_vse(a=3, b=4) +vypis_vse(*ntice, **slovnik) # Vyhodnotí se jako vypis_vse(1, 2, 3, 4, a=3, b=4) + + +# Viditelnost proměnných - vytvořme si globální proměnnou x +x = 5 + +def nastavX(cislo): + # Lokální proměnná x překryje globální x + x = cislo # => 43 + print(x) # => 43 + +def nastavGlobalniX(cislo): + global x + print(x) # => 5 + x = cislo # Nastaví globální proměnnou x na 6 + print(x) # => 6 + +nastavX(43) +nastavGlobalniX(6) + + +# Funkce jsou first-class objekty +def vyrobit_scitacku(pricitane_cislo): + def scitacka(x): + return x + pricitane_cislo + return scitacka + +pricist_10 = vyrobit_scitacku(10) +pricist_10(3) # => 13 + +# Klíčové slovo lambda vytvoří anonymní funkci +(lambda parametr: parametr > 2)(3) # => True + +# Lze použít funkce map() a filter() z funkcionálního programování +map(pricist_10, [1, 2, 3]) +# => - iterovatelný objekt s obsahem: [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) +# => - iterovatelný objekt s obsahem: [6, 7] + +# S generátorovou notací lze dosáhnout podobných výsledků, ale vrací seznam +[pricist_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] +# Generátorová notace funguje i pro slovníky +{x: x**2 for x in range(1, 5)} # => {1: 1, 2: 4, 3: 9, 4: 16} +# A také pro množiny +{pismeno for pismeno in "abeceda"} # => {"d", "a", "c", "e", "b"} + + +#################################################### +## 5. Třídy +#################################################### + +# Třída Clovek je potomkem (dědí od) třídy object +class Clovek(object): + + # Atribut třídy - je sdílený všemi instancemi + druh = "H. sapiens" + + # Toto je kostruktor. Je volán, když vytváříme instanci třídy. Dvě + # podtržítka na začátku a na konci značí, že se jedná o atribut nebo + # objekt využívaný Pythonem ke speciálním účelům, ale můžete sami + # definovat jeho chování. Metody jako __init__, __str__, __repr__ + # a další se nazývají "magické metody". Nikdy nepoužívejte toto + # speciální pojmenování pro běžné metody. + def __init__(self, jmeno): + # Přiřazení parametru do atributu instance jmeno + self.jmeno = jmeno + + # Metoda instance - všechny metody instance mají "self" jako první parametr + def rekni(self, hlaska): + return "{jmeno}: {hlaska}".format(jmeno=self.jmeno, hlaska=hlaska) + + # Metoda třídy - sdílená všemi instancemi + # Dostává jako první parametr třídu, na které je volána + @classmethod + def vrat_druh(cls): + return cls.druh + + # Statická metoda je volána bez reference na třídu nebo instanci + @staticmethod + def odkaslej_si(): + return "*ehm*" + + +# Vytvoření instance +d = Clovek(jmeno="David") +a = Clovek("Adéla") +print(d.rekni("ahoj")) # Vypíše: "David: ahoj" +print(a.rekni("nazdar")) # Vypíše: "Adéla: nazdar" + +# Volání třídní metody +d.vrat_druh() # => "H. sapiens" + +# Změna atributu třídy +Clovek.druh = "H. neanderthalensis" +d.vrat_druh() # => "H. neanderthalensis" +a.vrat_druh() # => "H. neanderthalensis" + +# Volání statické metody +Clovek.odkaslej_si() # => "*ehm*" + + +#################################################### +## 6. Moduly +#################################################### + +# Lze importovat moduly +import math +print(math.sqrt(16.0)) # => 4.0 + +# Lze také importovat pouze vybrané funkce z modulu +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Můžete také importovat všechny funkce z modulu, ale radši to nedělejte +from math import * + +# Můžete si přejmenovat modul při jeho importu +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Modul v Pythonu není nic jiného, než obyčejný soubor .py +# Můžete si napsat vlastní a prostě ho importovat podle jména +from muj_modul import moje_funkce # Nyní vyhodí ImportError - muj_modul neexistuje + +# Funkcí dir() lze zjistit, co modul obsahuje +import math +dir(math) + + +#################################################### +## 7. Pokročilé +#################################################### + +# Generátory jsou funkce, které místo return obsahují yield +def nasobicka_2(sekvence): + for i in sekvence: + print("Zpracovávám číslo {}".format(i)) + yield 2 * i + +# Generátor generuje hodnoty postupně, jak jsou potřeba. Místo toho, aby vrátil +# celou sekvenci s prvky vynásobenými dvěma, provádí jeden výpočet v každé iteraci. +for nasobek in nasobicka_2([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]): + # Vypíše postupně: "Zpracovávám číslo 1", ..., "Zpracovávám číslo 5" + if nasobek >= 10: + break + +# Funkce range() je také generátor - vytváření seznamu 900000000 prvků by zabralo +# hodně času i paměti, proto se místo toho čísla generují postupně. +for nasobek in nasobicka_2(range(900000000)): + # Vypíše postupně: "Zpracovávám číslo 1", ..., "Zpracovávám číslo 5" + if nasobek >= 10: + break + + +# Dekorátory jsou funkce, které se používají pro obalení jiné funkce, čímž mohou +# přidávat nebo měnit její stávající chování. Funkci dostávají jako parametr +# a typicky místo ní vrací jinou, která uvnitř volá tu původní. + +def nekolikrat(puvodni_funkce): + def opakovaci_funkce(*args, **kwargs): + for i in range(3): + puvodni_funkce(*args, **kwargs) + + return opakovaci_funkce + + +@nekolikrat +def pozdrav(jmeno): + print("Měj se {}!".format(jmeno)) + +pozdrav("Pepo") # Vypíše 3x: "Měj se Pepo!" +``` + +## Co dál? + +Spoustu odkazů na české i anglické materiály najdete na [webu české Python komunity] +(http://python.cz/). Můžete také přijít na Pyvo, kde to společně probereme. diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown deleted file mode 100644 index bd3690a8..00000000 --- a/cs-cz/python3.html.markdown +++ /dev/null @@ -1,647 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Tomáš Bedřich", "http://tbedrich.cz"] -translators: - - ["Tomáš Bedřich", "http://tbedrich.cz"] -filename: learnpython3-cz.py -lang: cs-cz ---- - -Python byl vytvořen Guidem Van Rossum v raných 90. letech. Nyní je jedním z nejpopulárnějších jazyků. -Zamiloval jsem si Python pro jeho syntaktickou čistotu - je to vlastně spustitelný pseudokód. - -Vaše zpětná vazba je vítána! Můžete mě zastihnout na [@louiedinh](http://twitter.com/louiedinh) nebo louiedinh [at] [email od googlu] anglicky, -autora českého překladu pak na [@tbedrich](http://twitter.com/tbedrich) nebo ja [at] tbedrich.cz - -Poznámka: Tento článek je zaměřen na Python 3. Zde se můžete [naučit starší Python 2.7](http://learnxinyminutes.com/docs/python/). - -```python - -# Jednořádkový komentář začíná křížkem - -""" Víceřádkové komentáře používají tři uvozovky nebo apostrofy - a jsou často využívány jako dokumentační komentáře k metodám -""" - -#################################################### -## 1. Primitivní datové typy a operátory -#################################################### - -# Čísla -3 # => 3 - -# Aritmetické operace se chovají běžným způsobem -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 - -# Až na dělení, které vrací desetinné číslo -35 / 5 # => 7.0 - -# Při celočíselném dělení je desetinná část oříznuta (pro kladná i záporná čísla) -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # celočíselně dělit lze i desetinným číslem --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Pokud použijete desetinné číslo, výsledek je jím také -3 * 2.0 # => 6.0 - -# Modulo -7 % 3 # => 1 - -# Mocnění (x na y-tou) -2**4 # => 16 - -# Pro vynucení priority použijte závorky -(1 + 3) * 2 # => 8 - -# Logické hodnoty -True -False - -# Negace se provádí pomocí not -not True # => False -not False # => True - -# Logické operátory -# U operátorů záleží na velikosti písmen -True and False # => False -False or True # => True - -# Používání logických operátorů s čísly -0 and 2 # => 0 --5 or 0 # => -5 - -# Při porovnání s boolean hodnotou nepoužívejte operátor rovnosti "==". -# Stejně jako u hodnoty None. -# Viz PEP8: https://www.python.org/dev/peps/pep-0008/ -0 is False # => True -2 is True # => False -1 is True # => True - -# Rovnost je == -1 == 1 # => True -2 == 1 # => False - -# Nerovnost je != -1 != 1 # => False -2 != 1 # => True - -# Další porovnání -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# Porovnání se dají řetězit! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - - -# Řetězce používají " nebo ' a mohou obsahovat unicode znaky -"Toto je řetězec." -'Toto je také řetězec.' - -# Řetězce se také dají slučovat -"Hello " + "world!" # => "Hello world!" -# Dají se spojovat i bez '+' -"Hello " "world!" # => "Hello world!" - -# Řetězec lze považovat za seznam znaků -"Toto je řetězec"[0] # => 'T' - -# .format lze použít ke skládání řetězců -"{} mohou být {}".format("řetězce", "skládány") - -# Formátovací argumenty můžete opakovat -"{0} {1} stříkaček stříkalo přes {0} {1} střech".format("tři sta třicet tři", "stříbrných") -# => "tři sta třicet tři stříbrných stříkaček stříkalo přes tři sta třicet tři stříbrných střech" - -# Pokud nechcete počítat, můžete použít pojmenované argumenty -"{jmeno} si dal {jidlo}".format(jmeno="Franta", jidlo="guláš") # => "Franta si dal guláš" - -# Pokud zároveň potřebujete podporovat Python 2.5 a nižší, můžete použít starší způsob formátování -"%s se dají %s jako v %s" % ("řetězce", "skládat", "jazyce C") - - -# None je objekt (jinde NULL, nil, ...) -None # => None - -# Pokud porovnáváte něco s None, nepoužívejte operátor rovnosti "==", -# použijte raději operátor "is", který testuje identitu. -"něco" is None # => False -None is None # => True - -# None, 0, a prázdný řetězec/seznam/N-tice/slovník/množina se vyhodnotí jako False -# Vše ostatní se vyhodnotí jako True -bool(0) # => False -bool("") # => False -bool([]) # => False -bool(tuple()) # => False -bool({}) # => False -bool(set()) # => False - - -#################################################### -## 2. Proměnné a kolekce -#################################################### - -# Python má funkci print -print("Jsem 3. Python 3.") - -# Proměnné není třeba deklarovat před přiřazením -# Konvence je používat male_pismo_s_podtrzitky -nazev_promenne = 5 -nazev_promenne # => 5 -# Názvy proměnných mohou obsahovat i unicode znaky, ale nedělejte to. -# Viz PEP 3131 -- Supporting Non-ASCII Identifiers: -# https://www.python.org/dev/peps/pep-3131/ -název_proměnné = 5 - -# Přístup k předtím nedefinované proměnné vyvolá výjimku -# Odchytávání vyjímek - viz další kapitola -neznama_promenna # Vyhodí NameError - -# Seznam se používá pro ukládání sekvencí -sez = [] -# Lze ho rovnou naplnit -jiny_seznam = [4, 5, 6] - -# Na konec seznamu se přidává pomocí append -sez.append(1) # sez je nyní [1] -sez.append(2) # sez je nyní [1, 2] -sez.append(4) # sez je nyní [1, 2, 4] -sez.append(3) # sez je nyní [1, 2, 4, 3] -# Z konce se odebírá se pomocí pop -sez.pop() # => 3 a sez je nyní [1, 2, 4] -# Vložme trojku zpátky -sez.append(3) # sez je nyní znovu [1, 2, 4, 3] - -# Přístup k prvkům funguje jako v poli -sez[0] # => 1 -# Mínus počítá odzadu (-1 je poslední prvek) -sez[-1] # => 3 - -# Přístup mimo seznam vyhodí IndexError -sez[4] # Vyhodí IndexError - -# Pomocí řezů lze ze seznamu vybírat různé intervaly -# (pro matematiky: jedná se o uzavřený/otevřený interval) -sez[1:3] # => [2, 4] -# Odříznutí začátku -sez[2:] # => [4, 3] -# Odříznutí konce -sez[:3] # => [1, 2, 4] -# Vybrání každého druhého prvku -sez[::2] # =>[1, 4] -# Vrácení seznamu v opačném pořadí -sez[::-1] # => [3, 4, 2, 1] -# Lze použít jakoukoliv kombinaci parametrů pro vytvoření složitějšího řezu -# sez[zacatek:konec:krok] - -# Odebírat prvky ze seznamu lze pomocí del -del sez[2] # sez je nyní [1, 2, 3] - -# Seznamy můžete slučovat -# Hodnoty sez a jiny_seznam přitom nejsou změněny -sez + jiny_seznam # => [1, 2, 3, 4, 5, 6] - -# Spojit seznamy lze pomocí extend -sez.extend(jiny_seznam) # sez je nyní [1, 2, 3, 4, 5, 6] - -# Kontrola, jestli prvek v seznamu existuje, se provádí pomocí in -1 in sez # => True - -# Délku seznamu lze zjistit pomocí len -len(sez) # => 6 - - -# N-tice je jako seznam, ale je neměnná -ntice = (1, 2, 3) -ntice[0] # => 1 -ntice[0] = 3 # Vyhodí TypeError - -# S n-ticemi lze dělat většinu operací, jako se seznamy -len(ntice) # => 3 -ntice + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -ntice[:2] # => (1, 2) -2 in ntice # => True - -# N-tice (nebo seznamy) lze rozbalit do proměnných jedním přiřazením -a, b, c = (1, 2, 3) # a je nyní 1, b je nyní 2 a c je nyní 3 -# N-tice jsou vytvářeny automaticky, když vynecháte závorky -d, e, f = 4, 5, 6 -# Prohození proměnných je tak velmi snadné -e, d = d, e # d je nyní 5, e je nyní 4 - - -# Slovníky ukládají klíče a hodnoty -prazdny_slovnik = {} -# Lze je také rovnou naplnit -slovnik = {"jedna": 1, "dva": 2, "tři": 3} - -# Přistupovat k hodnotám lze pomocí [] -slovnik["jedna"] # => 1 - -# Všechny klíče dostaneme pomocí keys() jako iterovatelný objekt. Nyní ještě -# potřebujeme obalit volání v list(), abychom dostali seznam. To rozebereme -# později. Pozor, že jakékoliv pořadí klíčů není garantováno - může být různé. -list(slovnik.keys()) # => ["dva", "jedna", "tři"] - -# Všechny hodnoty opět jako iterovatelný objekt získáme pomocí values(). Opět -# tedy potřebujeme použít list(), abychom dostali seznam. Stejně jako -# v předchozím případě, pořadí není garantováno a může být různé -list(slovnik.values()) # => [3, 2, 1] - -# Operátorem in se lze dotázat na přítomnost klíče -"jedna" in slovnik # => True -1 in slovnik # => False - -# Přístup k neexistujícímu klíči vyhodí KeyError -slovnik["čtyři"] # Vyhodí KeyError - -# Metoda get() funguje podobně jako [], ale vrátí None místo vyhození KeyError -slovnik.get("jedna") # => 1 -slovnik.get("čtyři") # => None -# Metodě get() lze předat i výchozí hodnotu místo None -slovnik.get("jedna", 4) # => 1 -slovnik.get("čtyři", 4) # => 4 - -# metoda setdefault() vloží prvek do slovníku pouze pokud tam takový klíč není -slovnik.setdefault("pět", 5) # slovnik["pět"] je nastaven na 5 -slovnik.setdefault("pět", 6) # slovnik["pět"] je pořád 5 - -# Přidání nové hodnoty do slovníku -slovnik["čtyři"] = 4 -# Hromadně aktualizovat nebo přidat data lze pomocí update(), parametrem je opět slovník -slovnik.update({"čtyři": 4}) # slovnik je nyní {"jedna": 1, "dva": 2, "tři": 3, "čtyři": 4, "pět": 5} - -# Odebírat ze slovníku dle klíče lze pomocí del -del slovnik["jedna"] # odebere klíč "jedna" ze slovnik - - -# Množiny ukládají ... překvapivě množiny -prazdna_mnozina = set() -# Také je lze rovnou naplnit. A ano, budou se vám plést se slovníky. Bohužel. -mnozina = {1, 1, 2, 2, 3, 4} # mnozina je nyní {1, 2, 3, 4} - -# Přidání položky do množiny -mnozina.add(5) # mnozina je nyní {1, 2, 3, 4, 5} - -# Průnik lze udělat pomocí operátoru & -jina_mnozina = {3, 4, 5, 6} -mnozina & jina_mnozina # => {3, 4, 5} - -# Sjednocení pomocí operátoru | -mnozina | jina_mnozina # => {1, 2, 3, 4, 5, 6} - -# Rozdíl pomocí operátoru - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Operátorem in se lze dotázat na přítomnost prvku v množině -2 in mnozina # => True -9 in mnozina # => False - - -#################################################### -## 3. Řízení toku programu, cykly -#################################################### - -# Vytvořme si proměnnou -promenna = 5 - -# Takto vypadá podmínka. Na odsazení v Pythonu záleží! -# Vypíše "proměnná je menší než 10". -if promenna > 10: - print("proměnná je velká jak Rusko") -elif promenna < 10: # Část elif je nepovinná - print("proměnná je menší než 10") -else: # Část else je také nepovinná - print("proměnná je právě 10") - - -""" -Smyčka for umí iterovat (nejen) přes seznamy -vypíše: - pes je savec - kočka je savec - myš je savec -""" -for zvire in ["pes", "kočka", "myš"]: - # Můžete použít formát pro složení řetězce - print("{} je savec".format(zvire)) - -""" -range(cislo) vrací iterovatelný objekt čísel od 0 do cislo -vypíše: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -range(spodni_limit, horni_limit) vrací iterovatelný objekt čísel mezi limity -vypíše: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -Smyčka while se opakuje, dokud je podmínka splněna. -vypíše: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Zkrácený zápis x = x + 1. Pozor, žádné x++ neexisuje. - - -# Výjimky lze ošetřit pomocí bloku try/except(/else/finally) -try: - # Pro vyhození výjimky použijte raise - raise IndexError("Přistoupil jste k neexistujícímu prvku v seznamu.") -except IndexError as e: - print("Nastala chyba: {}".format(e)) - # Vypíše: Nastala chyba: Přistoupil jste k neexistujícímu prvku v seznamu. -except (TypeError, NameError): # Více výjimek lze zachytit najednou - pass # Pass znamená nedělej nic - nepříliš vhodný způsob ošetření chyb -else: # Volitelný blok else musí být až za bloky except - print("OK!") # Vypíše OK! v případě, že nenastala žádná výjimka -finally: # Blok finally se spustí nakonec za všech okolností - print("Uvolníme zdroje, uzavřeme soubory...") - -# Místo try/finally lze použít with pro automatické uvolnění zdrojů -with open("soubor.txt") as soubor: - for radka in soubor: - print(radka) - -# Python běžně používá iterovatelné objekty, což je prakticky cokoliv, -# co lze považovat za sekvenci. Například to, co vrací metoda range(), -# nebo otevřený soubor, jsou iterovatelné objekty. - -slovnik = {"jedna": 1, "dva": 2, "tři": 3} -iterovatelny_objekt = slovnik.keys() -print(iterovatelny_objekt) # => dict_keys(["jedna", "dva", "tři"]). Toto je iterovatelný objekt. - -# Můžeme použít cyklus for na jeho projití -for klic in iterovatelny_objekt: - print(klic) # vypíše postupně: jedna, dva, tři - -# Ale nelze přistupovat k prvkům pod jejich indexem -iterovatelny_objekt[1] # Vyhodí TypeError - -# Všechny položky iterovatelného objektu lze získat jako seznam pomocí list() -list(slovnik.keys()) # => ["jedna", "dva", "tři"] - -# Z iterovatelného objektu lze vytvořit iterátor -iterator = iter(iterovatelny_objekt) - -# Iterátor je objekt, který si pamatuje stav v rámci svého iterovatelného objektu -# Další hodnotu dostaneme voláním next() -next(iterator) # => "jedna" - -# Iterátor si udržuje svůj stav v mezi jednotlivými voláními next() -next(iterator) # => "dva" -next(iterator) # => "tři" - -# Jakmile interátor vrátí všechna svá data, vyhodí výjimku StopIteration -next(iterator) # Vyhodí StopIteration - - -#################################################### -## 4. Funkce -#################################################### - -# Pro vytvoření nové funkce použijte klíčové slovo def -def secist(x, y): - print("x je {} a y je {}".format(x, y)) - return x + y # Hodnoty se vrací pomocí return - -# Volání funkce s parametry -secist(5, 6) # => Vypíše "x je 5 a y je 6" a vrátí 11 - -# Jiný způsob, jak volat funkci, je použít pojmenované argumenty -secist(y=6, x=5) # Pojmenované argumenty můžete předat v libovolném pořadí - -# Lze definovat funkce s proměnným počtem (pozičních) argumentů -def vrat_argumenty(*argumenty): - return argumenty - -vrat_argumenty(1, 2, 3) # => (1, 2, 3) - -# Lze definovat také funkce s proměnným počtem pojmenovaných argumentů -def vrat_pojmenovane_argumenty(**pojmenovane_argumenty): - return pojmenovane_argumenty - -vrat_pojmenovane_argumenty(kdo="se bojí", nesmi="do lesa") -# => {"kdo": "se bojí", "nesmi": "do lesa"} - - -# Pokud chcete, lze použít obojí najednou -# Konvence je používat pro tyto účely názvy *args a **kwargs -def vypis_vse(*args, **kwargs): - print(args, kwargs) # print() vypíše všechny své parametry oddělené mezerou - -vypis_vse(1, 2, a=3, b=4) # Vypíše: (1, 2) {"a": 3, "b": 4} - -# * nebo ** lze použít k rozbalení N-tic nebo slovníků! -ntice = (1, 2, 3, 4) -slovnik = {"a": 3, "b": 4} -vypis_vse(ntice) # Vyhodnotí se jako vypis_vse((1, 2, 3, 4)) – jeden parametr, N-tice -vypis_vse(*ntice) # Vyhodnotí se jako vypis_vse(1, 2, 3, 4) -vypis_vse(**slovnik) # Vyhodnotí se jako vypis_vse(a=3, b=4) -vypis_vse(*ntice, **slovnik) # Vyhodnotí se jako vypis_vse(1, 2, 3, 4, a=3, b=4) - - -# Viditelnost proměnných - vytvořme si globální proměnnou x -x = 5 - -def nastavX(cislo): - # Lokální proměnná x překryje globální x - x = cislo # => 43 - print(x) # => 43 - -def nastavGlobalniX(cislo): - global x - print(x) # => 5 - x = cislo # Nastaví globální proměnnou x na 6 - print(x) # => 6 - -nastavX(43) -nastavGlobalniX(6) - - -# Funkce jsou first-class objekty -def vyrobit_scitacku(pricitane_cislo): - def scitacka(x): - return x + pricitane_cislo - return scitacka - -pricist_10 = vyrobit_scitacku(10) -pricist_10(3) # => 13 - -# Klíčové slovo lambda vytvoří anonymní funkci -(lambda parametr: parametr > 2)(3) # => True - -# Lze použít funkce map() a filter() z funkcionálního programování -map(pricist_10, [1, 2, 3]) -# => - iterovatelný objekt s obsahem: [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) -# => - iterovatelný objekt s obsahem: [6, 7] - -# S generátorovou notací lze dosáhnout podobných výsledků, ale vrací seznam -[pricist_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] -# Generátorová notace funguje i pro slovníky -{x: x**2 for x in range(1, 5)} # => {1: 1, 2: 4, 3: 9, 4: 16} -# A také pro množiny -{pismeno for pismeno in "abeceda"} # => {"d", "a", "c", "e", "b"} - - -#################################################### -## 5. Třídy -#################################################### - -# Třída Clovek je potomkem (dědí od) třídy object -class Clovek(object): - - # Atribut třídy - je sdílený všemi instancemi - druh = "H. sapiens" - - # Toto je kostruktor. Je volán, když vytváříme instanci třídy. Dvě - # podtržítka na začátku a na konci značí, že se jedná o atribut nebo - # objekt využívaný Pythonem ke speciálním účelům, ale můžete sami - # definovat jeho chování. Metody jako __init__, __str__, __repr__ - # a další se nazývají "magické metody". Nikdy nepoužívejte toto - # speciální pojmenování pro běžné metody. - def __init__(self, jmeno): - # Přiřazení parametru do atributu instance jmeno - self.jmeno = jmeno - - # Metoda instance - všechny metody instance mají "self" jako první parametr - def rekni(self, hlaska): - return "{jmeno}: {hlaska}".format(jmeno=self.jmeno, hlaska=hlaska) - - # Metoda třídy - sdílená všemi instancemi - # Dostává jako první parametr třídu, na které je volána - @classmethod - def vrat_druh(cls): - return cls.druh - - # Statická metoda je volána bez reference na třídu nebo instanci - @staticmethod - def odkaslej_si(): - return "*ehm*" - - -# Vytvoření instance -d = Clovek(jmeno="David") -a = Clovek("Adéla") -print(d.rekni("ahoj")) # Vypíše: "David: ahoj" -print(a.rekni("nazdar")) # Vypíše: "Adéla: nazdar" - -# Volání třídní metody -d.vrat_druh() # => "H. sapiens" - -# Změna atributu třídy -Clovek.druh = "H. neanderthalensis" -d.vrat_druh() # => "H. neanderthalensis" -a.vrat_druh() # => "H. neanderthalensis" - -# Volání statické metody -Clovek.odkaslej_si() # => "*ehm*" - - -#################################################### -## 6. Moduly -#################################################### - -# Lze importovat moduly -import math -print(math.sqrt(16.0)) # => 4.0 - -# Lze také importovat pouze vybrané funkce z modulu -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# Můžete také importovat všechny funkce z modulu, ale radši to nedělejte -from math import * - -# Můžete si přejmenovat modul při jeho importu -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Modul v Pythonu není nic jiného, než obyčejný soubor .py -# Můžete si napsat vlastní a prostě ho importovat podle jména -from muj_modul import moje_funkce # Nyní vyhodí ImportError - muj_modul neexistuje - -# Funkcí dir() lze zjistit, co modul obsahuje -import math -dir(math) - - -#################################################### -## 7. Pokročilé -#################################################### - -# Generátory jsou funkce, které místo return obsahují yield -def nasobicka_2(sekvence): - for i in sekvence: - print("Zpracovávám číslo {}".format(i)) - yield 2 * i - -# Generátor generuje hodnoty postupně, jak jsou potřeba. Místo toho, aby vrátil -# celou sekvenci s prvky vynásobenými dvěma, provádí jeden výpočet v každé iteraci. -for nasobek in nasobicka_2([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]): - # Vypíše postupně: "Zpracovávám číslo 1", ..., "Zpracovávám číslo 5" - if nasobek >= 10: - break - -# Funkce range() je také generátor - vytváření seznamu 900000000 prvků by zabralo -# hodně času i paměti, proto se místo toho čísla generují postupně. -for nasobek in nasobicka_2(range(900000000)): - # Vypíše postupně: "Zpracovávám číslo 1", ..., "Zpracovávám číslo 5" - if nasobek >= 10: - break - - -# Dekorátory jsou funkce, které se používají pro obalení jiné funkce, čímž mohou -# přidávat nebo měnit její stávající chování. Funkci dostávají jako parametr -# a typicky místo ní vrací jinou, která uvnitř volá tu původní. - -def nekolikrat(puvodni_funkce): - def opakovaci_funkce(*args, **kwargs): - for i in range(3): - puvodni_funkce(*args, **kwargs) - - return opakovaci_funkce - - -@nekolikrat -def pozdrav(jmeno): - print("Měj se {}!".format(jmeno)) - -pozdrav("Pepo") # Vypíše 3x: "Měj se Pepo!" -``` - -## Co dál? - -Spoustu odkazů na české i anglické materiály najdete na [webu české Python komunity] -(http://python.cz/). Můžete také přijít na Pyvo, kde to společně probereme. diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown new file mode 100644 index 00000000..4ef997a1 --- /dev/null +++ b/de-de/python-de.html.markdown @@ -0,0 +1,655 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["kultprok", "http:/www.kulturproktologie.de"] + - ["matthiaskern", "https://github.com/matthiaskern"] +filename: learnpython3-de.py +lang: de-de +--- + +Anmerkungen des ursprünglichen Autors: +Python wurde in den frühen Neunzigern von Guido van Rossum entworfen. Es ist heute eine der beliebtesten Sprachen. Ich habe mich in Python wegen seiner syntaktischen Übersichtlichkeit verliebt. Eigentlich ist es ausführbarer Pseudocode. + +Feedback ist herzlich willkommen! Ihr erreicht mich unter [@louiedinh](http://twitter.com/louiedinh) oder louiedinh [at] [google's email service]. + +Hinweis: Dieser Beitrag bezieht sich implizit auf Python 3. Falls du lieber Python 2.7 lernen möchtest, schau [hier](http://learnxinyminutes.com/docs/python/) weiter. + +```python + +# Einzeilige Kommentare beginnen mit einer Raute (Doppelkreuz) + +""" Mehrzeilige Strings werden mit + drei '-Zeichen geschrieben und werden + oft als Kommentare genutzt. +""" + +#################################################### +## 1. Primitive Datentypen und Operatoren +#################################################### + +# Die Zahlen +3 #=> 3 + +# Mathematik funktioniert so, wie man das erwartet +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 + +# Außer Division, welche automatisch Gleitkommazahlen zurückgibt +35 / 5 # => 7.0 + +# Eine Division kann mit "//" für positive sowie negative Werte abgerundet werden. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Benutzt man eine Gleitkommazahl, ist auch das Ergebnis eine solche +3 * 2.0 # => 6.0 + +# Der Rest einer Division +7 % 3 # => 1 + +# Potenz +2**4 # => 16 + +# Rangfolge wird mit Klammern erzwungen +(1 + 3) * 2 #=> 8 + +# Boolesche Ausdrücke sind primitive Datentypen +True +False + +# Mit not wird negiert +not True #=> False +not False #=> True + +# Boolesche Operatoren +# Hinweis: "and" und "or" müssen klein geschrieben werden +True and False #=> False +False or True #=> True + +# Für die Benutzung von Booleschen Operatoren und ganzen Zahlen +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# Gleichheit ist == +1 == 1 #=> True +2 == 1 #=> False + +# Ungleichheit ist != +1 != 1 #=> False +2 != 1 #=> True + +# Ein paar weitere Vergleiche +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# Vergleiche können verknüpft werden! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Strings werden mit " oder ' gebildet +"Das ist ein String." +'Das ist auch ein String.' + +# Strings können auch addiert werden! Vermeide dies aber lieber. +"Hallo " + "Welt!" #=> "Hallo Welt!" +# Strings können ohne "+" addiert werden +"Hallo " "welt!" # => "Hallo Welt!" + +# Ein String kann wie eine Liste von Zeichen verwendet werden +"Das ist ein String"[0] #=> 'D' + +# .format kann Strings formatieren +"{} können {} werden".format("Strings", "formatiert") + +# Schneller geht das mit Wiederholungen +"{0} mag Spagetthi, {0} liebt es zu Schwimmen und ganz besonders mag {0} {1}".format("Hans", "Blattsalat") +#=> "Hans mag Spagetthi, Hans liebt es zu Schwimmen und ganz besonders mag Hans Blattsalat" + +# Wir können Schlüsselwörter verwenden, wenn wir nicht abzählen wollen. +"{name} will {food} essen".format(name="Bob", food="Lasagne") +#=> "Bob will Lasagne kochen" + +#Falls dein Python 3 Code auch unter Python 2.5 oder darunter laufen soll, kann das alte Format benutzt werden: +"%s können %s werden" % ("Strings", "interpoliert") + + +# None ist ein Objekt +None #=> None + +# Verwendet nicht das Symbol für Gleichheit `==`, um Objekte mit None zu vergleichen +# Benutzt stattdessen `is`. Dieser Operator testet Objektidentität +"etc" is None #=> False +None is None #=> True + + + +# None, 0, und leere Strings/Listen werden alle als False bewertet. +# Alle anderen Werte sind True +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False + + +#################################################### +## 2. Variablen und Collections +#################################################### + +# Textausgabe ist sehr einfach +print("Ich bin Python. Schön, dich kennenzulernen!") + +# Es gibt keinen Grund, Variablen vor der Zuweisung zu deklarieren. +some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm +some_var #=> 5 + +# Das Ansprechen einer noch nicht deklarierten Variable löst eine Exception aus. +# Unter "Kontrollstruktur" kann noch mehr über +# Ausnahmebehandlung erfahren werden. +some_unknown_var # Löst einen NameError aus + +# Listen speichern Sequenzen +li = [] +# Wir können mit einer bereits gefüllten Liste anfangen +other_li = [4, 5, 6] + +# append fügt Daten am Ende der Liste ein +li.append(1) #li ist jetzt [1] +li.append(2) #li ist jetzt [1, 2] +li.append(4) #li ist jetzt [1, 2, 4] +li.append(3) #li ist jetzt [1, 2, 4, 3] +# Vom Ende der Liste mit pop entfernen +li.pop() #=> 3 und li ist jetzt [1, 2, 4] +# und dann wieder hinzufügen +li.append(3) # li ist jetzt wieder [1, 2, 4, 3]. + +# Greife auf Listen wie auf Arrays zu +li[0] #=> 1 +# Das letzte Element ansehen +li[-1] #=> 3 + +# Bei Zugriffen außerhalb der Liste kommt es jedoch zu einem IndexError +li[4] # Verursacht einen IndexError + +# Wir können uns Ranges mit Slice-Syntax ansehen +li[1:3] #=> [2, 4] +# Den Anfang auslassen +li[2:] #=> [4, 3] +# Das Ende auslassen +li[:3] #=> [1, 2, 4] +# Jeden Zweiten Eintrag auswählen +li[::2] # =>[1, 4] +# Eine umgekehrte Kopie zurückgeben +li[::-1] # => [3, 4, 2, 1] +# Jegliche Kombination dieser Syntax machen fortgeschrittene Slices möglich +# li[Start:Ende:Schritt] + +# Ein bestimmtes Element mit del aus der Liste entfernen +del li[2] # li ist jetzt [1, 2, 3] + +# Listen können addiert werden +li + other_li #=> [1, 2, 3, 4, 5, 6] - Hinweis: li und other_li werden in Ruhe gelassen + +# Listen mit extend verknüpfen +li.extend(other_li) # Jetzt ist li [1, 2, 3, 4, 5, 6] + +# Mit in auf Existenz eines Elements prüfen +1 in li #=> True + +# Die Länge der Liste mit len ermitteln +len(li) #=> 6 + + +# Tupel sind wie Listen, nur unveränderlich. +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # Löst einen TypeError aus + +# Wir können all diese Listen-Dinge auch mit Tupeln anstellen +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Wir können Tupel (oder Listen) in Variablen entpacken +a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3 +# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen +d, e, f = 4, 5, 6 +# Es ist kinderleicht zwei Werte zu tauschen +e, d = d, e # d ist nun 5 und e ist nun 4 + + +# Dictionarys (Wörterbucher) speichern Schlüssel-Werte-Paare +empty_dict = {} +# Hier ein gefülltes Wörterbuch +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Wir können Einträge mit [] nachschlagen +filled_dict["one"] #=> 1 + +# So holen wir alle Keys (Schlüssel) als Liste +list(filled_dict.keys()) #=> ["three", "two", "one"] +# Hinweis - Die Reihenfolge von Schlüsseln in der Liste ist nicht garantiert. +# Einzelne Resultate können anders angeordnet sein. + +# Alle Values (Werte) als Liste +list(filled_dict.values()) #=> [3, 2, 1] +# Hinweis - Hier gelten dieselben Einschränkungen für die Reihenfolge wie bei Schlüsseln. + +# Das Vorhandensein eines Schlüssels im Wörterbuch mit "in" prüfen +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# Einen nicht vorhandenenen Schlüssel zu suchen, löst einen KeyError aus +filled_dict["four"] # KeyError + +# Mit der get-Methode verhindern wir das +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# Die get-Methode unterstützt auch ein Standardargument, falls der Wert fehlt +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# Die setdefault-Methode ist ein sicherer Weg, ein neues Schlüssel-Wert-Paar anzulegen +filled_dict.setdefault("five", 5) #filled_dict["five"] wird auf 5 gesetzt +filled_dict.setdefault("five", 6) #filled_dict["five"] ist noch immer 5 + +# Einträge zu einem Wörterbuch hinzufügen +filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} +#filled_dict["four"] = 4 # noch ein Weg, Werte hinzuzufügen + +# Schlüssel von einem Wörterbuch entfernen +del filled_dict["one"] # Entfert den Schlüssel "one" + + +# Sets speichern Mengen +empty_set = set() +# Initialisieren wir ein Set mit ein paar Werten +some_set = {1, 1, 2, 2, 3, 4} # some_set ist jetzt {1, 2, 3, 4} + +# Neue Variablen können einer Menge gleichgesetzt werden +filled_set = some_set + +# Mehr Elemente hinzufügen +filled_set.add(5) # filled_set ist jetzt {1, 2, 3, 4, 5} + +# Schnittmengen werden mit & gebildet +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# Mengen werden mit | vereinigt +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# Die Differenz einer Menge mit - bilden +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Auf Vorhandensein von Elementen mit in prüfen +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. Kontrollstruktur und Iteratoren +#################################################### + +# Erstellen wir mal eine Variable +some_var = 5 + +# Hier eine if-Anweisung. Die Einrückung ist in Python wichtig! +# gibt "some_var ist kleiner als 10" aus +if some_var > 10: + print("some_var ist viel größer als 10.") +elif some_var < 10: # Dieser elif-Absatz ist optional. + print("some_var ist kleiner als 10.") +else: # Das hier ist auch optional. + print("some_var ist tatsächlich 10.") + + +""" +For-Schleifen iterieren über Listen +Ausgabe: + hund ist ein Säugetier + katze ist ein Säugetier + maus ist ein Säugetier +""" +for animal in ["hund", "katze", "maus"]: + # Wir können Strings mit format() formatieren + print("{} ist ein Säugetier".format(animal)) + +""" +`range(Zahl)` gibt eine null-basierte Liste bis zur angegebenen Zahl wieder +Ausgabe: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(unten, oben)" gibt eine Liste von der unteren Zahl bis zur oberen Zahl aus +Ausgabe: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +While-Schleifen laufen, bis eine Bedingung erfüllt ist. +Ausgabe: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Kurzform für x = x + 1 + +# Ausnahmebehandlung mit einem try/except-Block +try: + # Mit raise wird ein Fehler ausgegeben + raise IndexError("Das hier ist ein Index-Fehler") +except IndexError as e: + pass # Pass ist nur eine no-op. Normalerweise würden wir hier den Fehler klären. +except (TypeError, NameError): + pass # Mehrere Fehler können zusammen geklärt werden, falls erforderlich. +else: # Optional, hinter allen except-Blöcken + print("Keine Probleme!") # Wird nur ausgeführt, wenn keine Ausnahmen aufgetreten sind +finally: # Wird immer ausgeführt + print("Hier können wir Ressourcen aufräumen") + +# alternativ zu einem try/finally Block um Aufzuräumen: +with open("meineDatei.txt") as f: + for line in f: + print(line) + +# Python bietet ein fundamentales Konzept der Iteration. +# Das Objekt, auf das die Iteration, also die Wiederholung einer Methode angewandt wird heißt auf Englisch "iterable". +# Die range Methode gibt ein solches Objekt aus. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) #=> range(1,10). Dies ist ein "iterable" Objekt. + +# Über dieses können wir auch iterieren +for i in our_iterable: + print(i) # Gibt one, two, three aus + +# Allerdings können wir die einzelnen Elemente nicht mit ihrem index ausgeben +our_iterable[1] # TypeError + +# Ein iterable ist ein Objekt, das weiß wie es einen Iteratoren erschafft. +our_iterator = iter(our_iterable) + +# Unser Iterator ist ein Objekt, das sich merkt, welchen Status es gerade hat während wir durch es gehen. +# Das jeweils nächste Objekt bekommen wir mit "next()" +next(our_iterator) #=> "one" + +# Es hält den vorherigen Status +next(our_iterator) #=> "two" +next(our_iterator) #=> "three" + +# Nachdem alle Daten ausgegeben worden sind, kommt eine StopIterator Ausnahme zurück +next(our_iterator) # Gibt StopIteration aus + +# Alle Elemente können mit "list()" ausgegeben werden +list(filled_dict.keys()) #=> ["one", "two", "three"] + + + +#################################################### +## 4. Funktionen +#################################################### + +# Mit def neue Funktionen erstellen +def add(x, y): + print("x ist %s und y ist %s" % (x, y)) + return x + y # Werte werden mit return zurückgegeben + +# Funktionen mit Parametern aufrufen +add(5, 6) #=> Ausgabe ist "x ist 5 und y ist 6" und gibt 11 zurück + +# Ein anderer Weg des Funktionsaufrufs sind Schlüsselwort-Argumente +add(y=6, x=5) # Schlüsselwörter können in beliebiger Reihenfolge übergeben werden. + +# Wir können Funktionen mit beliebiger Anzahl von # Positionsargumenten definieren +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# Wir können auch Funktionen mit beliebiger Anzahl +# Schlüsselwort-Argumenten definieren +def keyword_args(**kwargs): + return kwargs + +# Rufen wir es mal auf, um zu sehen, was passiert +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# Wir können beides gleichzeitig machen, wenn wir wollen +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) Ausgabe: + (1, 2) + {"a": 3, "b": 4} +""" + +# Beim Aufruf von Funktionen können wir das Gegenteil von varargs/kwargs machen! +# Wir benutzen dann *, um Tupel auszuweiten, und ** für kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # äquivalent zu foo(1, 2, 3, 4) +all_the_args(**kwargs) # äquivalent zu foo(a=3, b=4) +all_the_args(*args, **kwargs) # äquivalent zu foo(1, 2, 3, 4, a=3, b=4) + + +# Anwendungsbereich von Funktionen +x = 5 + +def setX(num): + # lokale Variable x ist nicht die globale Variable x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # globale Variable x ist jetzt 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# Python hat First-Class-Funktionen +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Es gibt auch anonyme Funktionen +(lambda x: x > 2)(3) #=> True + +# Es gibt auch Funktionen höherer Ordnung als Built-Ins +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Wir können bei map- und filter-Funktionen auch List Comprehensions einsetzen +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] + +#################################################### +## 5. Klassen +#################################################### + +# Wir bilden die Unterklasse eines Objekts, um Klassen zu erhalten. +class Human(object): + + # Ein Klassenattribut. Es wird von allen Instanzen einer Klasse geteilt + species = "H. sapiens" + + # Ein simpler Konstruktor + def __init__(self, name): + # Wir weisen das Argument name dem name-Attribut der Instanz zu + self.name = name + + # Eine Instanzmethode. Alle Methoden erhalten self als erstes Argument. + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # Eine Klassenmethode wird von allen Instanzen geteilt. + # Sie werden mit der aufrufenden Klasse als erstem Argument aufgerufen + @classmethod + def get_species(cls): + return cls.species + + # Eine statische Methode wird ohne Klasse oder Instanz aufgerufen + @staticmethod + def grunt(): + return "*grunt*" + + +# Eine Instanz einer Klasse erstellen +i = Human(name="Ian") +print(i.say("hi")) # gibt "Ian: hi" aus + +j = Human("Joel") +print(j.say("hello")) #gibt "Joel: hello" aus + +# Rufen wir mal unsere Klassenmethode auf +i.get_species() #=> "H. sapiens" + +# Ändern wir mal das gemeinsame Attribut +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Aufruf der statischen Methode +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. Module +#################################################### + +# Wir können Module importieren +import math +print(math.sqrt(16)) #=> 4.0 + +# Wir können auch nur spezielle Funktionen eines Moduls importieren +from math import ceil, floor +print(ceil(3.7)) #=> 4.0 +print(floor(3.7)) #=> 3.0 + +# Wir können auch alle Funktionen eines Moduls importieren +# Warnung: Dies wird nicht empfohlen +from math import * + +# Wir können Modulnamen abkürzen +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Module sind in Python nur gewöhnliche Dateien. Wir +# können unsere eigenen schreiben und importieren. Der Name des +# Moduls ist der Dateiname. + +# Wir können auch die Funktionen und Attribute eines +# Moduls herausfinden. +import math +dir(math) + + +#################################################### +## 7. Fortgeschritten +#################################################### + +# Generatoren helfen um Code schnell und einfach zu schreiben +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Ein Generator erschafft Werte spontan +# Statt alle Werte auf einmal, wird bei jeder Iteration einer erschaffen. +# iteration. Das heißt, Werte größer als 15 werden nicht behandelt. +# Die range-Methode ist auch ein Generator. Im Fall einer Liste von 1-900000000 +# würde das sehr viel Zeit in Anspruch nehmen. +# Wenn wir eine variable mit einem Namen erschaffen wollen, das +# normalerweise mit einem Python - Schlüsselwort kollidieren würde, +# benutzen wir einen Unterstrich nach dem Wort. +range_ = range(1, 900000000) +# Alle Nummern bis zu einem Ergebnis von >=30 werden verdoppelt +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Dekoratoren +# In diesem Beispiel die Methode beg umwickelt say +# Beim Aufruf von beg, say wird aufgerufen +# Falls say_please true ist, ändert sich die ausgegebene Nachricht +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # Can you buy me a beer? +print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( + +``` + +## Lust auf mehr? + +### Kostenlos online (Englisch) + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) + +### Totholz (Englisch) + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/de-de/python3-de.html.markdown b/de-de/python3-de.html.markdown deleted file mode 100644 index 4ef997a1..00000000 --- a/de-de/python3-de.html.markdown +++ /dev/null @@ -1,655 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://ldinh.ca"] -translators: - - ["kultprok", "http:/www.kulturproktologie.de"] - - ["matthiaskern", "https://github.com/matthiaskern"] -filename: learnpython3-de.py -lang: de-de ---- - -Anmerkungen des ursprünglichen Autors: -Python wurde in den frühen Neunzigern von Guido van Rossum entworfen. Es ist heute eine der beliebtesten Sprachen. Ich habe mich in Python wegen seiner syntaktischen Übersichtlichkeit verliebt. Eigentlich ist es ausführbarer Pseudocode. - -Feedback ist herzlich willkommen! Ihr erreicht mich unter [@louiedinh](http://twitter.com/louiedinh) oder louiedinh [at] [google's email service]. - -Hinweis: Dieser Beitrag bezieht sich implizit auf Python 3. Falls du lieber Python 2.7 lernen möchtest, schau [hier](http://learnxinyminutes.com/docs/python/) weiter. - -```python - -# Einzeilige Kommentare beginnen mit einer Raute (Doppelkreuz) - -""" Mehrzeilige Strings werden mit - drei '-Zeichen geschrieben und werden - oft als Kommentare genutzt. -""" - -#################################################### -## 1. Primitive Datentypen und Operatoren -#################################################### - -# Die Zahlen -3 #=> 3 - -# Mathematik funktioniert so, wie man das erwartet -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 - -# Außer Division, welche automatisch Gleitkommazahlen zurückgibt -35 / 5 # => 7.0 - -# Eine Division kann mit "//" für positive sowie negative Werte abgerundet werden. -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # works on floats too --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Benutzt man eine Gleitkommazahl, ist auch das Ergebnis eine solche -3 * 2.0 # => 6.0 - -# Der Rest einer Division -7 % 3 # => 1 - -# Potenz -2**4 # => 16 - -# Rangfolge wird mit Klammern erzwungen -(1 + 3) * 2 #=> 8 - -# Boolesche Ausdrücke sind primitive Datentypen -True -False - -# Mit not wird negiert -not True #=> False -not False #=> True - -# Boolesche Operatoren -# Hinweis: "and" und "or" müssen klein geschrieben werden -True and False #=> False -False or True #=> True - -# Für die Benutzung von Booleschen Operatoren und ganzen Zahlen -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -1 == True #=> True - -# Gleichheit ist == -1 == 1 #=> True -2 == 1 #=> False - -# Ungleichheit ist != -1 != 1 #=> False -2 != 1 #=> True - -# Ein paar weitere Vergleiche -1 < 10 #=> True -1 > 10 #=> False -2 <= 2 #=> True -2 >= 2 #=> True - -# Vergleiche können verknüpft werden! -1 < 2 < 3 #=> True -2 < 3 < 2 #=> False - -# Strings werden mit " oder ' gebildet -"Das ist ein String." -'Das ist auch ein String.' - -# Strings können auch addiert werden! Vermeide dies aber lieber. -"Hallo " + "Welt!" #=> "Hallo Welt!" -# Strings können ohne "+" addiert werden -"Hallo " "welt!" # => "Hallo Welt!" - -# Ein String kann wie eine Liste von Zeichen verwendet werden -"Das ist ein String"[0] #=> 'D' - -# .format kann Strings formatieren -"{} können {} werden".format("Strings", "formatiert") - -# Schneller geht das mit Wiederholungen -"{0} mag Spagetthi, {0} liebt es zu Schwimmen und ganz besonders mag {0} {1}".format("Hans", "Blattsalat") -#=> "Hans mag Spagetthi, Hans liebt es zu Schwimmen und ganz besonders mag Hans Blattsalat" - -# Wir können Schlüsselwörter verwenden, wenn wir nicht abzählen wollen. -"{name} will {food} essen".format(name="Bob", food="Lasagne") -#=> "Bob will Lasagne kochen" - -#Falls dein Python 3 Code auch unter Python 2.5 oder darunter laufen soll, kann das alte Format benutzt werden: -"%s können %s werden" % ("Strings", "interpoliert") - - -# None ist ein Objekt -None #=> None - -# Verwendet nicht das Symbol für Gleichheit `==`, um Objekte mit None zu vergleichen -# Benutzt stattdessen `is`. Dieser Operator testet Objektidentität -"etc" is None #=> False -None is None #=> True - - - -# None, 0, und leere Strings/Listen werden alle als False bewertet. -# Alle anderen Werte sind True -bool(0) # => False -bool("") # => False -bool([]) #=> False -bool({}) #=> False - - -#################################################### -## 2. Variablen und Collections -#################################################### - -# Textausgabe ist sehr einfach -print("Ich bin Python. Schön, dich kennenzulernen!") - -# Es gibt keinen Grund, Variablen vor der Zuweisung zu deklarieren. -some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm -some_var #=> 5 - -# Das Ansprechen einer noch nicht deklarierten Variable löst eine Exception aus. -# Unter "Kontrollstruktur" kann noch mehr über -# Ausnahmebehandlung erfahren werden. -some_unknown_var # Löst einen NameError aus - -# Listen speichern Sequenzen -li = [] -# Wir können mit einer bereits gefüllten Liste anfangen -other_li = [4, 5, 6] - -# append fügt Daten am Ende der Liste ein -li.append(1) #li ist jetzt [1] -li.append(2) #li ist jetzt [1, 2] -li.append(4) #li ist jetzt [1, 2, 4] -li.append(3) #li ist jetzt [1, 2, 4, 3] -# Vom Ende der Liste mit pop entfernen -li.pop() #=> 3 und li ist jetzt [1, 2, 4] -# und dann wieder hinzufügen -li.append(3) # li ist jetzt wieder [1, 2, 4, 3]. - -# Greife auf Listen wie auf Arrays zu -li[0] #=> 1 -# Das letzte Element ansehen -li[-1] #=> 3 - -# Bei Zugriffen außerhalb der Liste kommt es jedoch zu einem IndexError -li[4] # Verursacht einen IndexError - -# Wir können uns Ranges mit Slice-Syntax ansehen -li[1:3] #=> [2, 4] -# Den Anfang auslassen -li[2:] #=> [4, 3] -# Das Ende auslassen -li[:3] #=> [1, 2, 4] -# Jeden Zweiten Eintrag auswählen -li[::2] # =>[1, 4] -# Eine umgekehrte Kopie zurückgeben -li[::-1] # => [3, 4, 2, 1] -# Jegliche Kombination dieser Syntax machen fortgeschrittene Slices möglich -# li[Start:Ende:Schritt] - -# Ein bestimmtes Element mit del aus der Liste entfernen -del li[2] # li ist jetzt [1, 2, 3] - -# Listen können addiert werden -li + other_li #=> [1, 2, 3, 4, 5, 6] - Hinweis: li und other_li werden in Ruhe gelassen - -# Listen mit extend verknüpfen -li.extend(other_li) # Jetzt ist li [1, 2, 3, 4, 5, 6] - -# Mit in auf Existenz eines Elements prüfen -1 in li #=> True - -# Die Länge der Liste mit len ermitteln -len(li) #=> 6 - - -# Tupel sind wie Listen, nur unveränderlich. -tup = (1, 2, 3) -tup[0] #=> 1 -tup[0] = 3 # Löst einen TypeError aus - -# Wir können all diese Listen-Dinge auch mit Tupeln anstellen -len(tup) #=> 3 -tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tup[:2] #=> (1, 2) -2 in tup #=> True - -# Wir können Tupel (oder Listen) in Variablen entpacken -a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3 -# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen -d, e, f = 4, 5, 6 -# Es ist kinderleicht zwei Werte zu tauschen -e, d = d, e # d ist nun 5 und e ist nun 4 - - -# Dictionarys (Wörterbucher) speichern Schlüssel-Werte-Paare -empty_dict = {} -# Hier ein gefülltes Wörterbuch -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Wir können Einträge mit [] nachschlagen -filled_dict["one"] #=> 1 - -# So holen wir alle Keys (Schlüssel) als Liste -list(filled_dict.keys()) #=> ["three", "two", "one"] -# Hinweis - Die Reihenfolge von Schlüsseln in der Liste ist nicht garantiert. -# Einzelne Resultate können anders angeordnet sein. - -# Alle Values (Werte) als Liste -list(filled_dict.values()) #=> [3, 2, 1] -# Hinweis - Hier gelten dieselben Einschränkungen für die Reihenfolge wie bei Schlüsseln. - -# Das Vorhandensein eines Schlüssels im Wörterbuch mit "in" prüfen -"one" in filled_dict #=> True -1 in filled_dict #=> False - -# Einen nicht vorhandenenen Schlüssel zu suchen, löst einen KeyError aus -filled_dict["four"] # KeyError - -# Mit der get-Methode verhindern wir das -filled_dict.get("one") #=> 1 -filled_dict.get("four") #=> None -# Die get-Methode unterstützt auch ein Standardargument, falls der Wert fehlt -filled_dict.get("one", 4) #=> 1 -filled_dict.get("four", 4) #=> 4 - -# Die setdefault-Methode ist ein sicherer Weg, ein neues Schlüssel-Wert-Paar anzulegen -filled_dict.setdefault("five", 5) #filled_dict["five"] wird auf 5 gesetzt -filled_dict.setdefault("five", 6) #filled_dict["five"] ist noch immer 5 - -# Einträge zu einem Wörterbuch hinzufügen -filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} -#filled_dict["four"] = 4 # noch ein Weg, Werte hinzuzufügen - -# Schlüssel von einem Wörterbuch entfernen -del filled_dict["one"] # Entfert den Schlüssel "one" - - -# Sets speichern Mengen -empty_set = set() -# Initialisieren wir ein Set mit ein paar Werten -some_set = {1, 1, 2, 2, 3, 4} # some_set ist jetzt {1, 2, 3, 4} - -# Neue Variablen können einer Menge gleichgesetzt werden -filled_set = some_set - -# Mehr Elemente hinzufügen -filled_set.add(5) # filled_set ist jetzt {1, 2, 3, 4, 5} - -# Schnittmengen werden mit & gebildet -other_set = {3, 4, 5, 6} -filled_set & other_set #=> {3, 4, 5} - -# Mengen werden mit | vereinigt -filled_set | other_set #=> {1, 2, 3, 4, 5, 6} - -# Die Differenz einer Menge mit - bilden -{1,2,3,4} - {2,3,5} #=> {1, 4} - -# Auf Vorhandensein von Elementen mit in prüfen -2 in filled_set #=> True -10 in filled_set #=> False - - -#################################################### -## 3. Kontrollstruktur und Iteratoren -#################################################### - -# Erstellen wir mal eine Variable -some_var = 5 - -# Hier eine if-Anweisung. Die Einrückung ist in Python wichtig! -# gibt "some_var ist kleiner als 10" aus -if some_var > 10: - print("some_var ist viel größer als 10.") -elif some_var < 10: # Dieser elif-Absatz ist optional. - print("some_var ist kleiner als 10.") -else: # Das hier ist auch optional. - print("some_var ist tatsächlich 10.") - - -""" -For-Schleifen iterieren über Listen -Ausgabe: - hund ist ein Säugetier - katze ist ein Säugetier - maus ist ein Säugetier -""" -for animal in ["hund", "katze", "maus"]: - # Wir können Strings mit format() formatieren - print("{} ist ein Säugetier".format(animal)) - -""" -`range(Zahl)` gibt eine null-basierte Liste bis zur angegebenen Zahl wieder -Ausgabe: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -"range(unten, oben)" gibt eine Liste von der unteren Zahl bis zur oberen Zahl aus -Ausgabe: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -While-Schleifen laufen, bis eine Bedingung erfüllt ist. -Ausgabe: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Kurzform für x = x + 1 - -# Ausnahmebehandlung mit einem try/except-Block -try: - # Mit raise wird ein Fehler ausgegeben - raise IndexError("Das hier ist ein Index-Fehler") -except IndexError as e: - pass # Pass ist nur eine no-op. Normalerweise würden wir hier den Fehler klären. -except (TypeError, NameError): - pass # Mehrere Fehler können zusammen geklärt werden, falls erforderlich. -else: # Optional, hinter allen except-Blöcken - print("Keine Probleme!") # Wird nur ausgeführt, wenn keine Ausnahmen aufgetreten sind -finally: # Wird immer ausgeführt - print("Hier können wir Ressourcen aufräumen") - -# alternativ zu einem try/finally Block um Aufzuräumen: -with open("meineDatei.txt") as f: - for line in f: - print(line) - -# Python bietet ein fundamentales Konzept der Iteration. -# Das Objekt, auf das die Iteration, also die Wiederholung einer Methode angewandt wird heißt auf Englisch "iterable". -# Die range Methode gibt ein solches Objekt aus. - -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) #=> range(1,10). Dies ist ein "iterable" Objekt. - -# Über dieses können wir auch iterieren -for i in our_iterable: - print(i) # Gibt one, two, three aus - -# Allerdings können wir die einzelnen Elemente nicht mit ihrem index ausgeben -our_iterable[1] # TypeError - -# Ein iterable ist ein Objekt, das weiß wie es einen Iteratoren erschafft. -our_iterator = iter(our_iterable) - -# Unser Iterator ist ein Objekt, das sich merkt, welchen Status es gerade hat während wir durch es gehen. -# Das jeweils nächste Objekt bekommen wir mit "next()" -next(our_iterator) #=> "one" - -# Es hält den vorherigen Status -next(our_iterator) #=> "two" -next(our_iterator) #=> "three" - -# Nachdem alle Daten ausgegeben worden sind, kommt eine StopIterator Ausnahme zurück -next(our_iterator) # Gibt StopIteration aus - -# Alle Elemente können mit "list()" ausgegeben werden -list(filled_dict.keys()) #=> ["one", "two", "three"] - - - -#################################################### -## 4. Funktionen -#################################################### - -# Mit def neue Funktionen erstellen -def add(x, y): - print("x ist %s und y ist %s" % (x, y)) - return x + y # Werte werden mit return zurückgegeben - -# Funktionen mit Parametern aufrufen -add(5, 6) #=> Ausgabe ist "x ist 5 und y ist 6" und gibt 11 zurück - -# Ein anderer Weg des Funktionsaufrufs sind Schlüsselwort-Argumente -add(y=6, x=5) # Schlüsselwörter können in beliebiger Reihenfolge übergeben werden. - -# Wir können Funktionen mit beliebiger Anzahl von # Positionsargumenten definieren -def varargs(*args): - return args - -varargs(1, 2, 3) #=> (1,2,3) - - -# Wir können auch Funktionen mit beliebiger Anzahl -# Schlüsselwort-Argumenten definieren -def keyword_args(**kwargs): - return kwargs - -# Rufen wir es mal auf, um zu sehen, was passiert -keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} - -# Wir können beides gleichzeitig machen, wenn wir wollen -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) Ausgabe: - (1, 2) - {"a": 3, "b": 4} -""" - -# Beim Aufruf von Funktionen können wir das Gegenteil von varargs/kwargs machen! -# Wir benutzen dann *, um Tupel auszuweiten, und ** für kwargs. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # äquivalent zu foo(1, 2, 3, 4) -all_the_args(**kwargs) # äquivalent zu foo(a=3, b=4) -all_the_args(*args, **kwargs) # äquivalent zu foo(1, 2, 3, 4, a=3, b=4) - - -# Anwendungsbereich von Funktionen -x = 5 - -def setX(num): - # lokale Variable x ist nicht die globale Variable x - x = num # => 43 - print (x) # => 43 - -def setGlobalX(num): - global x - print (x) # => 5 - x = num # globale Variable x ist jetzt 6 - print (x) # => 6 - -setX(43) -setGlobalX(6) - - -# Python hat First-Class-Funktionen -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) #=> 13 - -# Es gibt auch anonyme Funktionen -(lambda x: x > 2)(3) #=> True - -# Es gibt auch Funktionen höherer Ordnung als Built-Ins -map(add_10, [1,2,3]) #=> [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] - -# Wir können bei map- und filter-Funktionen auch List Comprehensions einsetzen -[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] - -#################################################### -## 5. Klassen -#################################################### - -# Wir bilden die Unterklasse eines Objekts, um Klassen zu erhalten. -class Human(object): - - # Ein Klassenattribut. Es wird von allen Instanzen einer Klasse geteilt - species = "H. sapiens" - - # Ein simpler Konstruktor - def __init__(self, name): - # Wir weisen das Argument name dem name-Attribut der Instanz zu - self.name = name - - # Eine Instanzmethode. Alle Methoden erhalten self als erstes Argument. - def say(self, msg): - return "{name}: {message}".format(name=self.name, message=msg) - - # Eine Klassenmethode wird von allen Instanzen geteilt. - # Sie werden mit der aufrufenden Klasse als erstem Argument aufgerufen - @classmethod - def get_species(cls): - return cls.species - - # Eine statische Methode wird ohne Klasse oder Instanz aufgerufen - @staticmethod - def grunt(): - return "*grunt*" - - -# Eine Instanz einer Klasse erstellen -i = Human(name="Ian") -print(i.say("hi")) # gibt "Ian: hi" aus - -j = Human("Joel") -print(j.say("hello")) #gibt "Joel: hello" aus - -# Rufen wir mal unsere Klassenmethode auf -i.get_species() #=> "H. sapiens" - -# Ändern wir mal das gemeinsame Attribut -Human.species = "H. neanderthalensis" -i.get_species() #=> "H. neanderthalensis" -j.get_species() #=> "H. neanderthalensis" - -# Aufruf der statischen Methode -Human.grunt() #=> "*grunt*" - - -#################################################### -## 6. Module -#################################################### - -# Wir können Module importieren -import math -print(math.sqrt(16)) #=> 4.0 - -# Wir können auch nur spezielle Funktionen eines Moduls importieren -from math import ceil, floor -print(ceil(3.7)) #=> 4.0 -print(floor(3.7)) #=> 3.0 - -# Wir können auch alle Funktionen eines Moduls importieren -# Warnung: Dies wird nicht empfohlen -from math import * - -# Wir können Modulnamen abkürzen -import math as m -math.sqrt(16) == m.sqrt(16) #=> True - -# Module sind in Python nur gewöhnliche Dateien. Wir -# können unsere eigenen schreiben und importieren. Der Name des -# Moduls ist der Dateiname. - -# Wir können auch die Funktionen und Attribute eines -# Moduls herausfinden. -import math -dir(math) - - -#################################################### -## 7. Fortgeschritten -#################################################### - -# Generatoren helfen um Code schnell und einfach zu schreiben -def double_numbers(iterable): - for i in iterable: - yield i + i - -# Ein Generator erschafft Werte spontan -# Statt alle Werte auf einmal, wird bei jeder Iteration einer erschaffen. -# iteration. Das heißt, Werte größer als 15 werden nicht behandelt. -# Die range-Methode ist auch ein Generator. Im Fall einer Liste von 1-900000000 -# würde das sehr viel Zeit in Anspruch nehmen. -# Wenn wir eine variable mit einem Namen erschaffen wollen, das -# normalerweise mit einem Python - Schlüsselwort kollidieren würde, -# benutzen wir einen Unterstrich nach dem Wort. -range_ = range(1, 900000000) -# Alle Nummern bis zu einem Ergebnis von >=30 werden verdoppelt -for i in double_numbers(range_): - print(i) - if i >= 30: - break - - -# Dekoratoren -# In diesem Beispiel die Methode beg umwickelt say -# Beim Aufruf von beg, say wird aufgerufen -# Falls say_please true ist, ändert sich die ausgegebene Nachricht -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please - - -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( - -``` - -## Lust auf mehr? - -### Kostenlos online (Englisch) - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) - -### Totholz (Englisch) - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/el-gr/python-gr.html.markdown b/el-gr/python-gr.html.markdown new file mode 100644 index 00000000..445b85ba --- /dev/null +++ b/el-gr/python-gr.html.markdown @@ -0,0 +1,1031 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["evuez", "http://github.com/evuez"] + - ["Rommel Martinez", "https://ebzzry.io"] + - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] +filename: learnpython3-gr.py +lang: el-gr +--- + +Η Python δημιουργήθηκε από τον Guido van Rossum στις αρχές των 90s. Πλέον είναι μία από τις πιο +δημοφιλείς γλώσσες. Ερωτευεται κανείς την python για τη συντακτική της απλότητα. +Βασικά είναι εκτελέσιμος ψευδοκώδικας. + +Το Feedback είναι πάντα δεκτό! Μπορείτε να με βρείτε στο [@haritonaras](http://twitter.com/haritonaras) +ή τον αρχικό συγγραφέα στο [@louiedinh](http://twitter.com/louiedinh) ή στο +louiedinh [at] [google's email service] + +Σημείωση: Το παρόν άρθρο ασχολείται μόνο με την Python 3. Δείτε [εδώ](http://learnxinyminutes.com/docs/python/) αν θέλετε να μάθετε την παλιά Python 2.7 + +```python + +# Τα σχόλια μίας γραμμής ξεκινούν με # + +""" Τα σχόλια πολλαπλών γραμμών μπορούν + να γραφούν με τρία ", και συχνά χρησιμοποιούνται + ως documentation. +""" + +#################################################### +## 1. Primitive (πρωταρχικοί) Τύποι Δεδομένων και Τελεστές +#################################################### + +# Αφού έχει αριθμούς +3 # => 3 + +# Λογικά θα έχει και Μαθηματικά... +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 + +# Η διαίρεση ακεραίων κάνει στρογγυλοποίηση προς τα κάτω για θετικούς και αρνητικούς αριθμούς +5 // 3 # => 1 +-5 // 3 # => -2 +5.0 // 3.0 # => 1.0 # works on floats too +-5.0 // 3.0 # => -2.0 + +# Το αποτέλεσμα της διαίρεσης είναι πάντα float +10.0 / 3 # => 3.3333333333333335 + +# Modulo τελεστής +7 % 3 # => 1 + +# Ύψωση σε δύναμη (x**y, x στην y-οστή δύναμη) +2**3 # => 8 + +# Ελέγχουμε την προτεραιότητα πράξεων με παρενθέσεις +(1 + 3) * 2 # => 8 + +# Οι Boolean τιμές είναι primitives (Σημ.: τα κεφαλαία) +True +False + +# άρνηση με το not +not True # => False +not False # => True + +# Boolean τελεστές +# Σημ. ότι τα "and" και "or" είναι case-sensitive +True and False # => False +False or True # => True + +# Τα True και False είναι 1 και 0 αλλά με διαφορετικά keywords +True + True # => 2 +True * 8 # => 8 +False - 5 # => -5 + +# Μπορούμε να δούμε τις αριθμητικές τιμές των True και False μέσω των τελεστών σύγκρισης +0 == False # => True +1 == True # => True +2 == True # => False +-5 != False # => True + +# Χρησιμοποιώντας τελεστές boolean σε ακεραίους, οι ακέραιοι γίνονται cast σε +# boolean ώστε να γίνει η αποτίμηση της έκφρασης. +# Το αποτέλεσμα όμως είναι non-cast, δηλαδή ίδιου τύπου με τα αρχικά ορίσματα +# Μην μπερδεύετε τις bool(ints) και bitwise and/or (&,|) +bool(0) # => False +bool(4) # => True +bool(-6) # => True +0 and 2 # => 0 +-5 or 0 # => -5 + +# Ισότητα == +1 == 1 # => True +2 == 1 # => False + +# Διάφορο != +1 != 1 # => False +2 != 1 # => True + +# Περισσότερες συγκρίσεις +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Κοιτάζουμε αν μία τιμή ανήκει σε ένα εύρος +1 < 2 and 2 < 3 # => True +2 < 3 and 3 < 2 # => False +# Το Chaining (αλυσίδωση? :P) κάνει το παραπάνω πιο όμορφα +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (is vs. ==) το is ελέγχει αν δύο μεταβλητές αναφέρονται στο ίδιο αντικείμενο, +# αλλά το == ελέγχει αν τα αντικείμενα στα οποία αναφέρονται οι μεταβλητές έχουν τις ίδιες τιμές +a = [1, 2, 3, 4] # το a δείχνει σε μία νέα λίστα, [1,2,3,4] +b = a # το b δείχνει στο αντικείμενο που δείχνει το a +b is a # => True, a και b αναφέρονται στο ίδιο αντικείμενο +b == a # => True, τα αντικείμενα των a κι b είναι ίσα +b = [1, 2, 3, 4] # Το b δείχνει σε μία νέα λίστα, [1, 2, 3, 4] +b is a # => False, a και b δεν αναφέρονται στο ίδιο αντικείμενο +b == a # => True, τα αντικείμενα των a και b είναι ίσα + +# Τα Strings (συμβολοσειρές) δημιουργούνται με " ή ' +"This is a string." +'This is also a string.' + +# Μπορούμε και να προσθέτουμε Strings, αλλά προσπαθήστε να μην το κάνετε +"Hello " + "world!" # => "Hello world!" +# Τα String literals (αλλά όχι οι μεταβλητές) μπορούν να συντμιθούν και χωρίς το '+' +"Hello " "world!" # => "Hello world!" + +# Μπορούμε να φερθούμε σε string σαν να είναι λίστα από χαρακτήρες +"This is a string"[0] # => 'T' + +# Μπορούμε να βρούμε το μήκος ενός string +len("This is a string") # => 16 + +# Το .format μπορεί να χρησιμοποιηθεί για να μορφοποιήσουμε strings, όπως εδώ: +"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" + +# Μπορείς να επαναλάβεις τα ορίσματα του formatting για να γλιτώσεις λίγο χρονο +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# Μπορείς να χρησιμοποιήσεις keywords αν βαριέσαι το μέτρημα. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" + +# Αν ο κώδικας Python 3 που γράφεις πρόκειται να τρέξει και με python 2.5 ή παλιότερη +# μπορείς επίσης να χρησιμοποιήσεις το παλιό τρόπο για formatting: +"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" + +# Μπορείς επίσης να μορφοποιήσεις χρησιμοποιώντας τα f-strings / formatted string literals (σε Python 3.6+) +name = "Reiko" +f"She said her name is {name}." # => "She said her name is Reiko" +# Μπορείς βασικά να βάλεις οποιαδήποτε έκφραση Python στα άγκιστρα και θα εμφανιστεί στο string. +f"{name} is {len(name)} characters long." + + +# το None είναι ένα αντικείμενο (object) +None # => None + +# Μη χρησιμοποιείτε το σύμβολο ισότητας "==" για να συγκρίνετε αντικείμενα με το None +# Χρησιμοποιείτε το "is". Αυτό ελέγχει για ισότητα της ταυτότητας του αντικειμένου. +"etc" is None # => False +None is None # => True + +# Τα None, 0, και τα κενά strings/lists/dicts/tuples αποτιμούνται στην τιμή False +# All other values are True +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False +bool(()) # => False + +#################################################### +## 2. Μεταβλητές (variables) και Συλλογές (collections) +#################################################### + +# Η Python έχει μία συνάρτηση print() +print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! + +# By default, η συνάρτηση print() τυπώνει και ένα χαρακτήρα αλλαγής γραμμμής στο τέλος +# Χρησιμοποιείτε το προαιρετικό όρισμο end για να τυπώνει οτιδήποτε άλλο +print("Hello, World", end="!") # => Hello, World! + +# Απλός τρόπος για να πάρουμε δεδομένα εισόδου από το console +input_string_var = input("Enter some data: ") # επιστρέφει τα δεδομένα ως string +# Σημ.: Στις προηγούμενες εκδόσεις της Python, η μέθοδος input() ονομαζόταν raw_input() + +# Δεν υπάρχουν δηλώσεις, μόνο αναθέσεις τιμών. +# Η σύμβαση είναι να χρησιμοποιούμε μικρά γράμματα με κάτω παύλες +some_var = 5 +some_var # => 5 + +# Η πρόσβαση σε μεταβλητή που δεν έχει λάβει τιμή είναι εξαίρεση +# Δες τον Έλεγχο Ροής για να μάθεις περισσότερα για το χειρισμό εξαιρέσεων +some_unknown_var # Προκαλέι ένα NameError + +# Η παρακάτω έκφραση μπορεί να χρησιμποιηθεί ισοδύναμα με τον τελεστή '?' της C +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Οι λίστες κρατούν ακολουθίς +li = [] +# Μπορείς να αρχίσεις με μία προ-γεμισμένη λίστα +other_li = [4, 5, 6] + +# Και να βάλεις πράγματα στο τέλος με την μέθοδο append +li.append(1) # η li τώρα είναι [1] +li.append(2) # η li τώρα είναι [1, 2] +li.append(4) # η li τώρα είναι [1, 2, 4] +li.append(3) # η li τώρα είναι [1, 2, 4, 3] +# Αφαιρούμε από το τέλος με την μέθοδο pop +li.pop() # => 3 και η li γίνεται [1, 2, 4] +# Ας βάλουμε το 3 πίσω στη θέση του +li.append(3) # η li γίνεται πάλι [1, 2, 4, 3]. + +# Προσπελαύνουμε τις λίστες όπως τους πίνακες σε άλλες γλώσσες +li[0] # => 1 +# Το τελευταίο στοιχείο... +li[-1] # => 3 + +# Όταν βγαίνουμε εκτός ορίων της λίστας προκαλείται IndexError +li[4] # προκαλεί IndexError + +# Μπορείς να δεις ranges μιας λίστας με το slice syntax ':' +# Ο δείκτης εκίνησης περιλαμβάνεται στο διάστημα, ο δείκτης τερματισμού όχι +# (είναι ανοικτό/κλειστό διάστημα για τους φίλους των μαθηματικών) +li[1:3] # => [2, 4] +# Αγνόησε την αρχή και επίστρεψε τη λίστα +li[2:] # => [4, 3] +# Αγνόησε το τέλος και επίστρεψε τη λίστα +li[:3] # => [1, 2, 4] +# Διάλεξε κάθε δεύτερο στοιχείο +li[::2] # =>[1, 4] +# Επίστρεψε ένα reversed αντίγραφο της λίστας +li[::-1] # => [3, 4, 2, 1] +# Χρησιμοποιείστε οποιαδήποτε συνδυασμό αυτών για να φτιάξετε πιο προχωρημένα slices +# li[start:end:step] + +# Φτιάξε ένα αντίγραφο της λίστας χρησιμοποιώντας slices +li2 = li[:] # => li2 = [1, 2, 4, 3] αλλά το (li2 is li) επιστρέφει False + +# Αφαίρεσε οποιοδήποτε στοιχείο από λίστα με την εντολή "del" +del li[2] # η li γίνεται [1, 2, 3] + +# Αφαιρούμε το πρώτο στιγμυότυπο μιας τιμής +li.remove(2) # η li γίνεται [1, 3] +li.remove(2) # Προκαλεί ένα ValueError καθώς το 2 δεν βρίσκεται στη λίστα. + +# Εισαγωγή ενός στοιχείου σε συγκεκριμένη θέση +li.insert(1, 2) # η li γίνεται πάλι [1, 2, 3] + +# Βρες το index (δείκτη) του πρώτου στοιχείου με τιμή ίση με το όρισμα +li.index(2) # => 1 +li.index(4) # Προκαλεί ValueError καθώς το 4 δεν βρίσκεται στη λίστα + +# Μπορείς να προσθέτεις λίστες +# Σημ.: οι τιμές των li, other_li δεν αλλάζουν. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Σύντμιση λιστών με τη μέθοδο "extend()" +li.extend(other_li) # Τώρα η li είναι [1, 2, 3, 4, 5, 6] + +# Ελεγχος της ύπαρξης στοιχείου σε λίστα με το "in" +1 in li # => True + +# Εξατάζουμε το μήκος με "len()" +len(li) # => 6 + + +# Τα Tuples είναι σαν τις λίστες αλλά είναι αμετάβλητα (immutable). +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Προκαλεί TypeError + +# Σημειώστε ότι ένα tuple μήκους 1 πρέπει να έχει ένα κόμμα μετά το τελευταίο στοιχείο +# αλλά τα tuples άλλων μηκών, ακόμα και μηδενικού μήκους, δεν χρειάζονται κόμμα. +type((1)) # => +type((1,)) # => +type(()) # => + +# Μπορείς να εφαρμόσεις τις περισσότερες μεθόδους των λιστών και στα tuples +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Μπορείς να κάνεις unpack/"ξεπακετάρεις" tuples σε μεταβλητές +a, b, c = (1, 2, 3) # a == 1, b == 2 και c == 3 +# Μπορείς επίσης να επεκτείνεις το unpacking +a, *b, c = (1, 2, 3, 4) # a == 1, b == [2, 3] και c == 4 +# Τα Tuples δημιουργούνται by deafult αν δεν βάλεις παρενθέσεις +d, e, f = 4, 5, 6 # το tuple 4, 5, 6 "ξεπακετάρεται" στις μεταβλητές d, e και f +# αντίστοιχα έτσι ώστε να γίνεται d = 4, e = 5 and f = 6 +# Δείτε πόσο εύκολα μπορούμε να εναλλάσουμε δύο τιμές +e, d = d, e # το d παίρνει την τιμή 5 και το e παίρνει την τιμή 4 + + +# Τα λεξικά (Dictionaries) αποθηκεύουν απεικονίσεις από κλειδιά σε τιμές +empty_dict = {} +# Εδώ έχουμε ένα προ-γεμισμένο dictionary +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Σημ. ότι τα κλειδιά για τα dictionaries πρέπει να είναι αμετάβλητοι τύποι +# (immutable) αυτό γίνετια για να διασφαλίσουμε ότι τα κλειδιά μπορούν να +# μετατρέπονται σε σταθερές τιμές κατακερματισμού (hash values) για γρήγορη εύρεση. +# Μερικοί αμετάβλητοι τύποι είναι τα ints, floats, strings, tuples. +invalid_dict = {[1,2,3]: "123"} # => Προκαλεί TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Οι τιμές όμως μπορούν να έχουν οποιοδήποτε τύπο. + +# Βρίσκουμε τιμές με [] +filled_dict["one"] # => 1 + +# Μπορείς να πάρεις όλα τα κλειδιά με τη μέθοδο "keys()". +# Πρέπει να "τυλίξουμε" την κλήση με list() για να το μετατρέψουμε σε λίστα +# Θα μιλήσουμε για αυτά αργότερα. Σημ. - σε εκδόσεις Python < 3.7, η σειρά που +# εμφανίζονται τα κλειδιά δεν είναι εγγυημένη. Τα αποτελέσματά σας ίσως να μην +# είναι ακριβώς ίδια με τα παρακάτω. Στην έκδοση 3.7 πάντως, τα αντικείμενα του +# λεξικού διατηρούν τη σειρά με την οποία εισήχθησαν στο dictionary +list(filled_dict.keys()) # => ["three", "two", "one"] σε Python <3.7 +list(filled_dict.keys()) # => ["one", "two", "three"] σε Python 3.7+ + +# Παίρνουμε όλες τις τιμές ενός iterable με τη μέθοδο "values()". Και πάλι +# χρειάζεται να το περιτυλίξουμε σε list() +# Σημ. - όπως παραπάνω σχετικά με τη σειρά των keys +list(filled_dict.values()) # => [3, 2, 1] in Python <3.7 +list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+ + +# Έλεγχος της ύπαρξης κλειδιών σε ένα dictionary με το "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# Αν ψάξεις την τιμή ανύπαρκτου κλειδιού προκαλείται KeyError +filled_dict["four"] # KeyError + +# Χρησιμοποιούμε τη μέθοδο "get()" για να αποφύγουμε το KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# στο δεύτερο argument της get() μπορούμε να βάλουμε μία τιμή που πρέπει να +# επιστρέψει αν δεν υπάρχει το key που ψάχνουμε +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# το "setdefault()" εισάγει στο dictionary μόνο αν δεν υπάρχει το κλειδί +filled_dict.setdefault("five", 5) # filled_dict["five"] γίνεται 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] μένει 5 (υπαρκτό κλειδί) + +# Προσθήκη σε dictionary +filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} +filled_dict["four"] = 4 # β' τρόπος + +# Αφαίρεση κλειδιών από dictionary με del +del filled_dict["one"] # Αφαιρεί το κλειδί "one" από το filled_dict + +# Από την Python 3.5 μπορείς να χρησιμοποιήσεις και πρόσθετες επιλογές για unpacking +{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} +{'a': 1, **{'a': 2}} # => {'a': 2} + + + +# τα Sets -όπως όλοι περιμένουμε- αποθηκεύουν σύνολα +empty_set = set() +# Αρχικοποιούμε ένα set με μερικές τιμές. Ναι, μοιάζει λίγο με dictionary, Sorry. +some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} + +# Παρομοίως με τα κλειδιά του dictionary, τα στοιχεία ενός συνόλου πρέπει να είναι +# αμετάβλητα (immutable) +invalid_set = {[1], 1} # => Προκαλεί TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# Προσθέτουμε άλλο ένα στοιχείο στο σύνολο +filled_set = some_set +filled_set.add(5) # το filled_set είναι τώρα {1, 2, 3, 4, 5} +# Τα σύνολα δεν έχουν διπλοτυπα αντικείμενα +filled_set.add(5) # το σύνολο παραμένει ίδιο {1, 2, 3, 4, 5} + +# το & κάνει την τομή δύο συνόλων. +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# και το | την ένωση +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Η διαφορά συνόλων με το - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Το ^ επιστρέφει τη συμμετρική διαφορά +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Ελεγχος για το αν το δεξιά σύνολο είναι υπερσύνολο του δεξιού +{1, 2} >= {1, 2, 3} # => False + +# Ελεγχος για το αν το δεξιά σύνολο είναι υποσύνολο του δεξιού +{1, 2} <= {1, 2, 3} # => True + +# με το in κάνουμε έλεγχο ύπαρξης στοιχείο σε σετ +2 in filled_set # => True +10 in filled_set # => False + + + +#################################################### +## 3. Έλεγχος Ροής και Iterables +#################################################### + +# Φτιάχνουμε μία μεταβλητή +some_var = 5 + +# Εδώ έχουμε ένα if statement. Η στοίχιση είναι σημαντική στην Python! +# Η σύμβαση είναι να χρησιμοποιούμε 4 κενά, όχι tabs. +# Το παρακάτω τυπώνει "some_var is smaller than 10" +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # το (else if) -> elif μέρος είναι προαιρετικό. + print("some_var is smaller than 10.") +else: # και το else είναι προαιρετικό. + print("some_var is indeed 10.") + + +""" +τα for loops τρέχουν πάνω σε lists +το παρακάτω τυπώνει: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # You can use format() to interpolate formatted strings + print("{} is a mammal".format(animal)) + +""" +το "range(number)" επιστρέφει ένα iterable με αριθμούς +από το μηδέν μέχρι τον δωσμένο αριθμό number (κλειστό/ανοικτό διάστημα) +Το παρακάτω τυπώνει: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +το "range(lower, upper)" επιστρέφει ένα iterable με αριθμούς +από το lower εώς το upper (κλειστό/ανοικτό διάστημα) +το παρακάτω τυπώνει: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +το "range(lower, upper, step)" επιστρέφει ένα iterable με αριθμούς +από το lower μέχρι το upper, με βήμα step +αν δεν δώσουμε τιμή βήματος, το default βήμα είναι 1. +το παρακάτω τυπώνει: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) +""" + +τα While loops τρέχουν μέχρι μία συνθήκη να γίνει ψευδής. +το παρακάτω τυπώνει: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Shorthand for x = x + 1 + +# Χειριζόμαστε εξαιρέσεις με ένα try/except block +try: + # Χρησιμοποιούμε το "raise" για να πετάξουμε ένα error + raise IndexError("This is an index error") +except IndexError as e: + pass # το Pass δεν κάνει τίποτα. Συνήθως κάνουμε ανάκτηση. +except (TypeError, NameError): + pass # Μπορούμε να χειριζόμαστε πολλές εξαιρέσεις μαζί, αν χρειαστεί +else: # Προαιρετικό στο try/except block. Πρέπει να ακολουθεί όλα τα except blocks + print("All good!") # τρέχει μόνο αν ο κώδικας στο try δεν προκαλεί εξαιρέσεις +finally: # Εκτελείται ό,τι και να γίνει + print("We can clean up resources here") + +# Αντί για try/finally για να καθαρίσουμε τους πόρους, μπορούμε να χρησιμοποιούμε το +# with expression as target: + pass to cleanup resources you can use a with statement +with open("myfile.txt") as f: + for line in f: + print(line) + +# Η Python προσφέρει μία θεμελιώδη αφαίρεση (abstraction) που λέγεται Iterable. +# iterable είναι ένα αντικείμενο που μπορεί να χρησιμοποιηθεί ως ακολουθία. +# Το αντικείμενο που επιστρέφει η συνάρτηση range, είναι ένα iterable. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => dict_keys(['one', 'two', 'three']). +# Αυτό είναι ένα αντικείμενο που υλοποιεί την iterable διεπαφή μας. + +# μπορούμε να τρέχουμε loops πάνω του. +for i in our_iterable: + print(i) # Prints one, two, three + +# Ωστόσο δεν μπορούμε να προσπελάσουμε τα στοιχεία του με index. +our_iterable[1] # προκαλεί a TypeError + +# Ένα iterable είναι ένα αντικείμενο που ξέρει πώς να δημιουργήσει έναν iterator. +our_iterator = iter(our_iterable) + +# Ο iterator μας είναι ένα αντικείμενο που μπορεί να θυμάται την κατάσταση όπως το διατρέχουμε. +# Παίρνουμε το επόμενο αντικείμενο με το "next()" +next(our_iterator) # => "one" + +# Διατηρεί την κατάσταση καθώς επαναλαμβάνουμε. +next(our_iterator) # => "two" +next(our_iterator) # => "three" + +# Όταν ο iterator έχει επιστρέψει όλα τα δεδομένα του, προκαλεί ένα μια εξαίρεση StopIteration. +next(our_iterator) # προκαλεί StopIteration + +# Μπορείς να πάρεις όλα τα αντικείμενα ενός iteratior καλώντας list() πάνω του. +list(filled_dict.keys()) # => Επιστρέφει ["one", "two", "three"] + + +#################################################### +## 4. Συναρτήσεις +#################################################### + +# Χρησιμποιούμε το "def" για να ορίσουμε νέες συναρτήσεις +def add(x, y): + print("x is {} and y is {}".format(x, y)) + return x + y # επιστρέφει τιμές με την εντολή return + +# Καλούμε συναρτήσεις με παραμέτρους +add(5, 6) # => τυπώνει "x is 5 and y is 6" και επιστρέφει 11 + +# Ένας άλλος τρόπος να καλέσεις συνάρτησει είναι με keyword arguments (ορίσματα λέξεις-κλειδιά) +add(y=6, x=5) # τα Keyword arguments μπορούν να δωθούν με οποιαδήποτε σειρά. + +# Μπορείς να ορίσεις συναρτήσεις που δέχονται μεταβλητό πλήθος ορισμάτων +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# Μπορούμε να ορίσουμε και συναρτήσεις που δέχονται μεταβλητό πλήθος keyword arguments +def keyword_args(**kwargs): + return kwargs + +# Για να δούμε τι γίνεται αν την καλέσουμε +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# Μπορείς να κάνεις και τα δύο ταυτόχρονα αν θες +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) τυπώνει: + (1, 2) + {"a": 3, "b": 4} +""" + +# Όταν καλείς συναρτήσεις μπορείς να κάνεις και το αντίστροφο από args/kwargs! +# Χρησιμοποίησε το * για να επεκτείνεις tuples και χρησιμοποίησε το ** για να επεκτείλεις kwargs +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # ισοδύναμο με all_the_args(1, 2, 3, 4) +all_the_args(**kwargs) # ισοδύναμο με all_the_args(a=3, b=4) +all_the_args(*args, **kwargs) # ισοδύναμο με all_the_args(1, 2, 3, 4, a=3, b=4) + +# Επιστρέφουμε πλειάδα τιμών (με tuple assignments) +def swap(x, y): + return y, x # Επιστρέφει πολλές τιμές ως tuple χωρίς την παρένθεση + # (Σημ.: οι παρενθέσεις έχουν παραλειφθεί αλλά μπορούν να γραφούν) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Ξανά, οι παρενθέσεις έχουν παραληφθεί αλλά μπορούν να γραφούν + +# Εμβέλεια συναρτήσεων +x = 5 + +def set_x(num): + # Η τοπική μεταβλητή x δεν είναι η ίδια με την global μεταβλητή x + x = num # => 43 + print(x) # => 43 + +def set_global_x(num): + global x + print(x) # => 5 + x = num # η global μεταβλητή x τώρα είναι 6 + print(x) # => 6 + +set_x(43) +set_global_x(6) + + +# Η Python έχει πρώτης τάξης συναρτήσεις +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Αλλά έχει και anonymous συναρτήσεις. +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# Υπάρχουν ενσωματωμένες συναρτήσεις μεγαλύτερης τάξης +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] + +list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] + +# Μπορούμε να χρησιμοποιήσουμε list comprehensions για ωραία maps και filters +# το List comprehension αποθηκεύει την έξοδο ως μία λίστα που μπορεί και η ίδια +# να είναι μια εμφωλευμένη λίστα +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# Μπορείς επίσης να κατασκευάσεις set και dict comprehensions. +{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +## 5. Modules +#################################################### + +# Μπορείς να κάνεις import modules +import math +print(math.sqrt(16)) # => 4.0 + +# Μπορείς να πάρεις συγκεκριμένες συναρτήσεις από ένα module +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Μπορείς να κάνεις import όλες τις συναρτήσεις από ένα module. +# Προσοχή: δεν προτείνεται +from math import * + +# Μπορείς να δημιουργείς συντομογραφίες για τα ονόματα των modules +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Τα Python modules είναι απλά αρχεία Python. Μπορείς να δημιουργήσεις τα δικά σου +# και να τα κάνεις import το όνομα του module είναι ίδιο με το όνομα του αρχείου + +# μπορείς να βρεις ποιες συναρτήσεις και γνωρίσματα ορίζονται στο module +import math +dir(math) + +# Αν έχεις ένα Python script με όνομα math.py στον ίδιο φάκελο με το τρέχον script +# το αρχείο math.py θα φορτωθεί και όχι το built-in Python module +# Αυτό συμβαίνει επειδή τα τοπικά αρχεία έχουν προτεραιότητα έναντι των built-in +# βιβλιοθηκών της Python + + +#################################################### +## 6. Κλάσεις - Classes +#################################################### + +# χρησιμοποιούμε το "class" statement για να δημιουργήσουμε μια κλάση +class Human: + + # Ένα γνώρισμα της κλάσης. Είναι κοινό για όλα τα στιγμιότυπα αυτής. + species = "H. sapiens" + + # Βασικός initializer, καλείται όταν δημιουργείται στιγμιότυπο της κλάσης. + # Σημ. οι διπλές κάτω παύλες πριν και μετά υποδηλώνουν αντικείμενα + # ή γνωρίσματα που χρησιμοποιούνται από την Python αλλά ζουν σε ελεγχόμενα από + # το χρήση namespaces. + # Μέθοδοι (ή αντικείμενα ή γνωρίσματα) σαν τα __init__, __str__, __repr__ κλπ + # είναι ειδικές μέθοδοι (λέγονται και dunder (double underscore) μέθοδοι) + # Δεν πρέπει να δηλώνεις δικές σου τέτοιες συναρτήσεις + def __init__(self, name): + # Εκχώρησε στο attribute name του object το όρισμα + self.name = name + + # Αρχικοποίησε την ιδιότητα + self._age = 0 + + # Μία μέθοδος στιγμιότυπου (instance method). Όλες οι μέθοδοι παίρνουν το + # "self" ως πρώτο όρισμα + def say(self, msg): + print("{name}: {message}".format(name=self.name, message=msg)) + + # Ακόμα μία instance method + def sing(self): + return 'yo... yo... microphone check... one two... one two...' + + # Μία μέθοδος κλάσεις είναι κοινή ανάμεσα σε όλα τα instances. + # Καλούνται με calling class ώς πρώτο όρισμα + @classmethod + def get_species(cls): + return cls.species + + # Μία στατική μέθοδος καλείται χωρίς αναφορά σε κλάση ή στιγμιότυπο + @staticmethod + def grunt(): + return "*grunt*" + + # Ένα property είναι ακριβώς σαν ένα getter. + # Μετατρέπει τη μέθοδο age σε ένα γνώρισμα (attribute) μόνο-για-ανάγνωση + # με το ίδιο όνομα. + # Δεν χρειάζεται να γράφουμε τετριμένους getters και setters στην Python όμως. + @property + def age(self): + return self._age + + # Αυτό επιτρέπει στο property να γίνει set + @age.setter + def age(self, age): + self._age = age + + # Αυτό επιτρέπει σε ένα property να διαγραφεί + @age.deleter + def age(self): + del self._age + + +# Όταν ο διερμηνέας της Python διαβάζει αρχείο πηγαίου κώδικα τον εκτελεί όλο. +# Αυτός ο έλεγχος του __name__ σιγουρεύει ότι αυτό το block κώδικα τρέχει μόνο +# αυτό το module είναι το κύριο πρόγραμμα (και όχι imported) +if __name__ == '__main__': + # Δημιουργούμε στιγμιότυπο κλάσης + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # τα i και j είναι στιγμιότυπα του τύπου Human + + # Καλούμε τη μέθοδο της κλάσης + i.say(i.get_species()) # "Ian: H. sapiens" + # Αλλάζουμε το κοινό attribute των αντικειμένων της κλάσης + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # Καλούμε τη static μέθοδο + print(Human.grunt()) # => "*grunt*" + + # Δεν μπορούμε να καλέσουμε τη στατική μέθοδο με ένα στιγμιότυπο + # επειδή το i.grunt() θα βάλει αυτόματα το self (δηλαδή το αντικείμενο i) ως όρισμα + print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given + + # Ενημερώνουμε το property για αυτό το στγμιότυπο + i.age = 42 + # Παίρνουμε το property + i.say(i.age) # => "Ian: 42" + j.say(j.age) # => "Joel: 0" + # Διαγράφουμε το property + del i.age + # i.age # => αυτό θα προκαλούσε AttributeError + + +#################################################### +## 6.1 Κληρονομικότητα - Inheritance +#################################################### + +# Η κληρονομικότητα επιτρέπει σε νέες κλάσεις-παιδιά να οριστούν και να υιοθετήσουν +# μεθόδους και μεταβλητές από την κλάση-γονέα. + +# Χρησιμοποιώντας την κλάση Human που ορίστηκε πριν ως τη βασική κλάση (ή κλάση-γονέα) +# μπορούμε να ορίσουμε τις κλάσεις-παιδιά Superhero, που κληρονομεί μεταβλητές όπως +# "species", "name", και "age", καθώς και μεθόδους όπως "sing" και "grunt" +# από την κλάση Human, αλλά επίσης έχει τις δικές του ξεχωριστές ιδιότητες + +# Για να εκμεταλλευτείς το modularization κατά αρχείο, μπορείς να βάλεις την παραπάνω κλάση +# σε δικό της αρχείο, ας πούμε human.py + +# Για να κάνουμε import συναρτήσεις από άλλα αρχεία χρησιμοποιούμε το παρακάτω format +# from "filename-without-extension" import "function-or-class" + +from human import Human + + +# Προσδιόρισε την/τις parent class(es) ως παραμέτρους της κλάσης που ορίζεται +class Superhero(Human): + + # Αν η κλάση-παιδί πρέπει να κληρονομήσει όλους τους οεισμούς της κλάσης-γονέα + # χωρίς καμία αλλαγή, μπορείς απλά να γράψεις pass (και τίποτα άλλο) + # αλλά σε αυτή την περίπτωση είναι σχολιασμένο για να επιτρέψει τη δημιουργία + # ξεχωριστής κλάσης-παιδιού: + # pass + + # Η κλάση παιδί μπορεί να υπερφορτώσει (override) τα attributes της κλάσης από την οποία κληρονομεί + species = 'Superhuman' + + # Τα παιδιά αυτόματα, κληρονομούν τον constructo της κλάσης-γονέα + # συμπεριλαμβανομένων των ορισμάτων, αλλά μπορείς και να ορίσεις πρόσθετα ορίσματα + # ή ορισμούς και να κάνεις override τις μεθόδους, όπως τον constructor. + # Αυτός ο constructor κληρονομεί το όρισμα "name" από την κλάση Human και + # προσθέτει τα ορίσματα "superpower" και "movie": + def __init__(self, name, movie=False, + superpowers=["super strength", "bulletproofing"]): + + # πρόσθήκη επιπλέον attributes της κλάσης: + self.fictional = True + self.movie = movie + # έχετε το νου σας τις μεταβλητές (mutable) default τιμές, καθώς είναι κοινές + self.superpowers = superpowers + + # Η συνάρτηση "super" επιτρέπει την πρόσβαση στις μεθόδους της κλάσης-γονέα + # που είναι υπερφορτωμένες από το παιδί. Σε αυτή την περίπτωση τη μέθοδο __init__ + # Το παρακάτω καλεί τον constructor της κλάσης-γονέα: + super().__init__(name) + + # υπερφόρτωση της μεθόδου sing + def sing(self): + return 'Dun, dun, DUN!' + + # προσθήκη νέας μεθόδου που εφαρμόζεται σε στιγμιότυπα + def boast(self): + for power in self.superpowers: + print("I wield the power of {pow}!".format(pow=power)) + + +if __name__ == '__main__': + sup = Superhero(name="Tick") + + # Έλεγχος για το αν το στιγμιότυπο sup ανήκει στην κλάση Human + if isinstance(sup, Human): + print('I am human') + if type(sup) is Superhero: + print('I am a superhero') +# TODO: + # Παίρνουμε το Method Resolution search Order που χρησιμοποιούν οι getattr() και super() + # Αυτό το attribute είναι δυναμικό και μπορεί να ανανεωθεί + print(Superhero.__mro__) # => (, + # => , ) + + # Καλούμε μέθοδο της κλάσης-γονέα, αλλά χρησιμοποιεί το δικό της attribute + print(sup.get_species()) # => Superhuman + + # Καλεί την υπερφορτωμένη μέθοδο + print(sup.sing()) # => Dun, dun, DUN! + + # Καλεί μέθοδο από την κλάση Human + sup.say('Spoon') # => Tick: Spoon + + # Καλεί μέθοδο που υπάρχει μόνο στην κλάση Superhero + sup.boast() # => I wield the power of super strength! + # => I wield the power of bulletproofing! + + # Κληρονομημένο class attribute + sup.age = 31 + print(sup.age) # => 31 + + # Attribute που υπάρχει μόνο στην μέσα στην κλάση Superhero + print('Am I Oscar eligible? ' + str(sup.movie)) + +#################################################### +## 6.2 Πολλαπλή Κληρονομικότητα - Multiple Inheritance +#################################################### + +# Ένας ακόμη ορισμός κλάσης +# bat.py +class Bat: + + species = 'Baty' + + def __init__(self, can_fly=True): + self.fly = can_fly + + # Αυτή η κλάση έχει επίσης μία μέθοδο say + def say(self, msg): + msg = '... ... ...' + return msg + + # Και τη δική της μέθοδο sonar + def sonar(self): + return '))) ... (((' + +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) + + +# Και ορίζουμε μία ακόμα κλάση που κληρονομεί από τις κλάσεις Superhero και Bat +# superhero.py +from superhero import Superhero +from bat import Bat + +# Ας πούμε αυτή την κλάση Batman +class Batman(Superhero, Bat): + + def __init__(self, *args, **kwargs): + # Τυπικά γα να κληρονομήουμε attributes πρέπει να καλέσουμε τη super: + # super(Batman, self).__init__(*args, **kwargs) + # Ωστόσο έχουμε να κάνουμε με πολλαπλή κληρονομικότητα εδώ, και το super() + # δουλεύει μόνο με την αμέσως ανώτερη κλάση στην ιεραρχία. + # Οπότε, καλούμε ρητά την __init__ για όλους τους πρόγονους + # Η χρήση των *args και **kwargs επιτρέπει έναν καθαρό τρόπο για να περνάμε ορίσματα + # με κάθε κλάση-γονέα να "βγάζει μία φλούδα από το κρεμμύδι". + Superhero.__init__(self, 'anonymous', movie=True, + superpowers=['Wealthy'], *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # υπερφορτώνουμε την τιμή του γνωρίσματος name + self.name = 'Sad Affleck' + + def sing(self): + return 'nan nan nan nan nan batman!' + + +if __name__ == '__main__': + sup = Batman() + + # + # Λάβε το Method Resolution search Order που χρησιμοποιείται από το getattr() και το super(). + # Αυτό το attribute είναι δυναμικό και μπορεί να ενημερωθεί + print(Batman.__mro__) # => (, + # => , + # => , + # => , ) + + # Καλεί την μέθοδο της κλάσης-πατέρα αλλά χρησιμοποιεί το attribute της δικής του κλάσης + print(sup.get_species()) # => Superhuman + + # Καλεί την υπερφορτωμένη μέθοδο + print(sup.sing()) # => nan nan nan nan nan batman! + + # Καλεί μέθοδο από την κλάση Human, επειδή μετράει η σειρά της κληρονομιάς + sup.say('I agree') # => Sad Affleck: I agree + + # Καλεί μέθοδο που ανήκει μόνο στον δεύτερο πρόγονο + print(sup.sonar()) # => ))) ... ((( + + # Attribute της κληρονομημένης κλάσης + sup.age = 100 + print(sup.age) # => 100 + + # Κληρονομούμενο attribute από τον δεύτερο πρόγονο του οποίου η default τιμή + # έχει υπερφορτωθεί. + print('Can I fly? ' + str(sup.fly)) # => Can I fly? False + + + +#################################################### +## 7. Προχωρημένα +#################################################### + +# Με τους Generators μπορείς να γράψεις τεμπέλικο κώδικα. +def double_numbers(iterable): + for i in iterable: + yield i + i +# Οι Generators είναι αποδοτικοί από άποψη μνήμης επειδή φορτώνουν μόνο τα δεδομένα +# που είναι αναγκαία για να επεξεργαστούμε την επόμενη τιμή του iterable. +# Αυτό μας επιτρέπει να κάνουμε πράξεις σε τιμές που υπό άλλες συνθήκες θα ήταν +# απαγορευτικά μεγάλες. +for i in double_numbers(range(1, 900000000)): # το `range` είναι ένας generator. + print(i) + if i >= 30: + break + +# Όπως μπορείς να δημιουργήσεις list comprehension, έτσι μπορείς να δημιουργήσεις και +# generator comprehensions +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # τυπώνει -1 -2 -3 -4 -5 στο console/terminal + +# Μπορείς επίσης να μετατρέψεις ένα generator comprehension απευθείας σε λίστα. +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + + +# Decorators +# σε αυτό το παράδειγμα το `beg` τυλίγει το `say`. Αν το say_please είναι True τότε +# θα αλλάξει το μήνυμα που επιστρέφεται. +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # Can you buy me a beer? +print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( +``` + +## Έτοιμοι για περισσότερα? + +### Δωρεάν Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) +* [Dive Into Python 3](http://www.diveintopython3.net/index.html) +* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/el-gr/python3-gr.html.markdown b/el-gr/python3-gr.html.markdown deleted file mode 100644 index 445b85ba..00000000 --- a/el-gr/python3-gr.html.markdown +++ /dev/null @@ -1,1031 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] - - ["evuez", "http://github.com/evuez"] - - ["Rommel Martinez", "https://ebzzry.io"] - - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] -filename: learnpython3-gr.py -lang: el-gr ---- - -Η Python δημιουργήθηκε από τον Guido van Rossum στις αρχές των 90s. Πλέον είναι μία από τις πιο -δημοφιλείς γλώσσες. Ερωτευεται κανείς την python για τη συντακτική της απλότητα. -Βασικά είναι εκτελέσιμος ψευδοκώδικας. - -Το Feedback είναι πάντα δεκτό! Μπορείτε να με βρείτε στο [@haritonaras](http://twitter.com/haritonaras) -ή τον αρχικό συγγραφέα στο [@louiedinh](http://twitter.com/louiedinh) ή στο -louiedinh [at] [google's email service] - -Σημείωση: Το παρόν άρθρο ασχολείται μόνο με την Python 3. Δείτε [εδώ](http://learnxinyminutes.com/docs/python/) αν θέλετε να μάθετε την παλιά Python 2.7 - -```python - -# Τα σχόλια μίας γραμμής ξεκινούν με # - -""" Τα σχόλια πολλαπλών γραμμών μπορούν - να γραφούν με τρία ", και συχνά χρησιμοποιούνται - ως documentation. -""" - -#################################################### -## 1. Primitive (πρωταρχικοί) Τύποι Δεδομένων και Τελεστές -#################################################### - -# Αφού έχει αριθμούς -3 # => 3 - -# Λογικά θα έχει και Μαθηματικά... -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7.0 - -# Η διαίρεση ακεραίων κάνει στρογγυλοποίηση προς τα κάτω για θετικούς και αρνητικούς αριθμούς -5 // 3 # => 1 --5 // 3 # => -2 -5.0 // 3.0 # => 1.0 # works on floats too --5.0 // 3.0 # => -2.0 - -# Το αποτέλεσμα της διαίρεσης είναι πάντα float -10.0 / 3 # => 3.3333333333333335 - -# Modulo τελεστής -7 % 3 # => 1 - -# Ύψωση σε δύναμη (x**y, x στην y-οστή δύναμη) -2**3 # => 8 - -# Ελέγχουμε την προτεραιότητα πράξεων με παρενθέσεις -(1 + 3) * 2 # => 8 - -# Οι Boolean τιμές είναι primitives (Σημ.: τα κεφαλαία) -True -False - -# άρνηση με το not -not True # => False -not False # => True - -# Boolean τελεστές -# Σημ. ότι τα "and" και "or" είναι case-sensitive -True and False # => False -False or True # => True - -# Τα True και False είναι 1 και 0 αλλά με διαφορετικά keywords -True + True # => 2 -True * 8 # => 8 -False - 5 # => -5 - -# Μπορούμε να δούμε τις αριθμητικές τιμές των True και False μέσω των τελεστών σύγκρισης -0 == False # => True -1 == True # => True -2 == True # => False --5 != False # => True - -# Χρησιμοποιώντας τελεστές boolean σε ακεραίους, οι ακέραιοι γίνονται cast σε -# boolean ώστε να γίνει η αποτίμηση της έκφρασης. -# Το αποτέλεσμα όμως είναι non-cast, δηλαδή ίδιου τύπου με τα αρχικά ορίσματα -# Μην μπερδεύετε τις bool(ints) και bitwise and/or (&,|) -bool(0) # => False -bool(4) # => True -bool(-6) # => True -0 and 2 # => 0 --5 or 0 # => -5 - -# Ισότητα == -1 == 1 # => True -2 == 1 # => False - -# Διάφορο != -1 != 1 # => False -2 != 1 # => True - -# Περισσότερες συγκρίσεις -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# Κοιτάζουμε αν μία τιμή ανήκει σε ένα εύρος -1 < 2 and 2 < 3 # => True -2 < 3 and 3 < 2 # => False -# Το Chaining (αλυσίδωση? :P) κάνει το παραπάνω πιο όμορφα -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# (is vs. ==) το is ελέγχει αν δύο μεταβλητές αναφέρονται στο ίδιο αντικείμενο, -# αλλά το == ελέγχει αν τα αντικείμενα στα οποία αναφέρονται οι μεταβλητές έχουν τις ίδιες τιμές -a = [1, 2, 3, 4] # το a δείχνει σε μία νέα λίστα, [1,2,3,4] -b = a # το b δείχνει στο αντικείμενο που δείχνει το a -b is a # => True, a και b αναφέρονται στο ίδιο αντικείμενο -b == a # => True, τα αντικείμενα των a κι b είναι ίσα -b = [1, 2, 3, 4] # Το b δείχνει σε μία νέα λίστα, [1, 2, 3, 4] -b is a # => False, a και b δεν αναφέρονται στο ίδιο αντικείμενο -b == a # => True, τα αντικείμενα των a και b είναι ίσα - -# Τα Strings (συμβολοσειρές) δημιουργούνται με " ή ' -"This is a string." -'This is also a string.' - -# Μπορούμε και να προσθέτουμε Strings, αλλά προσπαθήστε να μην το κάνετε -"Hello " + "world!" # => "Hello world!" -# Τα String literals (αλλά όχι οι μεταβλητές) μπορούν να συντμιθούν και χωρίς το '+' -"Hello " "world!" # => "Hello world!" - -# Μπορούμε να φερθούμε σε string σαν να είναι λίστα από χαρακτήρες -"This is a string"[0] # => 'T' - -# Μπορούμε να βρούμε το μήκος ενός string -len("This is a string") # => 16 - -# Το .format μπορεί να χρησιμοποιηθεί για να μορφοποιήσουμε strings, όπως εδώ: -"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" - -# Μπορείς να επαναλάβεις τα ορίσματα του formatting για να γλιτώσεις λίγο χρονο -"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" - -# Μπορείς να χρησιμοποιήσεις keywords αν βαριέσαι το μέτρημα. -"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" - -# Αν ο κώδικας Python 3 που γράφεις πρόκειται να τρέξει και με python 2.5 ή παλιότερη -# μπορείς επίσης να χρησιμοποιήσεις το παλιό τρόπο για formatting: -"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" - -# Μπορείς επίσης να μορφοποιήσεις χρησιμοποιώντας τα f-strings / formatted string literals (σε Python 3.6+) -name = "Reiko" -f"She said her name is {name}." # => "She said her name is Reiko" -# Μπορείς βασικά να βάλεις οποιαδήποτε έκφραση Python στα άγκιστρα και θα εμφανιστεί στο string. -f"{name} is {len(name)} characters long." - - -# το None είναι ένα αντικείμενο (object) -None # => None - -# Μη χρησιμοποιείτε το σύμβολο ισότητας "==" για να συγκρίνετε αντικείμενα με το None -# Χρησιμοποιείτε το "is". Αυτό ελέγχει για ισότητα της ταυτότητας του αντικειμένου. -"etc" is None # => False -None is None # => True - -# Τα None, 0, και τα κενά strings/lists/dicts/tuples αποτιμούνται στην τιμή False -# All other values are True -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False -bool(()) # => False - -#################################################### -## 2. Μεταβλητές (variables) και Συλλογές (collections) -#################################################### - -# Η Python έχει μία συνάρτηση print() -print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! - -# By default, η συνάρτηση print() τυπώνει και ένα χαρακτήρα αλλαγής γραμμμής στο τέλος -# Χρησιμοποιείτε το προαιρετικό όρισμο end για να τυπώνει οτιδήποτε άλλο -print("Hello, World", end="!") # => Hello, World! - -# Απλός τρόπος για να πάρουμε δεδομένα εισόδου από το console -input_string_var = input("Enter some data: ") # επιστρέφει τα δεδομένα ως string -# Σημ.: Στις προηγούμενες εκδόσεις της Python, η μέθοδος input() ονομαζόταν raw_input() - -# Δεν υπάρχουν δηλώσεις, μόνο αναθέσεις τιμών. -# Η σύμβαση είναι να χρησιμοποιούμε μικρά γράμματα με κάτω παύλες -some_var = 5 -some_var # => 5 - -# Η πρόσβαση σε μεταβλητή που δεν έχει λάβει τιμή είναι εξαίρεση -# Δες τον Έλεγχο Ροής για να μάθεις περισσότερα για το χειρισμό εξαιρέσεων -some_unknown_var # Προκαλέι ένα NameError - -# Η παρακάτω έκφραση μπορεί να χρησιμποιηθεί ισοδύναμα με τον τελεστή '?' της C -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# Οι λίστες κρατούν ακολουθίς -li = [] -# Μπορείς να αρχίσεις με μία προ-γεμισμένη λίστα -other_li = [4, 5, 6] - -# Και να βάλεις πράγματα στο τέλος με την μέθοδο append -li.append(1) # η li τώρα είναι [1] -li.append(2) # η li τώρα είναι [1, 2] -li.append(4) # η li τώρα είναι [1, 2, 4] -li.append(3) # η li τώρα είναι [1, 2, 4, 3] -# Αφαιρούμε από το τέλος με την μέθοδο pop -li.pop() # => 3 και η li γίνεται [1, 2, 4] -# Ας βάλουμε το 3 πίσω στη θέση του -li.append(3) # η li γίνεται πάλι [1, 2, 4, 3]. - -# Προσπελαύνουμε τις λίστες όπως τους πίνακες σε άλλες γλώσσες -li[0] # => 1 -# Το τελευταίο στοιχείο... -li[-1] # => 3 - -# Όταν βγαίνουμε εκτός ορίων της λίστας προκαλείται IndexError -li[4] # προκαλεί IndexError - -# Μπορείς να δεις ranges μιας λίστας με το slice syntax ':' -# Ο δείκτης εκίνησης περιλαμβάνεται στο διάστημα, ο δείκτης τερματισμού όχι -# (είναι ανοικτό/κλειστό διάστημα για τους φίλους των μαθηματικών) -li[1:3] # => [2, 4] -# Αγνόησε την αρχή και επίστρεψε τη λίστα -li[2:] # => [4, 3] -# Αγνόησε το τέλος και επίστρεψε τη λίστα -li[:3] # => [1, 2, 4] -# Διάλεξε κάθε δεύτερο στοιχείο -li[::2] # =>[1, 4] -# Επίστρεψε ένα reversed αντίγραφο της λίστας -li[::-1] # => [3, 4, 2, 1] -# Χρησιμοποιείστε οποιαδήποτε συνδυασμό αυτών για να φτιάξετε πιο προχωρημένα slices -# li[start:end:step] - -# Φτιάξε ένα αντίγραφο της λίστας χρησιμοποιώντας slices -li2 = li[:] # => li2 = [1, 2, 4, 3] αλλά το (li2 is li) επιστρέφει False - -# Αφαίρεσε οποιοδήποτε στοιχείο από λίστα με την εντολή "del" -del li[2] # η li γίνεται [1, 2, 3] - -# Αφαιρούμε το πρώτο στιγμυότυπο μιας τιμής -li.remove(2) # η li γίνεται [1, 3] -li.remove(2) # Προκαλεί ένα ValueError καθώς το 2 δεν βρίσκεται στη λίστα. - -# Εισαγωγή ενός στοιχείου σε συγκεκριμένη θέση -li.insert(1, 2) # η li γίνεται πάλι [1, 2, 3] - -# Βρες το index (δείκτη) του πρώτου στοιχείου με τιμή ίση με το όρισμα -li.index(2) # => 1 -li.index(4) # Προκαλεί ValueError καθώς το 4 δεν βρίσκεται στη λίστα - -# Μπορείς να προσθέτεις λίστες -# Σημ.: οι τιμές των li, other_li δεν αλλάζουν. -li + other_li # => [1, 2, 3, 4, 5, 6] - -# Σύντμιση λιστών με τη μέθοδο "extend()" -li.extend(other_li) # Τώρα η li είναι [1, 2, 3, 4, 5, 6] - -# Ελεγχος της ύπαρξης στοιχείου σε λίστα με το "in" -1 in li # => True - -# Εξατάζουμε το μήκος με "len()" -len(li) # => 6 - - -# Τα Tuples είναι σαν τις λίστες αλλά είναι αμετάβλητα (immutable). -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # Προκαλεί TypeError - -# Σημειώστε ότι ένα tuple μήκους 1 πρέπει να έχει ένα κόμμα μετά το τελευταίο στοιχείο -# αλλά τα tuples άλλων μηκών, ακόμα και μηδενικού μήκους, δεν χρειάζονται κόμμα. -type((1)) # => -type((1,)) # => -type(()) # => - -# Μπορείς να εφαρμόσεις τις περισσότερες μεθόδους των λιστών και στα tuples -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# Μπορείς να κάνεις unpack/"ξεπακετάρεις" tuples σε μεταβλητές -a, b, c = (1, 2, 3) # a == 1, b == 2 και c == 3 -# Μπορείς επίσης να επεκτείνεις το unpacking -a, *b, c = (1, 2, 3, 4) # a == 1, b == [2, 3] και c == 4 -# Τα Tuples δημιουργούνται by deafult αν δεν βάλεις παρενθέσεις -d, e, f = 4, 5, 6 # το tuple 4, 5, 6 "ξεπακετάρεται" στις μεταβλητές d, e και f -# αντίστοιχα έτσι ώστε να γίνεται d = 4, e = 5 and f = 6 -# Δείτε πόσο εύκολα μπορούμε να εναλλάσουμε δύο τιμές -e, d = d, e # το d παίρνει την τιμή 5 και το e παίρνει την τιμή 4 - - -# Τα λεξικά (Dictionaries) αποθηκεύουν απεικονίσεις από κλειδιά σε τιμές -empty_dict = {} -# Εδώ έχουμε ένα προ-γεμισμένο dictionary -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Σημ. ότι τα κλειδιά για τα dictionaries πρέπει να είναι αμετάβλητοι τύποι -# (immutable) αυτό γίνετια για να διασφαλίσουμε ότι τα κλειδιά μπορούν να -# μετατρέπονται σε σταθερές τιμές κατακερματισμού (hash values) για γρήγορη εύρεση. -# Μερικοί αμετάβλητοι τύποι είναι τα ints, floats, strings, tuples. -invalid_dict = {[1,2,3]: "123"} # => Προκαλεί TypeError: unhashable type: 'list' -valid_dict = {(1,2,3):[1,2,3]} # Οι τιμές όμως μπορούν να έχουν οποιοδήποτε τύπο. - -# Βρίσκουμε τιμές με [] -filled_dict["one"] # => 1 - -# Μπορείς να πάρεις όλα τα κλειδιά με τη μέθοδο "keys()". -# Πρέπει να "τυλίξουμε" την κλήση με list() για να το μετατρέψουμε σε λίστα -# Θα μιλήσουμε για αυτά αργότερα. Σημ. - σε εκδόσεις Python < 3.7, η σειρά που -# εμφανίζονται τα κλειδιά δεν είναι εγγυημένη. Τα αποτελέσματά σας ίσως να μην -# είναι ακριβώς ίδια με τα παρακάτω. Στην έκδοση 3.7 πάντως, τα αντικείμενα του -# λεξικού διατηρούν τη σειρά με την οποία εισήχθησαν στο dictionary -list(filled_dict.keys()) # => ["three", "two", "one"] σε Python <3.7 -list(filled_dict.keys()) # => ["one", "two", "three"] σε Python 3.7+ - -# Παίρνουμε όλες τις τιμές ενός iterable με τη μέθοδο "values()". Και πάλι -# χρειάζεται να το περιτυλίξουμε σε list() -# Σημ. - όπως παραπάνω σχετικά με τη σειρά των keys -list(filled_dict.values()) # => [3, 2, 1] in Python <3.7 -list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+ - -# Έλεγχος της ύπαρξης κλειδιών σε ένα dictionary με το "in" -"one" in filled_dict # => True -1 in filled_dict # => False - -# Αν ψάξεις την τιμή ανύπαρκτου κλειδιού προκαλείται KeyError -filled_dict["four"] # KeyError - -# Χρησιμοποιούμε τη μέθοδο "get()" για να αποφύγουμε το KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# στο δεύτερο argument της get() μπορούμε να βάλουμε μία τιμή που πρέπει να -# επιστρέψει αν δεν υπάρχει το key που ψάχνουμε -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 - -# το "setdefault()" εισάγει στο dictionary μόνο αν δεν υπάρχει το κλειδί -filled_dict.setdefault("five", 5) # filled_dict["five"] γίνεται 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] μένει 5 (υπαρκτό κλειδί) - -# Προσθήκη σε dictionary -filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} -filled_dict["four"] = 4 # β' τρόπος - -# Αφαίρεση κλειδιών από dictionary με del -del filled_dict["one"] # Αφαιρεί το κλειδί "one" από το filled_dict - -# Από την Python 3.5 μπορείς να χρησιμοποιήσεις και πρόσθετες επιλογές για unpacking -{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} -{'a': 1, **{'a': 2}} # => {'a': 2} - - - -# τα Sets -όπως όλοι περιμένουμε- αποθηκεύουν σύνολα -empty_set = set() -# Αρχικοποιούμε ένα set με μερικές τιμές. Ναι, μοιάζει λίγο με dictionary, Sorry. -some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} - -# Παρομοίως με τα κλειδιά του dictionary, τα στοιχεία ενός συνόλου πρέπει να είναι -# αμετάβλητα (immutable) -invalid_set = {[1], 1} # => Προκαλεί TypeError: unhashable type: 'list' -valid_set = {(1,), 1} - -# Προσθέτουμε άλλο ένα στοιχείο στο σύνολο -filled_set = some_set -filled_set.add(5) # το filled_set είναι τώρα {1, 2, 3, 4, 5} -# Τα σύνολα δεν έχουν διπλοτυπα αντικείμενα -filled_set.add(5) # το σύνολο παραμένει ίδιο {1, 2, 3, 4, 5} - -# το & κάνει την τομή δύο συνόλων. -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# και το | την ένωση -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# Η διαφορά συνόλων με το - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Το ^ επιστρέφει τη συμμετρική διαφορά -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# Ελεγχος για το αν το δεξιά σύνολο είναι υπερσύνολο του δεξιού -{1, 2} >= {1, 2, 3} # => False - -# Ελεγχος για το αν το δεξιά σύνολο είναι υποσύνολο του δεξιού -{1, 2} <= {1, 2, 3} # => True - -# με το in κάνουμε έλεγχο ύπαρξης στοιχείο σε σετ -2 in filled_set # => True -10 in filled_set # => False - - - -#################################################### -## 3. Έλεγχος Ροής και Iterables -#################################################### - -# Φτιάχνουμε μία μεταβλητή -some_var = 5 - -# Εδώ έχουμε ένα if statement. Η στοίχιση είναι σημαντική στην Python! -# Η σύμβαση είναι να χρησιμοποιούμε 4 κενά, όχι tabs. -# Το παρακάτω τυπώνει "some_var is smaller than 10" -if some_var > 10: - print("some_var is totally bigger than 10.") -elif some_var < 10: # το (else if) -> elif μέρος είναι προαιρετικό. - print("some_var is smaller than 10.") -else: # και το else είναι προαιρετικό. - print("some_var is indeed 10.") - - -""" -τα for loops τρέχουν πάνω σε lists -το παρακάτω τυπώνει: - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - # You can use format() to interpolate formatted strings - print("{} is a mammal".format(animal)) - -""" -το "range(number)" επιστρέφει ένα iterable με αριθμούς -από το μηδέν μέχρι τον δωσμένο αριθμό number (κλειστό/ανοικτό διάστημα) -Το παρακάτω τυπώνει: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -το "range(lower, upper)" επιστρέφει ένα iterable με αριθμούς -από το lower εώς το upper (κλειστό/ανοικτό διάστημα) -το παρακάτω τυπώνει: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -το "range(lower, upper, step)" επιστρέφει ένα iterable με αριθμούς -από το lower μέχρι το upper, με βήμα step -αν δεν δώσουμε τιμή βήματος, το default βήμα είναι 1. -το παρακάτω τυπώνει: - 4 - 6 -""" -for i in range(4, 8, 2): - print(i) -""" - -τα While loops τρέχουν μέχρι μία συνθήκη να γίνει ψευδής. -το παρακάτω τυπώνει: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Shorthand for x = x + 1 - -# Χειριζόμαστε εξαιρέσεις με ένα try/except block -try: - # Χρησιμοποιούμε το "raise" για να πετάξουμε ένα error - raise IndexError("This is an index error") -except IndexError as e: - pass # το Pass δεν κάνει τίποτα. Συνήθως κάνουμε ανάκτηση. -except (TypeError, NameError): - pass # Μπορούμε να χειριζόμαστε πολλές εξαιρέσεις μαζί, αν χρειαστεί -else: # Προαιρετικό στο try/except block. Πρέπει να ακολουθεί όλα τα except blocks - print("All good!") # τρέχει μόνο αν ο κώδικας στο try δεν προκαλεί εξαιρέσεις -finally: # Εκτελείται ό,τι και να γίνει - print("We can clean up resources here") - -# Αντί για try/finally για να καθαρίσουμε τους πόρους, μπορούμε να χρησιμοποιούμε το -# with expression as target: - pass to cleanup resources you can use a with statement -with open("myfile.txt") as f: - for line in f: - print(line) - -# Η Python προσφέρει μία θεμελιώδη αφαίρεση (abstraction) που λέγεται Iterable. -# iterable είναι ένα αντικείμενο που μπορεί να χρησιμοποιηθεί ως ακολουθία. -# Το αντικείμενο που επιστρέφει η συνάρτηση range, είναι ένα iterable. - -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) # => dict_keys(['one', 'two', 'three']). -# Αυτό είναι ένα αντικείμενο που υλοποιεί την iterable διεπαφή μας. - -# μπορούμε να τρέχουμε loops πάνω του. -for i in our_iterable: - print(i) # Prints one, two, three - -# Ωστόσο δεν μπορούμε να προσπελάσουμε τα στοιχεία του με index. -our_iterable[1] # προκαλεί a TypeError - -# Ένα iterable είναι ένα αντικείμενο που ξέρει πώς να δημιουργήσει έναν iterator. -our_iterator = iter(our_iterable) - -# Ο iterator μας είναι ένα αντικείμενο που μπορεί να θυμάται την κατάσταση όπως το διατρέχουμε. -# Παίρνουμε το επόμενο αντικείμενο με το "next()" -next(our_iterator) # => "one" - -# Διατηρεί την κατάσταση καθώς επαναλαμβάνουμε. -next(our_iterator) # => "two" -next(our_iterator) # => "three" - -# Όταν ο iterator έχει επιστρέψει όλα τα δεδομένα του, προκαλεί ένα μια εξαίρεση StopIteration. -next(our_iterator) # προκαλεί StopIteration - -# Μπορείς να πάρεις όλα τα αντικείμενα ενός iteratior καλώντας list() πάνω του. -list(filled_dict.keys()) # => Επιστρέφει ["one", "two", "three"] - - -#################################################### -## 4. Συναρτήσεις -#################################################### - -# Χρησιμποιούμε το "def" για να ορίσουμε νέες συναρτήσεις -def add(x, y): - print("x is {} and y is {}".format(x, y)) - return x + y # επιστρέφει τιμές με την εντολή return - -# Καλούμε συναρτήσεις με παραμέτρους -add(5, 6) # => τυπώνει "x is 5 and y is 6" και επιστρέφει 11 - -# Ένας άλλος τρόπος να καλέσεις συνάρτησει είναι με keyword arguments (ορίσματα λέξεις-κλειδιά) -add(y=6, x=5) # τα Keyword arguments μπορούν να δωθούν με οποιαδήποτε σειρά. - -# Μπορείς να ορίσεις συναρτήσεις που δέχονται μεταβλητό πλήθος ορισμάτων -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - -# Μπορούμε να ορίσουμε και συναρτήσεις που δέχονται μεταβλητό πλήθος keyword arguments -def keyword_args(**kwargs): - return kwargs - -# Για να δούμε τι γίνεται αν την καλέσουμε -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# Μπορείς να κάνεις και τα δύο ταυτόχρονα αν θες -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) τυπώνει: - (1, 2) - {"a": 3, "b": 4} -""" - -# Όταν καλείς συναρτήσεις μπορείς να κάνεις και το αντίστροφο από args/kwargs! -# Χρησιμοποίησε το * για να επεκτείνεις tuples και χρησιμοποίησε το ** για να επεκτείλεις kwargs -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # ισοδύναμο με all_the_args(1, 2, 3, 4) -all_the_args(**kwargs) # ισοδύναμο με all_the_args(a=3, b=4) -all_the_args(*args, **kwargs) # ισοδύναμο με all_the_args(1, 2, 3, 4, a=3, b=4) - -# Επιστρέφουμε πλειάδα τιμών (με tuple assignments) -def swap(x, y): - return y, x # Επιστρέφει πολλές τιμές ως tuple χωρίς την παρένθεση - # (Σημ.: οι παρενθέσεις έχουν παραλειφθεί αλλά μπορούν να γραφούν) - -x = 1 -y = 2 -x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # Ξανά, οι παρενθέσεις έχουν παραληφθεί αλλά μπορούν να γραφούν - -# Εμβέλεια συναρτήσεων -x = 5 - -def set_x(num): - # Η τοπική μεταβλητή x δεν είναι η ίδια με την global μεταβλητή x - x = num # => 43 - print(x) # => 43 - -def set_global_x(num): - global x - print(x) # => 5 - x = num # η global μεταβλητή x τώρα είναι 6 - print(x) # => 6 - -set_x(43) -set_global_x(6) - - -# Η Python έχει πρώτης τάξης συναρτήσεις -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# Αλλά έχει και anonymous συναρτήσεις. -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# Υπάρχουν ενσωματωμένες συναρτήσεις μεγαλύτερης τάξης -list(map(add_10, [1, 2, 3])) # => [11, 12, 13] -list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] - -list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] - -# Μπορούμε να χρησιμοποιήσουμε list comprehensions για ωραία maps και filters -# το List comprehension αποθηκεύει την έξοδο ως μία λίστα που μπορεί και η ίδια -# να είναι μια εμφωλευμένη λίστα -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -# Μπορείς επίσης να κατασκευάσεις set και dict comprehensions. -{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} -{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} - - -#################################################### -## 5. Modules -#################################################### - -# Μπορείς να κάνεις import modules -import math -print(math.sqrt(16)) # => 4.0 - -# Μπορείς να πάρεις συγκεκριμένες συναρτήσεις από ένα module -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# Μπορείς να κάνεις import όλες τις συναρτήσεις από ένα module. -# Προσοχή: δεν προτείνεται -from math import * - -# Μπορείς να δημιουργείς συντομογραφίες για τα ονόματα των modules -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Τα Python modules είναι απλά αρχεία Python. Μπορείς να δημιουργήσεις τα δικά σου -# και να τα κάνεις import το όνομα του module είναι ίδιο με το όνομα του αρχείου - -# μπορείς να βρεις ποιες συναρτήσεις και γνωρίσματα ορίζονται στο module -import math -dir(math) - -# Αν έχεις ένα Python script με όνομα math.py στον ίδιο φάκελο με το τρέχον script -# το αρχείο math.py θα φορτωθεί και όχι το built-in Python module -# Αυτό συμβαίνει επειδή τα τοπικά αρχεία έχουν προτεραιότητα έναντι των built-in -# βιβλιοθηκών της Python - - -#################################################### -## 6. Κλάσεις - Classes -#################################################### - -# χρησιμοποιούμε το "class" statement για να δημιουργήσουμε μια κλάση -class Human: - - # Ένα γνώρισμα της κλάσης. Είναι κοινό για όλα τα στιγμιότυπα αυτής. - species = "H. sapiens" - - # Βασικός initializer, καλείται όταν δημιουργείται στιγμιότυπο της κλάσης. - # Σημ. οι διπλές κάτω παύλες πριν και μετά υποδηλώνουν αντικείμενα - # ή γνωρίσματα που χρησιμοποιούνται από την Python αλλά ζουν σε ελεγχόμενα από - # το χρήση namespaces. - # Μέθοδοι (ή αντικείμενα ή γνωρίσματα) σαν τα __init__, __str__, __repr__ κλπ - # είναι ειδικές μέθοδοι (λέγονται και dunder (double underscore) μέθοδοι) - # Δεν πρέπει να δηλώνεις δικές σου τέτοιες συναρτήσεις - def __init__(self, name): - # Εκχώρησε στο attribute name του object το όρισμα - self.name = name - - # Αρχικοποίησε την ιδιότητα - self._age = 0 - - # Μία μέθοδος στιγμιότυπου (instance method). Όλες οι μέθοδοι παίρνουν το - # "self" ως πρώτο όρισμα - def say(self, msg): - print("{name}: {message}".format(name=self.name, message=msg)) - - # Ακόμα μία instance method - def sing(self): - return 'yo... yo... microphone check... one two... one two...' - - # Μία μέθοδος κλάσεις είναι κοινή ανάμεσα σε όλα τα instances. - # Καλούνται με calling class ώς πρώτο όρισμα - @classmethod - def get_species(cls): - return cls.species - - # Μία στατική μέθοδος καλείται χωρίς αναφορά σε κλάση ή στιγμιότυπο - @staticmethod - def grunt(): - return "*grunt*" - - # Ένα property είναι ακριβώς σαν ένα getter. - # Μετατρέπει τη μέθοδο age σε ένα γνώρισμα (attribute) μόνο-για-ανάγνωση - # με το ίδιο όνομα. - # Δεν χρειάζεται να γράφουμε τετριμένους getters και setters στην Python όμως. - @property - def age(self): - return self._age - - # Αυτό επιτρέπει στο property να γίνει set - @age.setter - def age(self, age): - self._age = age - - # Αυτό επιτρέπει σε ένα property να διαγραφεί - @age.deleter - def age(self): - del self._age - - -# Όταν ο διερμηνέας της Python διαβάζει αρχείο πηγαίου κώδικα τον εκτελεί όλο. -# Αυτός ο έλεγχος του __name__ σιγουρεύει ότι αυτό το block κώδικα τρέχει μόνο -# αυτό το module είναι το κύριο πρόγραμμα (και όχι imported) -if __name__ == '__main__': - # Δημιουργούμε στιγμιότυπο κλάσης - i = Human(name="Ian") - i.say("hi") # "Ian: hi" - j = Human("Joel") - j.say("hello") # "Joel: hello" - # τα i και j είναι στιγμιότυπα του τύπου Human - - # Καλούμε τη μέθοδο της κλάσης - i.say(i.get_species()) # "Ian: H. sapiens" - # Αλλάζουμε το κοινό attribute των αντικειμένων της κλάσης - Human.species = "H. neanderthalensis" - i.say(i.get_species()) # => "Ian: H. neanderthalensis" - j.say(j.get_species()) # => "Joel: H. neanderthalensis" - - # Καλούμε τη static μέθοδο - print(Human.grunt()) # => "*grunt*" - - # Δεν μπορούμε να καλέσουμε τη στατική μέθοδο με ένα στιγμιότυπο - # επειδή το i.grunt() θα βάλει αυτόματα το self (δηλαδή το αντικείμενο i) ως όρισμα - print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given - - # Ενημερώνουμε το property για αυτό το στγμιότυπο - i.age = 42 - # Παίρνουμε το property - i.say(i.age) # => "Ian: 42" - j.say(j.age) # => "Joel: 0" - # Διαγράφουμε το property - del i.age - # i.age # => αυτό θα προκαλούσε AttributeError - - -#################################################### -## 6.1 Κληρονομικότητα - Inheritance -#################################################### - -# Η κληρονομικότητα επιτρέπει σε νέες κλάσεις-παιδιά να οριστούν και να υιοθετήσουν -# μεθόδους και μεταβλητές από την κλάση-γονέα. - -# Χρησιμοποιώντας την κλάση Human που ορίστηκε πριν ως τη βασική κλάση (ή κλάση-γονέα) -# μπορούμε να ορίσουμε τις κλάσεις-παιδιά Superhero, που κληρονομεί μεταβλητές όπως -# "species", "name", και "age", καθώς και μεθόδους όπως "sing" και "grunt" -# από την κλάση Human, αλλά επίσης έχει τις δικές του ξεχωριστές ιδιότητες - -# Για να εκμεταλλευτείς το modularization κατά αρχείο, μπορείς να βάλεις την παραπάνω κλάση -# σε δικό της αρχείο, ας πούμε human.py - -# Για να κάνουμε import συναρτήσεις από άλλα αρχεία χρησιμοποιούμε το παρακάτω format -# from "filename-without-extension" import "function-or-class" - -from human import Human - - -# Προσδιόρισε την/τις parent class(es) ως παραμέτρους της κλάσης που ορίζεται -class Superhero(Human): - - # Αν η κλάση-παιδί πρέπει να κληρονομήσει όλους τους οεισμούς της κλάσης-γονέα - # χωρίς καμία αλλαγή, μπορείς απλά να γράψεις pass (και τίποτα άλλο) - # αλλά σε αυτή την περίπτωση είναι σχολιασμένο για να επιτρέψει τη δημιουργία - # ξεχωριστής κλάσης-παιδιού: - # pass - - # Η κλάση παιδί μπορεί να υπερφορτώσει (override) τα attributes της κλάσης από την οποία κληρονομεί - species = 'Superhuman' - - # Τα παιδιά αυτόματα, κληρονομούν τον constructo της κλάσης-γονέα - # συμπεριλαμβανομένων των ορισμάτων, αλλά μπορείς και να ορίσεις πρόσθετα ορίσματα - # ή ορισμούς και να κάνεις override τις μεθόδους, όπως τον constructor. - # Αυτός ο constructor κληρονομεί το όρισμα "name" από την κλάση Human και - # προσθέτει τα ορίσματα "superpower" και "movie": - def __init__(self, name, movie=False, - superpowers=["super strength", "bulletproofing"]): - - # πρόσθήκη επιπλέον attributes της κλάσης: - self.fictional = True - self.movie = movie - # έχετε το νου σας τις μεταβλητές (mutable) default τιμές, καθώς είναι κοινές - self.superpowers = superpowers - - # Η συνάρτηση "super" επιτρέπει την πρόσβαση στις μεθόδους της κλάσης-γονέα - # που είναι υπερφορτωμένες από το παιδί. Σε αυτή την περίπτωση τη μέθοδο __init__ - # Το παρακάτω καλεί τον constructor της κλάσης-γονέα: - super().__init__(name) - - # υπερφόρτωση της μεθόδου sing - def sing(self): - return 'Dun, dun, DUN!' - - # προσθήκη νέας μεθόδου που εφαρμόζεται σε στιγμιότυπα - def boast(self): - for power in self.superpowers: - print("I wield the power of {pow}!".format(pow=power)) - - -if __name__ == '__main__': - sup = Superhero(name="Tick") - - # Έλεγχος για το αν το στιγμιότυπο sup ανήκει στην κλάση Human - if isinstance(sup, Human): - print('I am human') - if type(sup) is Superhero: - print('I am a superhero') -# TODO: - # Παίρνουμε το Method Resolution search Order που χρησιμοποιούν οι getattr() και super() - # Αυτό το attribute είναι δυναμικό και μπορεί να ανανεωθεί - print(Superhero.__mro__) # => (, - # => , ) - - # Καλούμε μέθοδο της κλάσης-γονέα, αλλά χρησιμοποιεί το δικό της attribute - print(sup.get_species()) # => Superhuman - - # Καλεί την υπερφορτωμένη μέθοδο - print(sup.sing()) # => Dun, dun, DUN! - - # Καλεί μέθοδο από την κλάση Human - sup.say('Spoon') # => Tick: Spoon - - # Καλεί μέθοδο που υπάρχει μόνο στην κλάση Superhero - sup.boast() # => I wield the power of super strength! - # => I wield the power of bulletproofing! - - # Κληρονομημένο class attribute - sup.age = 31 - print(sup.age) # => 31 - - # Attribute που υπάρχει μόνο στην μέσα στην κλάση Superhero - print('Am I Oscar eligible? ' + str(sup.movie)) - -#################################################### -## 6.2 Πολλαπλή Κληρονομικότητα - Multiple Inheritance -#################################################### - -# Ένας ακόμη ορισμός κλάσης -# bat.py -class Bat: - - species = 'Baty' - - def __init__(self, can_fly=True): - self.fly = can_fly - - # Αυτή η κλάση έχει επίσης μία μέθοδο say - def say(self, msg): - msg = '... ... ...' - return msg - - # Και τη δική της μέθοδο sonar - def sonar(self): - return '))) ... (((' - -if __name__ == '__main__': - b = Bat() - print(b.say('hello')) - print(b.fly) - - -# Και ορίζουμε μία ακόμα κλάση που κληρονομεί από τις κλάσεις Superhero και Bat -# superhero.py -from superhero import Superhero -from bat import Bat - -# Ας πούμε αυτή την κλάση Batman -class Batman(Superhero, Bat): - - def __init__(self, *args, **kwargs): - # Τυπικά γα να κληρονομήουμε attributes πρέπει να καλέσουμε τη super: - # super(Batman, self).__init__(*args, **kwargs) - # Ωστόσο έχουμε να κάνουμε με πολλαπλή κληρονομικότητα εδώ, και το super() - # δουλεύει μόνο με την αμέσως ανώτερη κλάση στην ιεραρχία. - # Οπότε, καλούμε ρητά την __init__ για όλους τους πρόγονους - # Η χρήση των *args και **kwargs επιτρέπει έναν καθαρό τρόπο για να περνάμε ορίσματα - # με κάθε κλάση-γονέα να "βγάζει μία φλούδα από το κρεμμύδι". - Superhero.__init__(self, 'anonymous', movie=True, - superpowers=['Wealthy'], *args, **kwargs) - Bat.__init__(self, *args, can_fly=False, **kwargs) - # υπερφορτώνουμε την τιμή του γνωρίσματος name - self.name = 'Sad Affleck' - - def sing(self): - return 'nan nan nan nan nan batman!' - - -if __name__ == '__main__': - sup = Batman() - - # - # Λάβε το Method Resolution search Order που χρησιμοποιείται από το getattr() και το super(). - # Αυτό το attribute είναι δυναμικό και μπορεί να ενημερωθεί - print(Batman.__mro__) # => (, - # => , - # => , - # => , ) - - # Καλεί την μέθοδο της κλάσης-πατέρα αλλά χρησιμοποιεί το attribute της δικής του κλάσης - print(sup.get_species()) # => Superhuman - - # Καλεί την υπερφορτωμένη μέθοδο - print(sup.sing()) # => nan nan nan nan nan batman! - - # Καλεί μέθοδο από την κλάση Human, επειδή μετράει η σειρά της κληρονομιάς - sup.say('I agree') # => Sad Affleck: I agree - - # Καλεί μέθοδο που ανήκει μόνο στον δεύτερο πρόγονο - print(sup.sonar()) # => ))) ... ((( - - # Attribute της κληρονομημένης κλάσης - sup.age = 100 - print(sup.age) # => 100 - - # Κληρονομούμενο attribute από τον δεύτερο πρόγονο του οποίου η default τιμή - # έχει υπερφορτωθεί. - print('Can I fly? ' + str(sup.fly)) # => Can I fly? False - - - -#################################################### -## 7. Προχωρημένα -#################################################### - -# Με τους Generators μπορείς να γράψεις τεμπέλικο κώδικα. -def double_numbers(iterable): - for i in iterable: - yield i + i -# Οι Generators είναι αποδοτικοί από άποψη μνήμης επειδή φορτώνουν μόνο τα δεδομένα -# που είναι αναγκαία για να επεξεργαστούμε την επόμενη τιμή του iterable. -# Αυτό μας επιτρέπει να κάνουμε πράξεις σε τιμές που υπό άλλες συνθήκες θα ήταν -# απαγορευτικά μεγάλες. -for i in double_numbers(range(1, 900000000)): # το `range` είναι ένας generator. - print(i) - if i >= 30: - break - -# Όπως μπορείς να δημιουργήσεις list comprehension, έτσι μπορείς να δημιουργήσεις και -# generator comprehensions -values = (-x for x in [1,2,3,4,5]) -for x in values: - print(x) # τυπώνει -1 -2 -3 -4 -5 στο console/terminal - -# Μπορείς επίσης να μετατρέψεις ένα generator comprehension απευθείας σε λίστα. -values = (-x for x in [1,2,3,4,5]) -gen_to_list = list(values) -print(gen_to_list) # => [-1, -2, -3, -4, -5] - - -# Decorators -# σε αυτό το παράδειγμα το `beg` τυλίγει το `say`. Αν το say_please είναι True τότε -# θα αλλάξει το μήνυμα που επιστρέφεται. -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please - - -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( -``` - -## Έτοιμοι για περισσότερα? - -### Δωρεάν Online - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) -* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) -* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) -* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) -* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) -* [Dive Into Python 3](http://www.diveintopython3.net/index.html) -* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown new file mode 100644 index 00000000..3236e73a --- /dev/null +++ b/es-es/python-es.html.markdown @@ -0,0 +1,577 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] +translators: + - ["Camilo Garrido", "http://twitter.com/hirohope"] +lang: es-es +filename: learnpython3-es.py +--- + +Python fue creado por Guido Van Rossum en el principio de los 90'. Ahora es uno +de los lenguajes más populares en existencia. Me enamoré de Python por su claridad sintáctica. +Es básicamente pseudocódigo ejecutable. + +¡Comentarios serán muy apreciados! Pueden contactarme en [@louiedinh](http://twitter.com/louiedinh) o louiedinh [at] [servicio de email de google] + +```python + +# Comentarios de una línea comienzan con una almohadilla (o signo gato) + +""" Strings multilinea pueden escribirse + usando tres "'s, y comunmente son usados + como comentarios. +""" + +#################################################### +## 1. Tipos de datos primitivos y operadores. +#################################################### + +# Tienes números +3 #=> 3 + +# Matemática es lo que esperarías +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 + +# Excepto la división la cual por defecto retorna un número 'float' (número de coma flotante) +35 / 5 # => 7.0 +# Sin embargo también tienes disponible división entera +34 // 5 # => 6 + +# Cuando usas un float, los resultados son floats +3 * 2.0 # => 6.0 + +# Refuerza la precedencia con paréntesis +(1 + 3) * 2 # => 8 + + +# Valores 'boolean' (booleanos) son primitivos +True +False + +# Niega con 'not' +not True # => False +not False # => True + + +# Igualdad es == +1 == 1 # => True +2 == 1 # => False + +# Desigualdad es != +1 != 1 # => False +2 != 1 # => True + +# Más comparaciones +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# ¡Las comparaciones pueden ser concatenadas! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Strings se crean con " o ' +"Esto es un string." +'Esto también es un string' + +# ¡Strings también pueden ser sumados! +"Hola " + "mundo!" #=> "Hola mundo!" + +# Un string puede ser tratado como una lista de caracteres +"Esto es un string"[0] #=> 'E' + +# .format puede ser usaro para darle formato a los strings, así: +"{} pueden ser {}".format("strings", "interpolados") + +# Puedes reutilizar los argumentos de formato si estos se repiten. +"{0} sé ligero, {0} sé rápido, {0} brinca sobre la {1}".format("Jack", "vela") #=> "Jack sé ligero, Jack sé rápido, Jack brinca sobre la vela" +# Puedes usar palabras claves si no quieres contar. +"{nombre} quiere comer {comida}".format(nombre="Bob", comida="lasaña") #=> "Bob quiere comer lasaña" +# También puedes interpolar cadenas usando variables en el contexto +nombre = 'Bob' +comida = 'Lasaña' +f'{nombre} quiere comer {comida}' #=> "Bob quiere comer lasaña" + +# None es un objeto +None # => None + +# No uses el símbolo de igualdad `==` para comparar objetos con None +# Usa `is` en su lugar +"etc" is None #=> False +None is None #=> True + +# None, 0, y strings/listas/diccionarios/conjuntos vacíos(as) todos se evalúan como False. +# Todos los otros valores son True +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False +bool(set()) #=> False + + +#################################################### +## 2. Variables y Colecciones +#################################################### + +# Python tiene una función para imprimir +print("Soy Python. Encantado de conocerte") + +# No hay necesidad de declarar las variables antes de asignarlas. +una_variable = 5 # La convención es usar guiones_bajos_con_minúsculas +una_variable #=> 5 + +# Acceder a variables no asignadas previamente es una excepción. +# Ve Control de Flujo para aprender más sobre el manejo de excepciones. +otra_variable # Levanta un error de nombre + +# Listas almacena secuencias +lista = [] +# Puedes empezar con una lista prellenada +otra_lista = [4, 5, 6] + +# Añadir cosas al final de una lista con 'append' +lista.append(1) #lista ahora es [1] +lista.append(2) #lista ahora es [1, 2] +lista.append(4) #lista ahora es [1, 2, 4] +lista.append(3) #lista ahora es [1, 2, 4, 3] +# Remueve del final de la lista con 'pop' +lista.pop() #=> 3 y lista ahora es [1, 2, 4] +# Pongámoslo de vuelta +lista.append(3) # Nuevamente lista ahora es [1, 2, 4, 3]. + +# Accede a una lista como lo harías con cualquier arreglo +lista[0] #=> 1 +# Mira el último elemento +lista[-1] #=> 3 + +# Mirar fuera de los límites es un error 'IndexError' +lista[4] # Levanta la excepción IndexError + +# Puedes mirar por rango con la sintáxis de trozo. +# (Es un rango cerrado/abierto para ustedes los matemáticos.) +lista[1:3] #=> [2, 4] +# Omite el inicio +lista[2:] #=> [4, 3] +# Omite el final +lista[:3] #=> [1, 2, 4] +# Selecciona cada dos elementos +lista[::2] # =>[1, 4] +# Invierte la lista +lista[::-1] # => [3, 4, 2, 1] +# Usa cualquier combinación de estos para crear trozos avanzados +# lista[inicio:final:pasos] + +# Remueve elementos arbitrarios de una lista con 'del' +del lista[2] # lista ahora es [1, 2, 3] + +# Puedes sumar listas +lista + otra_lista #=> [1, 2, 3, 4, 5, 6] - Nota: lista y otra_lista no se tocan + +# Concatenar listas con 'extend' +lista.extend(otra_lista) # lista ahora es [1, 2, 3, 4, 5, 6] + +# Verifica la existencia en una lista con 'in' +1 in lista #=> True + +# Examina el largo de una lista con 'len' +len(lista) #=> 6 + + +# Tuplas son como listas pero son inmutables. +tupla = (1, 2, 3) +tupla[0] #=> 1 +tupla[0] = 3 # Levanta un error TypeError + +# También puedes hacer todas esas cosas que haces con listas +len(tupla) #=> 3 +tupla + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tupla[:2] #=> (1, 2) +2 in tupla #=> True + +# Puedes desempacar tuplas (o listas) en variables +a, b, c = (1, 2, 3) # a ahora es 1, b ahora es 2 y c ahora es 3 +# Tuplas son creadas por defecto si omites los paréntesis +d, e, f = 4, 5, 6 +# Ahora mira que fácil es intercambiar dos valores +e, d = d, e # d ahora es 5 y e ahora es 4 + + +# Diccionarios relacionan llaves y valores +dicc_vacio = {} +# Aquí está un diccionario prellenado +dicc_lleno = {"uno": 1, "dos": 2, "tres": 3} + +# Busca valores con [] +dicc_lleno["uno"] #=> 1 + +# Obtén todas las llaves como una lista con 'keys()'. Necesitamos envolver la llamada en 'list()' porque obtenemos un iterable. Hablaremos de eso luego. +list(dicc_lleno.keys()) #=> ["tres", "dos", "uno"] +# Nota - El orden de las llaves del diccionario no está garantizada. +# Tus resultados podrían no ser los mismos del ejemplo. + +# Obtén todos los valores como una lista. Nuevamente necesitamos envolverlas en una lista para sacarlas del iterable. +list(dicc_lleno.values()) #=> [3, 2, 1] +# Nota - Lo mismo que con las llaves, no se garantiza el orden. + +# Verifica la existencia de una llave en el diccionario con 'in' +"uno" in dicc_lleno #=> True +1 in dicc_lleno #=> False + +# Buscar una llave inexistente deriva en KeyError +dicc_lleno["cuatro"] # KeyError + +# Usa el método 'get' para evitar la excepción KeyError +dicc_lleno.get("uno") #=> 1 +dicc_lleno.get("cuatro") #=> None +# El método 'get' soporta un argumento por defecto cuando el valor no existe. +dicc_lleno.get("uno", 4) #=> 1 +dicc_lleno.get("cuatro", 4) #=> 4 + +# El método 'setdefault' inserta en un diccionario solo si la llave no está presente +dicc_lleno.setdefault("cinco", 5) #dicc_lleno["cinco"] es puesto con valor 5 +dicc_lleno.setdefault("cinco", 6) #dicc_lleno["cinco"] todavía es 5 + + +# Remueve llaves de un diccionario con 'del' +del dicc_lleno['uno'] # Remueve la llave 'uno' de dicc_lleno + +# Sets (conjuntos) almacenan ... bueno, conjuntos +conjunto_vacio = set() +# Inicializar un conjunto con montón de valores. Yeah, se ve un poco como un diccionario. Lo siento. +un_conjunto = {1,2,2,3,4} # un_conjunto ahora es {1, 2, 3, 4} + +# Añade más valores a un conjunto +conjunto_lleno.add(5) # conjunto_lleno ahora es {1, 2, 3, 4, 5} + +# Haz intersección de conjuntos con & +otro_conjunto = {3, 4, 5, 6} +conjunto_lleno & otro_conjunto #=> {3, 4, 5} + +# Haz unión de conjuntos con | +conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6} + +# Haz diferencia de conjuntos con - +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Verifica la existencia en un conjunto con 'in' +2 in conjunto_lleno #=> True +10 in conjunto_lleno #=> False + + +#################################################### +## 3. Control de Flujo +#################################################### + +# Creemos una variable para experimentar +some_var = 5 + +# Aquí está una declaración de un 'if'. ¡La indentación es significativa en Python! +# imprime "una_variable es menor que 10" +if una_variable > 10: + print("una_variable es completamente mas grande que 10.") +elif una_variable < 10: # Este condición 'elif' es opcional. + print("una_variable es mas chica que 10.") +else: # Esto también es opcional. + print("una_variable es de hecho 10.") + +""" +For itera sobre iterables (listas, cadenas, diccionarios, tuplas, generadores...) +imprime: + perro es un mamifero + gato es un mamifero + raton es un mamifero +""" +for animal in ["perro", "gato", "raton"]: + print("{} es un mamifero".format(animal)) + +""" +`range(número)` retorna un generador de números +desde cero hasta el número dado +imprime: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +While itera hasta que una condición no se cumple. +imprime: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # versión corta de x = x + 1 + +# Maneja excepciones con un bloque try/except +try: + # Usa raise para levantar un error + raise IndexError("Este es un error de indice") +except IndexError as e: + pass # Pass no hace nada. Usualmente harias alguna recuperacion aqui. + +# Python oferce una abstracción fundamental llamada Iterable. +# Un iterable es un objeto que puede ser tratado como una sequencia. +# El objeto es retornado por la función 'range' es un iterable. + +dicc_lleno = {"uno": 1, "dos": 2, "tres": 3} +nuestro_iterable = dicc_lleno.keys() +print(nuestro_iterable) #=> dict_keys(['uno', 'dos', 'tres']). Este es un objeto que implementa nuestra interfaz Iterable + +Podemos recorrerla. +for i in nuestro_iterable: + print(i) # Imprime uno, dos, tres + +# Aunque no podemos selecionar un elemento por su índice. +nuestro_iterable[1] # Genera un TypeError + +# Un iterable es un objeto que sabe como crear un iterador. +nuestro_iterator = iter(nuestro_iterable) + +# Nuestro iterador es un objeto que puede recordar el estado mientras lo recorremos. +# Obtenemos el siguiente objeto llamando la función __next__. +nuestro_iterator.__next__() #=> "uno" + +# Mantiene el estado mientras llamamos __next__. +nuestro_iterator.__next__() #=> "dos" +nuestro_iterator.__next__() #=> "tres" + +# Después que el iterador ha retornado todos sus datos, da una excepción StopIterator. +nuestro_iterator.__next__() # Genera StopIteration + +# Puedes obtener todos los elementos de un iterador llamando a list() en el. +list(dicc_lleno.keys()) #=> Retorna ["uno", "dos", "tres"] + + + +#################################################### +## 4. Funciones +#################################################### + +# Usa 'def' para crear nuevas funciones +def add(x, y): + print("x es {} y y es {}".format(x, y)) + return x + y # Retorna valores con una la declaración return + +# Llamando funciones con parámetros +add(5, 6) #=> imprime "x es 5 y y es 6" y retorna 11 + +# Otra forma de llamar funciones es con argumentos de palabras claves +add(y=6, x=5) # Argumentos de palabra clave pueden ir en cualquier orden. + + +# Puedes definir funciones que tomen un número variable de argumentos +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# Puedes definir funciones que toman un número variable de argumentos +# de palabras claves +def keyword_args(**kwargs): + return kwargs + +# Llamémosla para ver que sucede +keyword_args(pie="grande", lago="ness") #=> {"pie": "grande", "lago": "ness"} + + +# Puedes hacer ambas a la vez si quieres +def todos_los_argumentos(*args, **kwargs): + print args + print kwargs +""" +todos_los_argumentos(1, 2, a=3, b=4) imprime: + (1, 2) + {"a": 3, "b": 4} +""" + +# ¡Cuando llames funciones, puedes hacer lo opuesto a varargs/kwargs! +# Usa * para expandir tuplas y usa ** para expandir argumentos de palabras claves. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +todos_los_argumentos(*args) # es equivalente a foo(1, 2, 3, 4) +todos_los_argumentos(**kwargs) # es equivalente a foo(a=3, b=4) +todos_los_argumentos(*args, **kwargs) # es equivalente a foo(1, 2, 3, 4, a=3, b=4) + +# Python tiene funciones de primera clase +def crear_suma(x): + def suma(y): + return x + y + return suma + +sumar_10 = crear_suma(10) +sumar_10(3) #=> 13 + +# También hay funciones anónimas +(lambda x: x > 2)(3) #=> True + +# Hay funciones integradas de orden superior +map(sumar_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Podemos usar listas por comprensión para mapeos y filtros agradables +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] +# también hay diccionarios +{k:k**2 for k in range(3)} #=> {0: 0, 1: 1, 2: 4} +# y conjuntos por comprensión +{c for c in "la cadena"} #=> {'d', 'l', 'a', 'n', ' ', 'c', 'e'} + +#################################################### +## 5. Classes +#################################################### + + +# Heredamos de object para obtener una clase. +class Humano(object): + + # Un atributo de clase es compartido por todas las instancias de esta clase + especie = "H. sapiens" + + # Constructor basico + def __init__(self, nombre): + # Asigna el argumento al atributo nombre de la instancia + self.nombre = nombre + + # Un metodo de instancia. Todos los metodos toman self como primer argumento + def decir(self, msg): + return "%s: %s" % (self.nombre, msg) + + # Un metodo de clase es compartido a través de todas las instancias + # Son llamados con la clase como primer argumento + @classmethod + def get_especie(cls): + return cls.especie + + # Un metodo estatico es llamado sin la clase o instancia como referencia + @staticmethod + def roncar(): + return "*roncar*" + + +# Instancia una clase +i = Humano(nombre="Ian") +print i.decir("hi") # imprime "Ian: hi" + +j = Humano("Joel") +print j.decir("hello") #imprime "Joel: hello" + +# Llama nuestro método de clase +i.get_especie() #=> "H. sapiens" + +# Cambia los atributos compartidos +Humano.especie = "H. neanderthalensis" +i.get_especie() #=> "H. neanderthalensis" +j.get_especie() #=> "H. neanderthalensis" + +# Llama al método estático +Humano.roncar() #=> "*roncar*" + + +#################################################### +## 6. Módulos +#################################################### + +# Puedes importar módulos +import math +print(math.sqrt(16)) #=> 4.0 + +# Puedes obtener funciones específicas desde un módulo +from math import ceil, floor +print(ceil(3.7)) #=> 4.0 +print(floor(3.7))#=> 3.0 + +# Puedes importar todas las funciones de un módulo +# Precaución: Esto no es recomendable +from math import * + +# Puedes acortar los nombres de los módulos +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Los módulos de Python son sólo archivos ordinarios de Python. +# Puedes escribir tus propios módulos e importarlos. El nombre del módulo +# es el mismo del nombre del archivo. + +# Puedes encontrar que funciones y atributos definen un módulo. +import math +dir(math) + + +#################################################### +## 7. Avanzado +#################################################### + +# Los generadores te ayudan a hacer un código perezoso (lazy) +def duplicar_numeros(iterable): + for i in iterable: + yield i + i + +# Un generador crea valores sobre la marcha. +# En vez de generar y retornar todos los valores de una vez, crea uno en cada iteración. +# Esto significa que valores más grandes que 15 no serán procesados en 'duplicar_numeros'. +# Fíjate que 'range' es un generador. Crear una lista 1-900000000 tomaría mucho tiempo en crearse. +_rango = range(1, 900000000) +# Duplicará todos los números hasta que un resultado >= se encuentre. +for i in duplicar_numeros(_rango): + print(i) + if i >= 30: + break + + +# Decoradores +# en este ejemplo 'pedir' envuelve a 'decir' +# Pedir llamará a 'decir'. Si decir_por_favor es True entonces cambiará el mensaje a retornar +from functools import wraps + + +def pedir(_decir): + @wraps(_decir) + def wrapper(*args, **kwargs): + mensaje, decir_por_favor = _decir(*args, **kwargs) + if decir_por_favor: + return "{} {}".format(mensaje, "¡Por favor! Soy pobre :(") + return mensaje + + return wrapper + + +@pedir +def say(decir_por_favor=False): + mensaje = "¿Puedes comprarme una cerveza?" + return mensaje, decir_por_favor + + +print(decir()) # ¿Puedes comprarme una cerveza? +print(decir(decir_por_favor=True)) # ¿Puedes comprarme una cerveza? ¡Por favor! Soy pobre :() +``` + +## ¿Listo para más? + +### Gratis y en línea + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/3/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +### Encuadernados + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + diff --git a/es-es/python3-es.html.markdown b/es-es/python3-es.html.markdown deleted file mode 100644 index 3236e73a..00000000 --- a/es-es/python3-es.html.markdown +++ /dev/null @@ -1,577 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] -translators: - - ["Camilo Garrido", "http://twitter.com/hirohope"] -lang: es-es -filename: learnpython3-es.py ---- - -Python fue creado por Guido Van Rossum en el principio de los 90'. Ahora es uno -de los lenguajes más populares en existencia. Me enamoré de Python por su claridad sintáctica. -Es básicamente pseudocódigo ejecutable. - -¡Comentarios serán muy apreciados! Pueden contactarme en [@louiedinh](http://twitter.com/louiedinh) o louiedinh [at] [servicio de email de google] - -```python - -# Comentarios de una línea comienzan con una almohadilla (o signo gato) - -""" Strings multilinea pueden escribirse - usando tres "'s, y comunmente son usados - como comentarios. -""" - -#################################################### -## 1. Tipos de datos primitivos y operadores. -#################################################### - -# Tienes números -3 #=> 3 - -# Matemática es lo que esperarías -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 - -# Excepto la división la cual por defecto retorna un número 'float' (número de coma flotante) -35 / 5 # => 7.0 -# Sin embargo también tienes disponible división entera -34 // 5 # => 6 - -# Cuando usas un float, los resultados son floats -3 * 2.0 # => 6.0 - -# Refuerza la precedencia con paréntesis -(1 + 3) * 2 # => 8 - - -# Valores 'boolean' (booleanos) son primitivos -True -False - -# Niega con 'not' -not True # => False -not False # => True - - -# Igualdad es == -1 == 1 # => True -2 == 1 # => False - -# Desigualdad es != -1 != 1 # => False -2 != 1 # => True - -# Más comparaciones -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# ¡Las comparaciones pueden ser concatenadas! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# Strings se crean con " o ' -"Esto es un string." -'Esto también es un string' - -# ¡Strings también pueden ser sumados! -"Hola " + "mundo!" #=> "Hola mundo!" - -# Un string puede ser tratado como una lista de caracteres -"Esto es un string"[0] #=> 'E' - -# .format puede ser usaro para darle formato a los strings, así: -"{} pueden ser {}".format("strings", "interpolados") - -# Puedes reutilizar los argumentos de formato si estos se repiten. -"{0} sé ligero, {0} sé rápido, {0} brinca sobre la {1}".format("Jack", "vela") #=> "Jack sé ligero, Jack sé rápido, Jack brinca sobre la vela" -# Puedes usar palabras claves si no quieres contar. -"{nombre} quiere comer {comida}".format(nombre="Bob", comida="lasaña") #=> "Bob quiere comer lasaña" -# También puedes interpolar cadenas usando variables en el contexto -nombre = 'Bob' -comida = 'Lasaña' -f'{nombre} quiere comer {comida}' #=> "Bob quiere comer lasaña" - -# None es un objeto -None # => None - -# No uses el símbolo de igualdad `==` para comparar objetos con None -# Usa `is` en su lugar -"etc" is None #=> False -None is None #=> True - -# None, 0, y strings/listas/diccionarios/conjuntos vacíos(as) todos se evalúan como False. -# Todos los otros valores son True -bool(0) # => False -bool("") # => False -bool([]) #=> False -bool({}) #=> False -bool(set()) #=> False - - -#################################################### -## 2. Variables y Colecciones -#################################################### - -# Python tiene una función para imprimir -print("Soy Python. Encantado de conocerte") - -# No hay necesidad de declarar las variables antes de asignarlas. -una_variable = 5 # La convención es usar guiones_bajos_con_minúsculas -una_variable #=> 5 - -# Acceder a variables no asignadas previamente es una excepción. -# Ve Control de Flujo para aprender más sobre el manejo de excepciones. -otra_variable # Levanta un error de nombre - -# Listas almacena secuencias -lista = [] -# Puedes empezar con una lista prellenada -otra_lista = [4, 5, 6] - -# Añadir cosas al final de una lista con 'append' -lista.append(1) #lista ahora es [1] -lista.append(2) #lista ahora es [1, 2] -lista.append(4) #lista ahora es [1, 2, 4] -lista.append(3) #lista ahora es [1, 2, 4, 3] -# Remueve del final de la lista con 'pop' -lista.pop() #=> 3 y lista ahora es [1, 2, 4] -# Pongámoslo de vuelta -lista.append(3) # Nuevamente lista ahora es [1, 2, 4, 3]. - -# Accede a una lista como lo harías con cualquier arreglo -lista[0] #=> 1 -# Mira el último elemento -lista[-1] #=> 3 - -# Mirar fuera de los límites es un error 'IndexError' -lista[4] # Levanta la excepción IndexError - -# Puedes mirar por rango con la sintáxis de trozo. -# (Es un rango cerrado/abierto para ustedes los matemáticos.) -lista[1:3] #=> [2, 4] -# Omite el inicio -lista[2:] #=> [4, 3] -# Omite el final -lista[:3] #=> [1, 2, 4] -# Selecciona cada dos elementos -lista[::2] # =>[1, 4] -# Invierte la lista -lista[::-1] # => [3, 4, 2, 1] -# Usa cualquier combinación de estos para crear trozos avanzados -# lista[inicio:final:pasos] - -# Remueve elementos arbitrarios de una lista con 'del' -del lista[2] # lista ahora es [1, 2, 3] - -# Puedes sumar listas -lista + otra_lista #=> [1, 2, 3, 4, 5, 6] - Nota: lista y otra_lista no se tocan - -# Concatenar listas con 'extend' -lista.extend(otra_lista) # lista ahora es [1, 2, 3, 4, 5, 6] - -# Verifica la existencia en una lista con 'in' -1 in lista #=> True - -# Examina el largo de una lista con 'len' -len(lista) #=> 6 - - -# Tuplas son como listas pero son inmutables. -tupla = (1, 2, 3) -tupla[0] #=> 1 -tupla[0] = 3 # Levanta un error TypeError - -# También puedes hacer todas esas cosas que haces con listas -len(tupla) #=> 3 -tupla + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tupla[:2] #=> (1, 2) -2 in tupla #=> True - -# Puedes desempacar tuplas (o listas) en variables -a, b, c = (1, 2, 3) # a ahora es 1, b ahora es 2 y c ahora es 3 -# Tuplas son creadas por defecto si omites los paréntesis -d, e, f = 4, 5, 6 -# Ahora mira que fácil es intercambiar dos valores -e, d = d, e # d ahora es 5 y e ahora es 4 - - -# Diccionarios relacionan llaves y valores -dicc_vacio = {} -# Aquí está un diccionario prellenado -dicc_lleno = {"uno": 1, "dos": 2, "tres": 3} - -# Busca valores con [] -dicc_lleno["uno"] #=> 1 - -# Obtén todas las llaves como una lista con 'keys()'. Necesitamos envolver la llamada en 'list()' porque obtenemos un iterable. Hablaremos de eso luego. -list(dicc_lleno.keys()) #=> ["tres", "dos", "uno"] -# Nota - El orden de las llaves del diccionario no está garantizada. -# Tus resultados podrían no ser los mismos del ejemplo. - -# Obtén todos los valores como una lista. Nuevamente necesitamos envolverlas en una lista para sacarlas del iterable. -list(dicc_lleno.values()) #=> [3, 2, 1] -# Nota - Lo mismo que con las llaves, no se garantiza el orden. - -# Verifica la existencia de una llave en el diccionario con 'in' -"uno" in dicc_lleno #=> True -1 in dicc_lleno #=> False - -# Buscar una llave inexistente deriva en KeyError -dicc_lleno["cuatro"] # KeyError - -# Usa el método 'get' para evitar la excepción KeyError -dicc_lleno.get("uno") #=> 1 -dicc_lleno.get("cuatro") #=> None -# El método 'get' soporta un argumento por defecto cuando el valor no existe. -dicc_lleno.get("uno", 4) #=> 1 -dicc_lleno.get("cuatro", 4) #=> 4 - -# El método 'setdefault' inserta en un diccionario solo si la llave no está presente -dicc_lleno.setdefault("cinco", 5) #dicc_lleno["cinco"] es puesto con valor 5 -dicc_lleno.setdefault("cinco", 6) #dicc_lleno["cinco"] todavía es 5 - - -# Remueve llaves de un diccionario con 'del' -del dicc_lleno['uno'] # Remueve la llave 'uno' de dicc_lleno - -# Sets (conjuntos) almacenan ... bueno, conjuntos -conjunto_vacio = set() -# Inicializar un conjunto con montón de valores. Yeah, se ve un poco como un diccionario. Lo siento. -un_conjunto = {1,2,2,3,4} # un_conjunto ahora es {1, 2, 3, 4} - -# Añade más valores a un conjunto -conjunto_lleno.add(5) # conjunto_lleno ahora es {1, 2, 3, 4, 5} - -# Haz intersección de conjuntos con & -otro_conjunto = {3, 4, 5, 6} -conjunto_lleno & otro_conjunto #=> {3, 4, 5} - -# Haz unión de conjuntos con | -conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6} - -# Haz diferencia de conjuntos con - -{1,2,3,4} - {2,3,5} #=> {1, 4} - -# Verifica la existencia en un conjunto con 'in' -2 in conjunto_lleno #=> True -10 in conjunto_lleno #=> False - - -#################################################### -## 3. Control de Flujo -#################################################### - -# Creemos una variable para experimentar -some_var = 5 - -# Aquí está una declaración de un 'if'. ¡La indentación es significativa en Python! -# imprime "una_variable es menor que 10" -if una_variable > 10: - print("una_variable es completamente mas grande que 10.") -elif una_variable < 10: # Este condición 'elif' es opcional. - print("una_variable es mas chica que 10.") -else: # Esto también es opcional. - print("una_variable es de hecho 10.") - -""" -For itera sobre iterables (listas, cadenas, diccionarios, tuplas, generadores...) -imprime: - perro es un mamifero - gato es un mamifero - raton es un mamifero -""" -for animal in ["perro", "gato", "raton"]: - print("{} es un mamifero".format(animal)) - -""" -`range(número)` retorna un generador de números -desde cero hasta el número dado -imprime: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -While itera hasta que una condición no se cumple. -imprime: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # versión corta de x = x + 1 - -# Maneja excepciones con un bloque try/except -try: - # Usa raise para levantar un error - raise IndexError("Este es un error de indice") -except IndexError as e: - pass # Pass no hace nada. Usualmente harias alguna recuperacion aqui. - -# Python oferce una abstracción fundamental llamada Iterable. -# Un iterable es un objeto que puede ser tratado como una sequencia. -# El objeto es retornado por la función 'range' es un iterable. - -dicc_lleno = {"uno": 1, "dos": 2, "tres": 3} -nuestro_iterable = dicc_lleno.keys() -print(nuestro_iterable) #=> dict_keys(['uno', 'dos', 'tres']). Este es un objeto que implementa nuestra interfaz Iterable - -Podemos recorrerla. -for i in nuestro_iterable: - print(i) # Imprime uno, dos, tres - -# Aunque no podemos selecionar un elemento por su índice. -nuestro_iterable[1] # Genera un TypeError - -# Un iterable es un objeto que sabe como crear un iterador. -nuestro_iterator = iter(nuestro_iterable) - -# Nuestro iterador es un objeto que puede recordar el estado mientras lo recorremos. -# Obtenemos el siguiente objeto llamando la función __next__. -nuestro_iterator.__next__() #=> "uno" - -# Mantiene el estado mientras llamamos __next__. -nuestro_iterator.__next__() #=> "dos" -nuestro_iterator.__next__() #=> "tres" - -# Después que el iterador ha retornado todos sus datos, da una excepción StopIterator. -nuestro_iterator.__next__() # Genera StopIteration - -# Puedes obtener todos los elementos de un iterador llamando a list() en el. -list(dicc_lleno.keys()) #=> Retorna ["uno", "dos", "tres"] - - - -#################################################### -## 4. Funciones -#################################################### - -# Usa 'def' para crear nuevas funciones -def add(x, y): - print("x es {} y y es {}".format(x, y)) - return x + y # Retorna valores con una la declaración return - -# Llamando funciones con parámetros -add(5, 6) #=> imprime "x es 5 y y es 6" y retorna 11 - -# Otra forma de llamar funciones es con argumentos de palabras claves -add(y=6, x=5) # Argumentos de palabra clave pueden ir en cualquier orden. - - -# Puedes definir funciones que tomen un número variable de argumentos -def varargs(*args): - return args - -varargs(1, 2, 3) #=> (1,2,3) - - -# Puedes definir funciones que toman un número variable de argumentos -# de palabras claves -def keyword_args(**kwargs): - return kwargs - -# Llamémosla para ver que sucede -keyword_args(pie="grande", lago="ness") #=> {"pie": "grande", "lago": "ness"} - - -# Puedes hacer ambas a la vez si quieres -def todos_los_argumentos(*args, **kwargs): - print args - print kwargs -""" -todos_los_argumentos(1, 2, a=3, b=4) imprime: - (1, 2) - {"a": 3, "b": 4} -""" - -# ¡Cuando llames funciones, puedes hacer lo opuesto a varargs/kwargs! -# Usa * para expandir tuplas y usa ** para expandir argumentos de palabras claves. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -todos_los_argumentos(*args) # es equivalente a foo(1, 2, 3, 4) -todos_los_argumentos(**kwargs) # es equivalente a foo(a=3, b=4) -todos_los_argumentos(*args, **kwargs) # es equivalente a foo(1, 2, 3, 4, a=3, b=4) - -# Python tiene funciones de primera clase -def crear_suma(x): - def suma(y): - return x + y - return suma - -sumar_10 = crear_suma(10) -sumar_10(3) #=> 13 - -# También hay funciones anónimas -(lambda x: x > 2)(3) #=> True - -# Hay funciones integradas de orden superior -map(sumar_10, [1,2,3]) #=> [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] - -# Podemos usar listas por comprensión para mapeos y filtros agradables -[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] -# también hay diccionarios -{k:k**2 for k in range(3)} #=> {0: 0, 1: 1, 2: 4} -# y conjuntos por comprensión -{c for c in "la cadena"} #=> {'d', 'l', 'a', 'n', ' ', 'c', 'e'} - -#################################################### -## 5. Classes -#################################################### - - -# Heredamos de object para obtener una clase. -class Humano(object): - - # Un atributo de clase es compartido por todas las instancias de esta clase - especie = "H. sapiens" - - # Constructor basico - def __init__(self, nombre): - # Asigna el argumento al atributo nombre de la instancia - self.nombre = nombre - - # Un metodo de instancia. Todos los metodos toman self como primer argumento - def decir(self, msg): - return "%s: %s" % (self.nombre, msg) - - # Un metodo de clase es compartido a través de todas las instancias - # Son llamados con la clase como primer argumento - @classmethod - def get_especie(cls): - return cls.especie - - # Un metodo estatico es llamado sin la clase o instancia como referencia - @staticmethod - def roncar(): - return "*roncar*" - - -# Instancia una clase -i = Humano(nombre="Ian") -print i.decir("hi") # imprime "Ian: hi" - -j = Humano("Joel") -print j.decir("hello") #imprime "Joel: hello" - -# Llama nuestro método de clase -i.get_especie() #=> "H. sapiens" - -# Cambia los atributos compartidos -Humano.especie = "H. neanderthalensis" -i.get_especie() #=> "H. neanderthalensis" -j.get_especie() #=> "H. neanderthalensis" - -# Llama al método estático -Humano.roncar() #=> "*roncar*" - - -#################################################### -## 6. Módulos -#################################################### - -# Puedes importar módulos -import math -print(math.sqrt(16)) #=> 4.0 - -# Puedes obtener funciones específicas desde un módulo -from math import ceil, floor -print(ceil(3.7)) #=> 4.0 -print(floor(3.7))#=> 3.0 - -# Puedes importar todas las funciones de un módulo -# Precaución: Esto no es recomendable -from math import * - -# Puedes acortar los nombres de los módulos -import math as m -math.sqrt(16) == m.sqrt(16) #=> True - -# Los módulos de Python son sólo archivos ordinarios de Python. -# Puedes escribir tus propios módulos e importarlos. El nombre del módulo -# es el mismo del nombre del archivo. - -# Puedes encontrar que funciones y atributos definen un módulo. -import math -dir(math) - - -#################################################### -## 7. Avanzado -#################################################### - -# Los generadores te ayudan a hacer un código perezoso (lazy) -def duplicar_numeros(iterable): - for i in iterable: - yield i + i - -# Un generador crea valores sobre la marcha. -# En vez de generar y retornar todos los valores de una vez, crea uno en cada iteración. -# Esto significa que valores más grandes que 15 no serán procesados en 'duplicar_numeros'. -# Fíjate que 'range' es un generador. Crear una lista 1-900000000 tomaría mucho tiempo en crearse. -_rango = range(1, 900000000) -# Duplicará todos los números hasta que un resultado >= se encuentre. -for i in duplicar_numeros(_rango): - print(i) - if i >= 30: - break - - -# Decoradores -# en este ejemplo 'pedir' envuelve a 'decir' -# Pedir llamará a 'decir'. Si decir_por_favor es True entonces cambiará el mensaje a retornar -from functools import wraps - - -def pedir(_decir): - @wraps(_decir) - def wrapper(*args, **kwargs): - mensaje, decir_por_favor = _decir(*args, **kwargs) - if decir_por_favor: - return "{} {}".format(mensaje, "¡Por favor! Soy pobre :(") - return mensaje - - return wrapper - - -@pedir -def say(decir_por_favor=False): - mensaje = "¿Puedes comprarme una cerveza?" - return mensaje, decir_por_favor - - -print(decir()) # ¿Puedes comprarme una cerveza? -print(decir(decir_por_favor=True)) # ¿Puedes comprarme una cerveza? ¡Por favor! Soy pobre :() -``` - -## ¿Listo para más? - -### Gratis y en línea - -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/3/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) - -### Encuadernados - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) - diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown new file mode 100644 index 00000000..7112cd90 --- /dev/null +++ b/fr-fr/python-fr.html.markdown @@ -0,0 +1,732 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] +translators: + - ["Gnomino", "https://github.com/Gnomino"] + - ["Julien M'Poy", "http://github.com/groovytron"] +filename: learnpython3-fr.py +lang: fr-fr +--- + +Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des +langages les plus populaires. Je suis tombé amoureux de Python pour la clarté de sa syntaxe. +C'est tout simplement du pseudo-code exécutable. + +L'auteur original apprécierait les retours (en anglais): vous pouvez le contacter sur Twitter à [@louiedinh](http://twitter.com/louiedinh) ou par mail à l'adresse louiedinh [at] [google's email service] + +Note : Cet article s'applique spécifiquement à Python 3. Jettez un coup d'oeil [ici](http://learnxinyminutes.com/docs/fr-fr/python-fr/) pour apprendre le vieux Python 2.7 + +```python + +# Un commentaire d'une ligne commence par un dièse + +""" Les chaînes de caractères peuvent être écrites + avec 3 guillemets doubles ("), et sont souvent + utilisées comme des commentaires. +""" + +#################################################### +## 1. Types de données primaires et opérateurs +#################################################### + +# On a des nombres +3 # => 3 + +# Les calculs sont ce à quoi on s'attend +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Sauf pour la division qui retourne un float (nombre à virgule flottante) +35 / 5 # => 7.0 + +# Résultats de divisions entières tronqués pour les nombres positifs et négatifs +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Quand on utilise un float, le résultat est un float +3 * 2.0 # => 6.0 + +# Modulo (reste de la division) +7 % 3 # => 1 + +# Exponentiation (x**y, x élevé à la puissance y) +2**4 # => 16 + +# Forcer la priorité de calcul avec des parenthèses +(1 + 3) * 2 # => 8 + +# Les valeurs booléennes sont primitives +True +False + +# Négation avec not +not True # => False +not False # => True + +# Opérateurs booléens +# On note que "and" et "or" sont sensibles à la casse +True and False #=> False +False or True #=> True + +# Utilisation des opérations booléennes avec des entiers : +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# On vérifie une égalité avec == +1 == 1 # => True +2 == 1 # => False + +# On vérifie une inégalité avec != +1 != 1 # => False +2 != 1 # => True + +# Autres opérateurs de comparaison +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# On peut enchaîner les comparaisons +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (is vs. ==) is vérifie si deux variables pointent sur le même objet, mais == vérifie +# si les objets ont la même valeur. +a = [1, 2, 3, 4] # a pointe sur une nouvelle liste, [1, 2, 3, 4] +b = a # b pointe sur a +b is a # => True, a et b pointent sur le même objet +b == a # => True, les objets a et b sont égaux +b = [1, 2, 3, 4] # b pointe sur une nouvelle liste, [1, 2, 3, 4] +b is a # => False, a et b ne pointent pas sur le même objet +b == a # => True, les objets a et b ne pointent pas sur le même objet + +# Les chaînes (ou strings) sont créées avec " ou ' +"Ceci est une chaine" +'Ceci est une chaine aussi.' + +# On peut additionner des chaînes aussi ! Mais essayez d'éviter de le faire. +"Hello " + "world!" # => "Hello world!" +# On peut aussi le faire sans utiliser '+' +"Hello " "world!" # => "Hello world!" + +# On peut traîter une chaîne comme une liste de caractères +"This is a string"[0] # => 'T' + +# .format peut être utilisé pour formatter des chaînes, comme ceci: +"{} peuvent etre {}".format("Les chaînes", "interpolées") + +# On peut aussi réutiliser le même argument pour gagner du temps. +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# On peut aussi utiliser des mots clés pour éviter de devoir compter. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna" + +# Il est également possible d'utiliser les f-strings depuis Python 3.6 (https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals) +name = "Fred" +f"Il a dit que son nom est {name}." #=> "Il a dit que son nom est Fred." + +# Si votre code doit aussi être compatible avec Python 2.5 et moins, +# vous pouvez encore utiliser l'ancienne syntaxe : +"Les %s peuvent être %s avec la %s méthode" % ("chaînes", "interpolées", "vieille") + + +# None est un objet +None # => None + +# N'utilisez pas "==" pour comparer des objets à None +# Utilisez plutôt "is". Cela permet de vérifier l'égalité de l'identité des objets. +"etc" is None # => False +None is None # => True + +# None, 0, and les strings/lists/dicts (chaînes/listes/dictionnaires) valent False lorsqu'ils sont convertis en booléens. +# Toutes les autres valeurs valent True +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False + + +#################################################### +## 2. Variables et Collections +#################################################### + +# Python a une fonction print pour afficher du texte +print("I'm Python. Nice to meet you!") + +# Par défaut, la fonction print affiche aussi une nouvelle ligne à la fin. +# Utilisez l'argument optionnel end pour changer ce caractère de fin. +print("Hello, World", end="!") # => Hello, World! + +# Pas besoin de déclarer des variables avant de les définir. +# La convention est de nommer ses variables avec des minuscules_et_underscores +some_var = 5 +some_var # => 5 + +# Tenter d'accéder à une variable non définie lève une exception. +# Voir Structures de contrôle pour en apprendre plus sur le traitement des exceptions. +une_variable_inconnue # Lève une NameError + +# Les listes permettent de stocker des séquences +li = [] +# On peut initialiser une liste pré-remplie +other_li = [4, 5, 6] + +# On ajoute des objets à la fin d'une liste avec .append +li.append(1) # li vaut maintenant [1] +li.append(2) # li vaut maintenant [1, 2] +li.append(4) # li vaut maintenant [1, 2, 4] +li.append(3) # li vaut maintenant [1, 2, 4, 3] +# On enlève le dernier élément avec .pop +li.pop() # => 3 et li vaut maintenant [1, 2, 4] +# Et on le remet +li.append(3) # li vaut de nouveau [1, 2, 4, 3] + +# Accès à un élément d'une liste : +li[0] # => 1 +# Accès au dernier élément : +li[-1] # => 3 + +# Accéder à un élément en dehors des limites lève une IndexError +li[4] # Lève une IndexError + +# On peut accéder à une intervalle avec la syntaxe "slice" +# (c'est un rang du type "fermé/ouvert") +li[1:3] # => [2, 4] +# Omettre les deux premiers éléments +li[2:] # => [4, 3] +# Prendre les trois premiers +li[:3] # => [1, 2, 4] +# Sélectionner un élément sur deux +li[::2] # =>[1, 4] +# Avoir une copie de la liste à l'envers +li[::-1] # => [3, 4, 2, 1] +# Pour des "slices" plus élaborées : +# li[debut:fin:pas] + +# Faire une copie d'une profondeur de un avec les "slices" +li2 = li[:] # => li2 = [1, 2, 4, 3] mais (li2 is li) vaut False. + +# Enlever des éléments arbitrairement d'une liste +del li[2] # li is now [1, 2, 3] + +# On peut additionner des listes +# Note: les valeurs de li et other_li ne sont pas modifiées. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Concaténer des listes avec "extend()" +li.extend(other_li) # Maintenant li contient [1, 2, 3, 4, 5, 6] + +# Vérifier la présence d'un objet dans une liste avec "in" +1 in li # => True + +# Examiner la longueur avec "len()" +len(li) # => 6 + + +# Les tuples sont comme des listes mais sont immuables. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Lève une TypeError + +# Note : un tuple de taille un doit avoir une virgule après le dernier élément, +# mais ce n'est pas le cas des tuples d'autres tailles, même zéro. +type((1)) # => +type((1,)) # => +type(()) # => + +# On peut utiliser la plupart des opérations des listes sur des tuples. +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Vous pouvez décomposer des tuples (ou des listes) dans des variables +a, b, c = (1, 2, 3) # a vaut 1, b vaut 2 et c vaut 3 +# Les tuples sont créés par défaut sans parenthèses +d, e, f = 4, 5, 6 +# Voyez comme il est facile d'intervertir deux valeurs : +e, d = d, e # d vaut maintenant 5 et e vaut maintenant 4 + + +# Créer un dictionnaire : +empty_dict = {} +# Un dictionnaire pré-rempli : +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Note : les clés des dictionnaires doivent être de types immuables. +# Elles doivent être convertibles en une valeur constante pour une recherche rapide. +# Les types immuables incluent les ints, floats, strings et tuples. +invalid_dict = {[1,2,3]: "123"} # => Lève une TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Par contre, les valeurs peuvent être de tout type. + +# On trouve une valeur avec [] +filled_dict["one"] # => 1 + +# On obtient toutes les clés sous forme d'un itérable avec "keys()" Il faut l'entourer +# de list() pour avoir une liste Note: l'ordre n'est pas garanti. +list(filled_dict.keys()) # => ["three", "two", "one"] + + +# On obtient toutes les valeurs sous forme d'un itérable avec "values()". +# Là aussi, il faut utiliser list() pour avoir une liste. +# Note : l'ordre n'est toujours pas garanti. +list(filled_dict.values()) # => [3, 2, 1] + + +# On vérifie la présence d'une clé dans un dictionnaire avec "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# L'accès à une clé non-existente lève une KeyError +filled_dict["four"] # KeyError + +# On utilise "get()" pour éviter la KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# La méthode get accepte une valeur de retour par défaut en cas de valeur non-existante. +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# "setdefault()" insère une valeur dans un dictionnaire si la clé n'est pas présente. +filled_dict.setdefault("five", 5) # filled_dict["five"] devient 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] est toujours 5 + +# Ajouter à un dictionnaire +filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} +#filled_dict["four"] = 4 # une autre méthode + +# Enlever des clés d'un dictionnaire avec del +del filled_dict["one"] # Enlever la clé "one" de filled_dict. + + +# Les sets stockent des ensembles +empty_set = set() +# Initialiser un set avec des valeurs. Oui, ça ressemble aux dictionnaires, désolé. +some_set = {1, 1, 2, 2, 3, 4} # some_set est maintenant {1, 2, 3, 4} + +# Comme les clés d'un dictionnaire, les éléments d'un set doivent être immuables. +invalid_set = {[1], 1} # => Lève une TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# On peut changer un set : +filled_set = some_set + +# Ajouter un objet au set : +filled_set.add(5) # filled_set vaut maintenant {1, 2, 3, 4, 5} + +# Chercher les intersections de deux sets avec & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# On fait l'union de sets avec | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# On fait la différence de deux sets avec - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# On vérifie la présence d'un objet dans un set avec in +2 in filled_set # => True +10 in filled_set # => False + + + +#################################################### +## 3. Structures de contrôle et Itérables +#################################################### + +# On crée juste une variable +some_var = 5 + +# Voici une condition "si". L'indentation est significative en Python! +# Affiche: "some_var is smaller than 10" +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # La clause elif ("sinon si") est optionelle + print("some_var is smaller than 10.") +else: # La clause else ("sinon") l'est aussi. + print("some_var is indeed 10.") + + +""" +Les boucles "for" itèrent sur une liste +Affiche: + chien est un mammifère + chat est un mammifère + souris est un mammifère +""" +for animal in ["chien", "chat", "souris"]: + # On peut utiliser format() pour interpoler des chaînes formattées + print("{} est un mammifère".format(animal)) + +""" +"range(nombre)" retourne un itérable de nombres +de zéro au nombre donné +Affiche: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(debut, fin)" retourne un itérable de nombre +de debut à fin. +Affiche: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(debut, fin, pas)" retourne un itérable de nombres +de début à fin en incrémentant de pas. +Si le pas n'est pas indiqué, la valeur par défaut est 1. +Affiche: + 4 + 6 + 8 +""" +for i in range(4, 8, 2): + print(i) +""" + +Les boucles "while" bouclent jusqu'à ce que la condition devienne fausse. +Affiche: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Raccourci pour x = x + 1 + +# On gère les exceptions avec un bloc try/except +try: + # On utilise "raise" pour lever une erreur + raise IndexError("Ceci est une erreur d'index") +except IndexError as e: + pass # Pass signifie simplement "ne rien faire". Généralement, on gère l'erreur ici. +except (TypeError, NameError): + pass # Si besoin, on peut aussi gérer plusieurs erreurs en même temps. +else: # Clause optionelle des blocs try/except. Doit être après tous les except. + print("Tout va bien!") # Uniquement si aucune exception n'est levée. +finally: # Éxécuté dans toutes les circonstances. + print("On nettoie les ressources ici") + +# Au lieu de try/finally pour nettoyer les ressources, on peut utiliser with +with open("myfile.txt") as f: + for line in f: + print(line) + +# Python offre une abstraction fondamentale : l'Iterable. +# Un itérable est un objet pouvant être traîté comme une séquence. +# L'objet retourné par la fonction range() est un itérable. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) #=> range(1,10). C'est un objet qui implémente l'interface Iterable + +# On peut boucler dessus +for i in our_iterable: + print(i) # Affiche one, two, three + +# Cependant, on ne peut pas accéder aux éléments par leur adresse. +our_iterable[1] # Lève une TypeError + +# Un itérable est un objet qui sait créer un itérateur. +our_iterator = iter(our_iterable) + +# Notre itérateur est un objet qui se rappelle de notre position quand on le traverse. +# On passe à l'élément suivant avec "next()". +next(our_iterator) #=> "one" + +# Il garde son état quand on itère. +next(our_iterator) #=> "two" +next(our_iterator) #=> "three" + +# Après que l'itérateur a retourné toutes ses données, il lève une exception StopIterator +next(our_iterator) # Lève une StopIteration + +# On peut mettre tous les éléments d'un itérateur dans une liste avec list() +list(filled_dict.keys()) #=> Returns ["one", "two", "three"] + + +#################################################### +## 4. Fonctions +#################################################### + +# On utilise "def" pour créer des fonctions +def add(x, y): + print("x est {} et y est {}".format(x, y)) + return x + y # On retourne une valeur avec return + +# Appel d'une fonction avec des paramètres : +add(5, 6) # => affiche "x est 5 et y est 6" et retourne 11 + +# Une autre manière d'appeler une fonction : avec des arguments +add(y=6, x=5) # Les arguments peuvent être dans n'importe quel ordre. + +# Définir une fonction qui prend un nombre variable d'arguments +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# On peut aussi définir une fonction qui prend un nombre variable de paramètres. +def keyword_args(**kwargs): + return kwargs + +# Appelons la pour voir ce qu'il se passe : +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# On peut aussi faire les deux à la fois : +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) affiche: + (1, 2) + {"a": 3, "b": 4} +""" + +# En appelant des fonctions, on peut aussi faire l'inverse : +# utiliser * pour étendre un tuple de paramètres +# et ** pour étendre un dictionnaire d'arguments. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # équivalent à foo(1, 2, 3, 4) +all_the_args(**kwargs) # équivalent à foo(a=3, b=4) +all_the_args(*args, **kwargs) # équivalent à foo(1, 2, 3, 4, a=3, b=4) + +# Retourne plusieurs valeurs (avec un tuple) +def swap(x, y): + return y, x # Retourne plusieurs valeurs avec un tuple sans parenthèses. + # (Note: on peut aussi utiliser des parenthèses) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Là aussi, rien ne nous empêche d'ajouter des parenthèses + +# Portée des fonctions : +x = 5 + +def setX(num): + # La variable locale x n'est pas la même que la variable globale x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # la variable globale x est maintenant 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# Python a des fonctions de première classe +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Mais aussi des fonctions anonymes +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# TODO - Fix for iterables +# Il y a aussi des fonctions de base +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# On peut utiliser les compréhensions de listes pour de jolies maps et filtres. +# Une compréhension de liste stocke la sortie comme une liste qui peut elle même être une liste imbriquée. +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. Classes +#################################################### + + +# On utilise l'opérateur "class" pour définir une classe +class Human: + + # Un attribut de la classe. Il est partagé par toutes les instances de la classe. + species = "H. sapiens" + + # L'initialiseur de base. Il est appelé quand la classe est instanciée. + # Note : les doubles underscores au début et à la fin sont utilisés pour + # les fonctions et attributs utilisés par Python mais contrôlés par l'utilisateur. + # Les méthodes (ou objets ou attributs) comme: __init__, __str__, + # __repr__ etc. sont appelés méthodes magiques. + # Vous ne devriez pas inventer de noms de ce style. + def __init__(self, name): + # Assigner l'argument à l'attribut de l'instance + self.name = name + + # Une méthode de l'instance. Toutes prennent "self" comme premier argument. + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # Une méthode de classe est partagée avec entre les instances + # Ils sont appelés avec la classe comme premier argument + @classmethod + def get_species(cls): + return cls.species + + # Une méthode statique est appelée sans référence à une instance ni à une classe. + @staticmethod + def grunt(): + return "*grunt*" + + +# Instantier une classe +i = Human(name="Ian") +print(i.say("hi")) # affiche "Ian: hi" + +j = Human("Joel") +print(j.say("hello")) # affiche "Joel: hello" + +# Appeller notre méthode de classe +i.get_species() # => "H. sapiens" + +# Changer les attributs partagés +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Appeller la méthode statique +Human.grunt() # => "*grunt*" + + +#################################################### +## 6. Modules +#################################################### + +# On peut importer des modules +import math +print(math.sqrt(16)) # => 4.0 + +# On peut importer des fonctions spécifiques d'un module +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# On peut importer toutes les fonctions d'un module +# Attention: ce n'est pas recommandé. +from math import * + +# On peut raccourcir un nom de module +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Les modules Python sont juste des fichiers Python. +# Vous pouvez écrire les vôtres et les importer. Le nom du module +# est le nom du fichier. + +# On peut voir quels fonctions et objets un module définit +import math +dir(math) + + +#################################################### +## 7. Avancé +#################################################### + +# Les générateurs aident à faire du code paresseux (lazy) +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Un générateur crée des valeurs à la volée. +# Au lieu de générer et retourner toutes les valeurs en une fois, il en crée une à chaque +# itération. Cela signifie que les valeurs supérieures à 30 ne seront pas traîtées par +# double_numbers. +# Note : range est un générateur aussi. +# Créer une liste 1-900000000 prendrait beaucoup de temps +# On met un underscore à la fin d'un nom de variable normalement réservé par Python. +range_ = range(1, 900000000) +# Double tous les nombres jusqu'à ce qu'un nombre >=30 soit trouvé +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Decorateurs +# Dans cet exemple, beg enveloppe say +# Beg appellera say. Si say_please vaut True le message retourné sera changé +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # affiche Can you buy me a beer? +print(say(say_please=True)) # affiche Can you buy me a beer? Please! I am poor :( +``` + +## Prêt pour encore plus ? + +### En ligne et gratuit (en anglais) + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) + +### En ligne et gratuit (en français) + +* [Le petit guide des batteries à découvrir](https://he-arc.github.io/livre-python/) + +### Livres (en anglais) + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/fr-fr/python3-fr.html.markdown b/fr-fr/python3-fr.html.markdown deleted file mode 100644 index 7112cd90..00000000 --- a/fr-fr/python3-fr.html.markdown +++ /dev/null @@ -1,732 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] -translators: - - ["Gnomino", "https://github.com/Gnomino"] - - ["Julien M'Poy", "http://github.com/groovytron"] -filename: learnpython3-fr.py -lang: fr-fr ---- - -Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des -langages les plus populaires. Je suis tombé amoureux de Python pour la clarté de sa syntaxe. -C'est tout simplement du pseudo-code exécutable. - -L'auteur original apprécierait les retours (en anglais): vous pouvez le contacter sur Twitter à [@louiedinh](http://twitter.com/louiedinh) ou par mail à l'adresse louiedinh [at] [google's email service] - -Note : Cet article s'applique spécifiquement à Python 3. Jettez un coup d'oeil [ici](http://learnxinyminutes.com/docs/fr-fr/python-fr/) pour apprendre le vieux Python 2.7 - -```python - -# Un commentaire d'une ligne commence par un dièse - -""" Les chaînes de caractères peuvent être écrites - avec 3 guillemets doubles ("), et sont souvent - utilisées comme des commentaires. -""" - -#################################################### -## 1. Types de données primaires et opérateurs -#################################################### - -# On a des nombres -3 # => 3 - -# Les calculs sont ce à quoi on s'attend -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 - -# Sauf pour la division qui retourne un float (nombre à virgule flottante) -35 / 5 # => 7.0 - -# Résultats de divisions entières tronqués pour les nombres positifs et négatifs -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # works on floats too --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Quand on utilise un float, le résultat est un float -3 * 2.0 # => 6.0 - -# Modulo (reste de la division) -7 % 3 # => 1 - -# Exponentiation (x**y, x élevé à la puissance y) -2**4 # => 16 - -# Forcer la priorité de calcul avec des parenthèses -(1 + 3) * 2 # => 8 - -# Les valeurs booléennes sont primitives -True -False - -# Négation avec not -not True # => False -not False # => True - -# Opérateurs booléens -# On note que "and" et "or" sont sensibles à la casse -True and False #=> False -False or True #=> True - -# Utilisation des opérations booléennes avec des entiers : -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -1 == True #=> True - -# On vérifie une égalité avec == -1 == 1 # => True -2 == 1 # => False - -# On vérifie une inégalité avec != -1 != 1 # => False -2 != 1 # => True - -# Autres opérateurs de comparaison -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# On peut enchaîner les comparaisons -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# (is vs. ==) is vérifie si deux variables pointent sur le même objet, mais == vérifie -# si les objets ont la même valeur. -a = [1, 2, 3, 4] # a pointe sur une nouvelle liste, [1, 2, 3, 4] -b = a # b pointe sur a -b is a # => True, a et b pointent sur le même objet -b == a # => True, les objets a et b sont égaux -b = [1, 2, 3, 4] # b pointe sur une nouvelle liste, [1, 2, 3, 4] -b is a # => False, a et b ne pointent pas sur le même objet -b == a # => True, les objets a et b ne pointent pas sur le même objet - -# Les chaînes (ou strings) sont créées avec " ou ' -"Ceci est une chaine" -'Ceci est une chaine aussi.' - -# On peut additionner des chaînes aussi ! Mais essayez d'éviter de le faire. -"Hello " + "world!" # => "Hello world!" -# On peut aussi le faire sans utiliser '+' -"Hello " "world!" # => "Hello world!" - -# On peut traîter une chaîne comme une liste de caractères -"This is a string"[0] # => 'T' - -# .format peut être utilisé pour formatter des chaînes, comme ceci: -"{} peuvent etre {}".format("Les chaînes", "interpolées") - -# On peut aussi réutiliser le même argument pour gagner du temps. -"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" - -# On peut aussi utiliser des mots clés pour éviter de devoir compter. -"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna" - -# Il est également possible d'utiliser les f-strings depuis Python 3.6 (https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals) -name = "Fred" -f"Il a dit que son nom est {name}." #=> "Il a dit que son nom est Fred." - -# Si votre code doit aussi être compatible avec Python 2.5 et moins, -# vous pouvez encore utiliser l'ancienne syntaxe : -"Les %s peuvent être %s avec la %s méthode" % ("chaînes", "interpolées", "vieille") - - -# None est un objet -None # => None - -# N'utilisez pas "==" pour comparer des objets à None -# Utilisez plutôt "is". Cela permet de vérifier l'égalité de l'identité des objets. -"etc" is None # => False -None is None # => True - -# None, 0, and les strings/lists/dicts (chaînes/listes/dictionnaires) valent False lorsqu'ils sont convertis en booléens. -# Toutes les autres valeurs valent True -bool(0) # => False -bool("") # => False -bool([]) #=> False -bool({}) #=> False - - -#################################################### -## 2. Variables et Collections -#################################################### - -# Python a une fonction print pour afficher du texte -print("I'm Python. Nice to meet you!") - -# Par défaut, la fonction print affiche aussi une nouvelle ligne à la fin. -# Utilisez l'argument optionnel end pour changer ce caractère de fin. -print("Hello, World", end="!") # => Hello, World! - -# Pas besoin de déclarer des variables avant de les définir. -# La convention est de nommer ses variables avec des minuscules_et_underscores -some_var = 5 -some_var # => 5 - -# Tenter d'accéder à une variable non définie lève une exception. -# Voir Structures de contrôle pour en apprendre plus sur le traitement des exceptions. -une_variable_inconnue # Lève une NameError - -# Les listes permettent de stocker des séquences -li = [] -# On peut initialiser une liste pré-remplie -other_li = [4, 5, 6] - -# On ajoute des objets à la fin d'une liste avec .append -li.append(1) # li vaut maintenant [1] -li.append(2) # li vaut maintenant [1, 2] -li.append(4) # li vaut maintenant [1, 2, 4] -li.append(3) # li vaut maintenant [1, 2, 4, 3] -# On enlève le dernier élément avec .pop -li.pop() # => 3 et li vaut maintenant [1, 2, 4] -# Et on le remet -li.append(3) # li vaut de nouveau [1, 2, 4, 3] - -# Accès à un élément d'une liste : -li[0] # => 1 -# Accès au dernier élément : -li[-1] # => 3 - -# Accéder à un élément en dehors des limites lève une IndexError -li[4] # Lève une IndexError - -# On peut accéder à une intervalle avec la syntaxe "slice" -# (c'est un rang du type "fermé/ouvert") -li[1:3] # => [2, 4] -# Omettre les deux premiers éléments -li[2:] # => [4, 3] -# Prendre les trois premiers -li[:3] # => [1, 2, 4] -# Sélectionner un élément sur deux -li[::2] # =>[1, 4] -# Avoir une copie de la liste à l'envers -li[::-1] # => [3, 4, 2, 1] -# Pour des "slices" plus élaborées : -# li[debut:fin:pas] - -# Faire une copie d'une profondeur de un avec les "slices" -li2 = li[:] # => li2 = [1, 2, 4, 3] mais (li2 is li) vaut False. - -# Enlever des éléments arbitrairement d'une liste -del li[2] # li is now [1, 2, 3] - -# On peut additionner des listes -# Note: les valeurs de li et other_li ne sont pas modifiées. -li + other_li # => [1, 2, 3, 4, 5, 6] - -# Concaténer des listes avec "extend()" -li.extend(other_li) # Maintenant li contient [1, 2, 3, 4, 5, 6] - -# Vérifier la présence d'un objet dans une liste avec "in" -1 in li # => True - -# Examiner la longueur avec "len()" -len(li) # => 6 - - -# Les tuples sont comme des listes mais sont immuables. -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # Lève une TypeError - -# Note : un tuple de taille un doit avoir une virgule après le dernier élément, -# mais ce n'est pas le cas des tuples d'autres tailles, même zéro. -type((1)) # => -type((1,)) # => -type(()) # => - -# On peut utiliser la plupart des opérations des listes sur des tuples. -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# Vous pouvez décomposer des tuples (ou des listes) dans des variables -a, b, c = (1, 2, 3) # a vaut 1, b vaut 2 et c vaut 3 -# Les tuples sont créés par défaut sans parenthèses -d, e, f = 4, 5, 6 -# Voyez comme il est facile d'intervertir deux valeurs : -e, d = d, e # d vaut maintenant 5 et e vaut maintenant 4 - - -# Créer un dictionnaire : -empty_dict = {} -# Un dictionnaire pré-rempli : -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Note : les clés des dictionnaires doivent être de types immuables. -# Elles doivent être convertibles en une valeur constante pour une recherche rapide. -# Les types immuables incluent les ints, floats, strings et tuples. -invalid_dict = {[1,2,3]: "123"} # => Lève une TypeError: unhashable type: 'list' -valid_dict = {(1,2,3):[1,2,3]} # Par contre, les valeurs peuvent être de tout type. - -# On trouve une valeur avec [] -filled_dict["one"] # => 1 - -# On obtient toutes les clés sous forme d'un itérable avec "keys()" Il faut l'entourer -# de list() pour avoir une liste Note: l'ordre n'est pas garanti. -list(filled_dict.keys()) # => ["three", "two", "one"] - - -# On obtient toutes les valeurs sous forme d'un itérable avec "values()". -# Là aussi, il faut utiliser list() pour avoir une liste. -# Note : l'ordre n'est toujours pas garanti. -list(filled_dict.values()) # => [3, 2, 1] - - -# On vérifie la présence d'une clé dans un dictionnaire avec "in" -"one" in filled_dict # => True -1 in filled_dict # => False - -# L'accès à une clé non-existente lève une KeyError -filled_dict["four"] # KeyError - -# On utilise "get()" pour éviter la KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# La méthode get accepte une valeur de retour par défaut en cas de valeur non-existante. -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 - -# "setdefault()" insère une valeur dans un dictionnaire si la clé n'est pas présente. -filled_dict.setdefault("five", 5) # filled_dict["five"] devient 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] est toujours 5 - -# Ajouter à un dictionnaire -filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} -#filled_dict["four"] = 4 # une autre méthode - -# Enlever des clés d'un dictionnaire avec del -del filled_dict["one"] # Enlever la clé "one" de filled_dict. - - -# Les sets stockent des ensembles -empty_set = set() -# Initialiser un set avec des valeurs. Oui, ça ressemble aux dictionnaires, désolé. -some_set = {1, 1, 2, 2, 3, 4} # some_set est maintenant {1, 2, 3, 4} - -# Comme les clés d'un dictionnaire, les éléments d'un set doivent être immuables. -invalid_set = {[1], 1} # => Lève une TypeError: unhashable type: 'list' -valid_set = {(1,), 1} - -# On peut changer un set : -filled_set = some_set - -# Ajouter un objet au set : -filled_set.add(5) # filled_set vaut maintenant {1, 2, 3, 4, 5} - -# Chercher les intersections de deux sets avec & -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# On fait l'union de sets avec | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# On fait la différence de deux sets avec - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# On vérifie la présence d'un objet dans un set avec in -2 in filled_set # => True -10 in filled_set # => False - - - -#################################################### -## 3. Structures de contrôle et Itérables -#################################################### - -# On crée juste une variable -some_var = 5 - -# Voici une condition "si". L'indentation est significative en Python! -# Affiche: "some_var is smaller than 10" -if some_var > 10: - print("some_var is totally bigger than 10.") -elif some_var < 10: # La clause elif ("sinon si") est optionelle - print("some_var is smaller than 10.") -else: # La clause else ("sinon") l'est aussi. - print("some_var is indeed 10.") - - -""" -Les boucles "for" itèrent sur une liste -Affiche: - chien est un mammifère - chat est un mammifère - souris est un mammifère -""" -for animal in ["chien", "chat", "souris"]: - # On peut utiliser format() pour interpoler des chaînes formattées - print("{} est un mammifère".format(animal)) - -""" -"range(nombre)" retourne un itérable de nombres -de zéro au nombre donné -Affiche: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -"range(debut, fin)" retourne un itérable de nombre -de debut à fin. -Affiche: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -"range(debut, fin, pas)" retourne un itérable de nombres -de début à fin en incrémentant de pas. -Si le pas n'est pas indiqué, la valeur par défaut est 1. -Affiche: - 4 - 6 - 8 -""" -for i in range(4, 8, 2): - print(i) -""" - -Les boucles "while" bouclent jusqu'à ce que la condition devienne fausse. -Affiche: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Raccourci pour x = x + 1 - -# On gère les exceptions avec un bloc try/except -try: - # On utilise "raise" pour lever une erreur - raise IndexError("Ceci est une erreur d'index") -except IndexError as e: - pass # Pass signifie simplement "ne rien faire". Généralement, on gère l'erreur ici. -except (TypeError, NameError): - pass # Si besoin, on peut aussi gérer plusieurs erreurs en même temps. -else: # Clause optionelle des blocs try/except. Doit être après tous les except. - print("Tout va bien!") # Uniquement si aucune exception n'est levée. -finally: # Éxécuté dans toutes les circonstances. - print("On nettoie les ressources ici") - -# Au lieu de try/finally pour nettoyer les ressources, on peut utiliser with -with open("myfile.txt") as f: - for line in f: - print(line) - -# Python offre une abstraction fondamentale : l'Iterable. -# Un itérable est un objet pouvant être traîté comme une séquence. -# L'objet retourné par la fonction range() est un itérable. - -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) #=> range(1,10). C'est un objet qui implémente l'interface Iterable - -# On peut boucler dessus -for i in our_iterable: - print(i) # Affiche one, two, three - -# Cependant, on ne peut pas accéder aux éléments par leur adresse. -our_iterable[1] # Lève une TypeError - -# Un itérable est un objet qui sait créer un itérateur. -our_iterator = iter(our_iterable) - -# Notre itérateur est un objet qui se rappelle de notre position quand on le traverse. -# On passe à l'élément suivant avec "next()". -next(our_iterator) #=> "one" - -# Il garde son état quand on itère. -next(our_iterator) #=> "two" -next(our_iterator) #=> "three" - -# Après que l'itérateur a retourné toutes ses données, il lève une exception StopIterator -next(our_iterator) # Lève une StopIteration - -# On peut mettre tous les éléments d'un itérateur dans une liste avec list() -list(filled_dict.keys()) #=> Returns ["one", "two", "three"] - - -#################################################### -## 4. Fonctions -#################################################### - -# On utilise "def" pour créer des fonctions -def add(x, y): - print("x est {} et y est {}".format(x, y)) - return x + y # On retourne une valeur avec return - -# Appel d'une fonction avec des paramètres : -add(5, 6) # => affiche "x est 5 et y est 6" et retourne 11 - -# Une autre manière d'appeler une fonction : avec des arguments -add(y=6, x=5) # Les arguments peuvent être dans n'importe quel ordre. - -# Définir une fonction qui prend un nombre variable d'arguments -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - -# On peut aussi définir une fonction qui prend un nombre variable de paramètres. -def keyword_args(**kwargs): - return kwargs - -# Appelons la pour voir ce qu'il se passe : -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# On peut aussi faire les deux à la fois : -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) affiche: - (1, 2) - {"a": 3, "b": 4} -""" - -# En appelant des fonctions, on peut aussi faire l'inverse : -# utiliser * pour étendre un tuple de paramètres -# et ** pour étendre un dictionnaire d'arguments. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # équivalent à foo(1, 2, 3, 4) -all_the_args(**kwargs) # équivalent à foo(a=3, b=4) -all_the_args(*args, **kwargs) # équivalent à foo(1, 2, 3, 4, a=3, b=4) - -# Retourne plusieurs valeurs (avec un tuple) -def swap(x, y): - return y, x # Retourne plusieurs valeurs avec un tuple sans parenthèses. - # (Note: on peut aussi utiliser des parenthèses) - -x = 1 -y = 2 -x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # Là aussi, rien ne nous empêche d'ajouter des parenthèses - -# Portée des fonctions : -x = 5 - -def setX(num): - # La variable locale x n'est pas la même que la variable globale x - x = num # => 43 - print (x) # => 43 - -def setGlobalX(num): - global x - print (x) # => 5 - x = num # la variable globale x est maintenant 6 - print (x) # => 6 - -setX(43) -setGlobalX(6) - - -# Python a des fonctions de première classe -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# Mais aussi des fonctions anonymes -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# TODO - Fix for iterables -# Il y a aussi des fonctions de base -map(add_10, [1, 2, 3]) # => [11, 12, 13] -map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] - -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] - -# On peut utiliser les compréhensions de listes pour de jolies maps et filtres. -# Une compréhension de liste stocke la sortie comme une liste qui peut elle même être une liste imbriquée. -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -#################################################### -## 5. Classes -#################################################### - - -# On utilise l'opérateur "class" pour définir une classe -class Human: - - # Un attribut de la classe. Il est partagé par toutes les instances de la classe. - species = "H. sapiens" - - # L'initialiseur de base. Il est appelé quand la classe est instanciée. - # Note : les doubles underscores au début et à la fin sont utilisés pour - # les fonctions et attributs utilisés par Python mais contrôlés par l'utilisateur. - # Les méthodes (ou objets ou attributs) comme: __init__, __str__, - # __repr__ etc. sont appelés méthodes magiques. - # Vous ne devriez pas inventer de noms de ce style. - def __init__(self, name): - # Assigner l'argument à l'attribut de l'instance - self.name = name - - # Une méthode de l'instance. Toutes prennent "self" comme premier argument. - def say(self, msg): - return "{name}: {message}".format(name=self.name, message=msg) - - # Une méthode de classe est partagée avec entre les instances - # Ils sont appelés avec la classe comme premier argument - @classmethod - def get_species(cls): - return cls.species - - # Une méthode statique est appelée sans référence à une instance ni à une classe. - @staticmethod - def grunt(): - return "*grunt*" - - -# Instantier une classe -i = Human(name="Ian") -print(i.say("hi")) # affiche "Ian: hi" - -j = Human("Joel") -print(j.say("hello")) # affiche "Joel: hello" - -# Appeller notre méthode de classe -i.get_species() # => "H. sapiens" - -# Changer les attributs partagés -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" - -# Appeller la méthode statique -Human.grunt() # => "*grunt*" - - -#################################################### -## 6. Modules -#################################################### - -# On peut importer des modules -import math -print(math.sqrt(16)) # => 4.0 - -# On peut importer des fonctions spécifiques d'un module -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# On peut importer toutes les fonctions d'un module -# Attention: ce n'est pas recommandé. -from math import * - -# On peut raccourcir un nom de module -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Les modules Python sont juste des fichiers Python. -# Vous pouvez écrire les vôtres et les importer. Le nom du module -# est le nom du fichier. - -# On peut voir quels fonctions et objets un module définit -import math -dir(math) - - -#################################################### -## 7. Avancé -#################################################### - -# Les générateurs aident à faire du code paresseux (lazy) -def double_numbers(iterable): - for i in iterable: - yield i + i - -# Un générateur crée des valeurs à la volée. -# Au lieu de générer et retourner toutes les valeurs en une fois, il en crée une à chaque -# itération. Cela signifie que les valeurs supérieures à 30 ne seront pas traîtées par -# double_numbers. -# Note : range est un générateur aussi. -# Créer une liste 1-900000000 prendrait beaucoup de temps -# On met un underscore à la fin d'un nom de variable normalement réservé par Python. -range_ = range(1, 900000000) -# Double tous les nombres jusqu'à ce qu'un nombre >=30 soit trouvé -for i in double_numbers(range_): - print(i) - if i >= 30: - break - - -# Decorateurs -# Dans cet exemple, beg enveloppe say -# Beg appellera say. Si say_please vaut True le message retourné sera changé -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please - - -print(say()) # affiche Can you buy me a beer? -print(say(say_please=True)) # affiche Can you buy me a beer? Please! I am poor :( -``` - -## Prêt pour encore plus ? - -### En ligne et gratuit (en anglais) - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) - -### En ligne et gratuit (en français) - -* [Le petit guide des batteries à découvrir](https://he-arc.github.io/livre-python/) - -### Livres (en anglais) - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/it-it/python-it.html.markdown b/it-it/python-it.html.markdown new file mode 100644 index 00000000..04f78cff --- /dev/null +++ b/it-it/python-it.html.markdown @@ -0,0 +1,1016 @@ +--- +language: python3 +filename: learnpython3-it.py +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["evuez", "http://github.com/evuez"] + - ["Rommel Martinez", "https://ebzzry.io"] +translators: + - ["Draio", "http://github.com/Draio/"] + - ["Ale46", "http://github.com/Ale46/"] + - ["Tommaso Pifferi", "http://github.com/neslinesli93/"] +lang: it-it +--- + +Python è stato creato da Guido Van Rossum agli inizi degli anni 90. Oggi è uno dei più popolari linguaggi esistenti. Mi sono innamorato di Python per la sua chiarezza sintattica. E' sostanzialmente pseudocodice eseguibile. + +Feedback sono altamente apprezzati! Potete contattarmi su [@louiedinh](http://twitter.com/louiedinh) oppure [at] [google's email service] + +Nota: Questo articolo è riferito a Python 3 in modo specifico. Se volete avete la necessità di utilizzare Python 2.7 potete consultarla [qui](https://learnxinyminutes.com/docs/it-it/python-it/) + +```python + +# I commenti su una sola linea iniziano con un cancelletto + + +""" Più stringhe possono essere scritte + usando tre ", e sono spesso usate + come documentazione +""" + +#################################################### +## 1. Tipi di dati primitivi ed Operatori +#################################################### + +# Ci sono i numeri +3 # => 3 + +# La matematica è quello che vi aspettereste +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 + +# Risultato della divisione intera troncata sia in positivo che in negativo +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Il risultato di una divisione è sempre un numero decimale (float) +10.0 / 3 # => 3.3333333333333335 + +# Operazione Modulo +7 % 3 # => 1 + +# Elevamento a potenza (x alla y-esima potenza) +2**3 # => 8 + +# Forzare le precedenze con le parentesi +(1 + 3) * 2 # => 8 + +# I valori booleani sono primitive del linguaggio (nota la maiuscola) +True +False + +# nega con not +not True # => False +not False # => True + +# Operatori Booleani +# Nota "and" e "or" sono case-sensitive +True and False # => False +False or True # => True + +# Note sull'uso di operatori Bool con interi +# False è 0 e True è 1 +# Non confonderti tra bool(ints) e le operazioni bitwise and/or (&,|) +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True +-5 != False != True #=> True + +# Uguaglianza è == +1 == 1 # => True +2 == 1 # => False + +# Disuguaglianza è != +1 != 1 # => False +2 != 1 # => True + +# Altri confronti +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# I confronti possono essere concatenati! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# ('is' vs. '==') +# 'is' controlla se due variabili si riferiscono allo stesso oggetto +# '==' controlla se gli oggetti puntati hanno lo stesso valore. +a = [1, 2, 3, 4] # a punta ad una nuova lista [1, 2, 3, 4] +b = a # b punta a ciò a cui punta a +b is a # => True, a e b puntano allo stesso oggeto +b == a # => True, gli oggetti di a e b sono uguali +b = [1, 2, 3, 4] # b punta ad una nuova lista [1, 2, 3, 4] +b is a # => False, a e b non puntano allo stesso oggetto +b == a # => True, gli oggetti di a e b sono uguali + +# Le stringhe sono create con " o ' +"Questa è una stringa." +'Anche questa è una stringa.' + +# Anche le stringhe possono essere sommate! Ma cerca di non farlo. +"Hello " + "world!" # => "Hello world!" +# Le stringhe (ma non le variabili contenenti stringhe) possono essere +# sommate anche senza '+' +"Hello " "world!" # => "Hello world!" + +# Una stringa può essere considerata come una lista di caratteri +"Questa è una stringa"[0] # => 'Q' + +# Puoi conoscere la lunghezza di una stringa +len("Questa è una stringa") # => 20 + +# .format può essere usato per formattare le stringhe, in questo modo: +"{} possono essere {}".format("Le stringhe", "interpolate") # => "Le stringhe possono essere interpolate" + +# Puoi ripetere gli argomenti di formattazione per risparmiare un po' di codice +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# Puoi usare dei nomi se non vuoi contare gli argomenti +"{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="le lasagne") # => "Bob vuole mangiare le lasagne" + +# Se il tuo codice Python 3 necessita di eseguire codice Python 2.x puoi ancora +# utilizzare il vecchio stile di formattazione: +"%s possono essere %s nel %s modo" % ("Le stringhe", "interpolate", "vecchio") # => "Le stringhe possono essere interpolate nel vecchio modo" + +# None è un oggetto +None # => None + +# Non usare il simbolo di uguaglianza "==" per comparare oggetti a None +# Usa "is" invece +"etc" is None # => False +None is None # => True + +# None, 0, e stringhe/liste/dizionari/tuple vuoti vengono considerati +# falsi (False). Tutti gli altri valori sono considerati veri (True). +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False +bool(()) # => False + +#################################################### +## 2. Variabili e Collections +#################################################### + +# Python ha una funzione per scrivere (sul tuo schermo) +print("Sono Python. Piacere di conoscerti!") # => Sono Python. Piacere di conoscerti! + +# Di default la funzione print() scrive e va a capo aggiungendo un carattere +# newline alla fine della stringa. È possibile utilizzare l'argomento opzionale +# end per cambiare quest'ultimo carattere aggiunto. +print("Hello, World", end="!") # => Hello, World! + +# Un modo semplice per ricevere dati in input dalla riga di comando +variabile_stringa_input = input("Inserisci del testo: ") # Restituisce i dati letti come stringa +# Nota: Nelle precedenti vesioni di Python, il metodo input() +# era chiamato raw_input() + +# Non c'è bisogno di dichiarare una variabile per assegnarle un valore +# Come convenzione, per i nomi delle variabili, si utilizzano i caratteri +# minuscoli separati, se necessario, da underscore +some_var = 5 +some_var # => 5 + +# Accedendo ad una variabile non precedentemente assegnata genera un'eccezione. +# Dai un'occhiata al Control Flow per imparare di più su come gestire +# le eccezioni. +some_unknown_var # Genera un errore di nome + +# if può essere usato come un'espressione +# È l'equivalente dell'operatore ternario in C +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Le liste immagazzinano sequenze +li = [] +# Puoi partire con una lista pre-riempita +other_li = [4, 5, 6] + +# Aggiungere alla fine di una lista con append +li.append(1) # li ora è [1] +li.append(2) # li ora è [1, 2] +li.append(4) # li ora è [1, 2, 4] +li.append(3) # li ora è [1, 2, 4, 3] +# Rimuovi dalla fine della lista con pop +li.pop() # => 3 e li ora è [1, 2, 4] +# Rimettiamolo a posto +li.append(3) # li ora è [1, 2, 4, 3] di nuovo. + +# Accedi ad una lista come faresti con un array +li[0] # => 1 +# Guarda l'ultimo elemento +li[-1] # => 3 + +# Guardare al di fuori dei limiti genera un IndexError +li[4] # Genera IndexError + +# Puoi guardare gli intervalli con la sintassi slice (a fetta). +# (E' un intervallo chiuso/aperto per voi tipi matematici.) +li[1:3] # => [2, 4] +# Ometti l'inizio +li[2:] # => [4, 3] +# Ometti la fine +li[:3] # => [1, 2, 4] +# Seleziona ogni seconda voce +li[::2] # =>[1, 4] +# Copia al contrario della lista +li[::-1] # => [3, 4, 2, 1] +# Usa combinazioni per fare slices avanzate +# li[inizio:fine:passo] + +# Crea una copia (one layer deep copy) usando la sintassi slices +li2 = li[:] # => li2 = [1, 2, 4, 3] ma (li2 is li) risulterà falso. + +# Rimuovi arbitrariamente elementi da una lista con "del" +del li[2] # li è ora [1, 2, 3] + +# Rimuove la prima occorrenza di un elemento +li.remove(2) # Ora li è [1, 3, 4, 5, 6] +li.remove(2) # Emette un ValueError, poichè 2 non è contenuto nella lista + +# Inserisce un elemento all'indice specificato +li.insert(1, 2) # li è di nuovo [1, 2, 3, 4, 5, 6] + + Ritorna l'indice della prima occorrenza dell'elemento fornito +li.index(2) # => 1 +li.index(7) # Emette un ValueError, poichè 7 non è contenuto nella lista + +# Puoi sommare le liste +# Nota: i valori per li e per other_li non vengono modificati. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Concatena le liste con "extend()" +li.extend(other_li) # Adesso li è [1, 2, 3, 4, 5, 6] + +# Controlla l'esistenza di un valore in una lista con "in" +1 in li # => True + +# Esamina la lunghezza con "len()" +len(li) # => 6 + + +# Le tuple sono come le liste ma immutabili. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Genera un TypeError + +# Note that a tuple of length one has to have a comma after the last element but +# tuples of other lengths, even zero, do not. +type((1)) # => +type((1,)) # => +type(()) # => + +# Puoi fare tutte queste cose da lista anche sulle tuple +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Puoi scompattare le tuple (o liste) in variabili +a, b, c = (1, 2, 3) # a è ora 1, b è ora 2 e c è ora 3 +d, e, f = 4, 5, 6 # puoi anche omettere le parentesi +# Le tuple sono create di default se non usi le parentesi +g = 4, 5, 6 # => (4, 5, 6) +# Guarda come è facile scambiare due valori +e, d = d, e # d è ora 5 ed e è ora 4 + +# I dizionari memorizzano insiemi di dati indicizzati da nomi arbitrari (chiavi) +empty_dict= {} +# Questo è un dizionario pre-caricato +filled_dict = {"uno": 1, "due": 2, "tre": 3} + +# Nota: le chiavi dei dizionari devono essere di tipo immutabile. Questo per +# assicurare che le chiavi possano essere convertite in calori hash costanti +# per un risposta più veloce. +invalid_dict = {[1,2,3]: "123"} # => Emette un TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # I valori, invece, possono essere di qualunque tipo + +# Accedi ai valori indicando la chiave tra [] +filled_dict["uno"] # => 1 + +# Puoi ottenere tutte le chiavi di un dizionario con "keys()" +# (come oggetto iterabile). Per averle in formato lista è necessario +# utilizzare list(). +# Nota - Nei dizionari l'ordine delle chiavi non è garantito. +# Il tuo risultato potrebbe non essere uguale a questo. +list(filled_dict.keys()) # => ["tre", "due", "uno"] + + +# Puoi ottenere tutti i valori di un dizionario con "values()" +# (come oggetto iterabile). +# Anche in questo caso, er averle in formato lista, è necessario utilizzare list() +# Anche in questo caso, come per le chiavi, l'ordine non è garantito +list(filled_dict.values()) # => [3, 2, 1] + +# Controlla l'esistenza delle chiavi in un dizionario con "in" +"uno" in filled_dict # => True +1 in filled_dict # => False + +# Cercando una chiave non esistente genera un KeyError +filled_dict["quattro"] # KeyError + +# Usa il metodo "get()" per evitare KeyError +filled_dict.get("uno") # => 1 +filled_dict.get("quattro") # => None +# Il metodo get supporta un argomento di default quando il valore è mancante +filled_dict.get("uno", 4) # => 1 +filled_dict.get("quattro", 4) # => 4 + + +# "setdefault()" inserisce un valore per una chiave in un dizionario +# solo se la chiave data non è già presente +filled_dict.setdefault("cinque", 5) # filled_dict["cinque"] viene impostato a 5 +filled_dict.setdefault("cinque", 6) # filled_dict["cinque"] rimane 5 + +# Aggiungere una coppia chiave->valore a un dizionario +filled_dict.update({"quattro":4}) # => {"uno": 1, "due": 2, "tre": 3, "quattro": 4} +filled_dict["quattro"] = 4 # un altro modo pe aggiungere a un dizionario + +# Rimuovi una chiave da un dizionario con del +del filled_dict["uno"] # Rimuove la chiave "uno" dal dizionario + +# Da Python 3.5 puoi anche usare ulteriori opzioni di spacchettamento +{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} +{'a': 1, **{'a': 2}} # => {'a': 2} + +# I set sono come le liste ma non possono contenere doppioni +empty_set = set() +# Inizializza un "set()" con un dei valori. Sì, sembra un dizionario. +some_set = {1, 1, 2, 2, 3, 4} # set_nuovo è {1, 2, 3, 4} + +# Come le chiavi di un dizionario, gli elementi di un set devono essere +# di tipo immutabile +invalid_set = {[1], 1} # => Genera un "TypeError: unhashable type: 'list'"" +valid_set = {(1,), 1} + +# Aggiungere uno o più elementi ad un set +some_set.add(5) # some_set ora è {1, 2, 3, 4, 5} + +# Fai intersezioni su un set con & +other_set = {3, 4, 5, 6} +some_set & other_set # => {3, 4, 5} + +# Fai unioni su set con | +some_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Fai differenze su set con - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Effettua la differenza simmetrica con ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Controlla se il set a sinistra contiene quello a destra +{1, 2} >= {1, 2, 3} # => False + +# Controlla se il set a sinistra è un sottoinsieme di quello a destra +{1, 2} <= {1, 2, 3} # => True + +# Controlla l'esistenza in un set con in +2 in some_set # => True +10 in some_set # => False + + + +#################################################### +## 3. Control Flow e oggetti Iterabili +#################################################### + +# Dichiariamo una variabile +some_var = 5 + +# Questo è un controllo if. L'indentazione è molto importante in python! +# Come convenzione si utilizzano quattro spazi, non la tabulazione. +# Il seguente codice stampa "some_var è minore di 10" +if some_var > 10: + print("some_var è maggiore di 10") +elif some_var < 10: # La clausolo elif è opzionale + print("some_var è minore di 10") +else: # Anche else è opzionale + print("some_var è 10.") + +""" +I cicli for iterano sulle liste, cioè ripetono un codice per ogni elemento +di una lista. +Il seguente codice scriverà: + cane è un mammifero + gatto è un mammifero + topo è un mammifero +""" +for animale in ["cane", "gatto", "topo"]: + # Puoi usare format() per interpolare le stringhe formattate. + print("{} è un mammifero".format(animale)) + +""" +"range(numero)" restituisce una lista di numeri da zero al numero dato +Il seguente codice scriverà: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(lower, upper)" restituisce una lista di numeri dal più piccolo (lower) +al più grande (upper). +Il seguente codice scriverà: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(lower, upper, step)" rrestituisce una lista di numeri dal più piccolo +(lower) al più grande (upper), incrementando del valore step. +Se step non è indicato, avrà come valore di default 1. +Il seguente codice scriverà: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) +""" + +I cicli while vengono eseguiti finchè una condizione viene a mancare +Il seguente codice scriverà: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Forma compatta per x = x + 1 + +# Gestione delle eccezioni con un blocco try/except +try: + # Usa "raise" per generare un errore + raise IndexError("Questo è un IndexError") +except IndexError as e: + pass # Pass è solo una non-operazione. Solitamente vorrai rimediare all'errore. +except (TypeError, NameError): + pass # Eccezioni multiple possono essere gestite tutte insieme, se necessario. +else: # Clausola opzionale al blocco try/except. Deve essere dopo tutti i blocchi except + print("Tutto ok!") # Viene eseguita solo se il codice dentro try non genera eccezioni +finally: # Eseguito sempre + print("Possiamo liberare risorse qui") + +# Se ti serve solo un try/finally, per liberare risorse, puoi usare il metodo with +with open("myfile.txt") as f: + for line in f: + print(line) + +# In Python qualunque oggetto in grado di essere trattato come una +# sequenza è definito un oggetto Iterable (itarabile). +# L'oggetto restituito da una funzione range è un iterabile. + +filled_dict = {"uno": 1, "due": 2, "tre": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => dict_keys(['uno', 'due', 'tre']). +# Questo è un oggetto che implementa la nostra interfaccia Iterable. + +# È possibile utilizzarlo con i loop: +for i in our_iterable: + print(i) # Scrive uno, due, tre + +# Tuttavia non possiamo recuperarne i valori tramite indice. +our_iterable[1] # Genera un TypeError + +# Un oggetto iterabile è in grado di generare un iteratore +our_iterator = iter(our_iterable) + +# L'iteratore è un oggetto che ricorda il suo stato mentro lo si "attraversa" +# Possiamo accedere al successivo elemento con "next()". +next(our_iterator) # => "uno" + +# Mantiene il suo stato mentro eseguiamo l'iterazione +next(our_iterator) # => "due" +next(our_iterator) # => "tre" + +# Dopo che un iteratore ha restituito tutti i suoi dati, genera +# un'eccezione StopIteration +next(our_iterator) # Raises StopIteration + +# Puoi prendere tutti gli elementi di un iteratore utilizzando list(). +list(filled_dict.keys()) # => Returns ["one", "two", "three"] + + + +#################################################### +## 4. Funzioni +#################################################### + +# Usa "def" per creare nuove funzioni +def aggiungi(x, y): + print("x è {} e y è {}".format(x, y)) // Scrive i valori formattati in una stringa + return x + y # Restituisce la somma dei valori con il metodo return + +# Chiamare funzioni con parametri +aggiungi(5, 6) # => scrive "x è 5 e y è 6" e restituisce 11 + +# Un altro modo per chiamare funzioni è con parole chiave come argomenti +aggiungi(y=6, x=5) # In questo modo non è necessario rispettare l'ordine degli argomenti + +# Puoi definire funzioni che accettano un numero non definito di argomenti +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# Puoi definire funzioni che accettano un numero variabile di parole chiave +# come argomento, che saranno interpretati come un dizionario usando ** +def keyword_args(**kwargs): + return kwargs + +# Chiamiamola per vedere cosa succede +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# Puoi farle entrambi in una volta, se ti va +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) stampa: + (1, 2) + {"a": 3, "b": 4} +""" + +# Quando chiami funzioni, puoi fare l'opposto di args/kwargs! +# Usa * per sviluppare gli argomenti posizionale ed usa ** per +# espandere gli argomenti parola chiave +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalente a foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalente a foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4) + + +# Restituire valori multipli (with tuple assignments) +def swap(x, y): + return y, x # Restituisce valori multipli come tupla senza parentesi + # (Nota: le parentesi sono state escluse ma possono essere messe) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Le parentesi sono state escluse ma possono essere incluse. + +# Funzioni - Visibilità delle variabili (variable scope) +x = 5 + +def set_x(num): + # La variabile locale x non è la variabile globale x + x = num # => 43 + print(x) # => 43 + +def set_global_x(num): + global x + print(x) # => 5 + x = num # la variabile globable x è ora 6 + print(x) # => 6 + +set_x(43) +set_global_x(6) + + +# Python ha "first class functions" +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Ci sono anche funzioni anonime +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# È possibile creare "mappe" e "filtri" +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] + +list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] + +# Possiamo usare le "list comprehensions" per mappe e filtri +# Le "list comprehensions" memorizzano l'output come una lista che può essere +# di per sé una lista annidata +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# Puoi fare anche la comprensione di set e dizionari +{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +## 5. Modules +#################################################### + +# Puoi importare moduli +import math +print(math.sqrt(16)) # => 4.0 + +# Puoi ottenere specifiche funzione da un modulo +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Puoi importare tutte le funzioni da un modulo +# Attenzione: questo non è raccomandato +from math import * + +# Puoi abbreviare i nomi dei moduli +import math as m +math.sqrt(16) == m.sqrt(16) # => True + + +# I moduli di Python sono normali file python. Ne puoi +# scrivere di tuoi ed importarli. Il nome del modulo +# è lo stesso del nome del file. + +# Potete scoprire quali funzioni e attributi +# sono definiti in un modulo +import math +dir(math) + +# Se nella cartella corrente hai uno script chiamato math.py, +# Python caricherà quello invece del modulo math. +# Questo succede perchè la cartella corrente ha priorità +# sulle librerie standard di Python + +# Se hai uno script Python chiamato math.py nella stessa +# cartella del tua script, Python caricherà quello al posto del +# comune modulo math. +# Questo accade perché la cartella locale ha la priorità +# sulle librerie built-in di Python. + + +#################################################### +## 6. Classes +#################################################### + +# Usiamo l'istruzione "class" per creare una classe +class Human: + + # Un attributo della classe. E' condiviso tra tutte le istanze delle classe + species = "H. sapiens" + + # Si noti che i doppi underscore iniziali e finali denotano gli oggetti o + # attributi utilizzati da Python ma che vivono nel namespace controllato + # dall'utente + # Metodi, oggetti o attributi come: __init__, __str__, __repr__, etc. sono + # chiamati metodi speciali (o talvolta chiamati "dunder methods"). + # Non dovresti inventare tali nomi da solo. + + def __init__(self, name): + # Assegna l'argomento all'attributo name dell'istanza + self.name = name + + # Inizializza una proprietà + self._age = 0 + + # Un metodo dell'istanza. Tutti i metodi prendo "self" come primo argomento + def say(self, msg): + print("{name}: {message}".format(name=self.name, message=msg)) + + # Un altro metodo dell'istanza + def sing(self): + return 'yo... yo... microphone check... one two... one two...' + + # Un metodo della classe è condiviso fra tutte le istanze + # Sono chiamati con la classe chiamante come primo argomento + @classmethod + def get_species(cls): + return cls.species + + # Un metodo statico è chiamato senza classe o istanza di riferimento + @staticmethod + def grunt(): + return "*grunt*" + + # Una property è come un metodo getter. + # Trasforma il metodo age() in un attributo in sola lettura, che ha + # lo stesso nome + # In Python non c'è bisogno di scrivere futili getter e setter. + @property + def age(self): + return self._age + + # Questo metodo permette di modificare una property + @age.setter + def age(self, age): + self._age = age + + # Questo metodo permette di cancellare una property + @age.deleter + def age(self): + del self._age + +# Quando l'interprete Python legge un sorgente esegue tutto il suo codice. +# Questo controllo su __name__ assicura che questo blocco di codice venga +# eseguito solo quando questo modulo è il programma principale. + +if __name__ == '__main__': + # Crea un'istanza della classe + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # i e j sono istanze del tipo Human, o in altre parole sono oggetti Human + + # Chiama un metodo della classe + i.say(i.get_species()) # "Ian: H. sapiens" + # Cambia l'attributo condiviso + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # Chiama un metodo statico + print(Human.grunt()) # => "*grunt*" + + # Non è possibile chiamare il metodo statico con l'istanza dell'oggetto + # poiché i.grunt() metterà automaticamente "self" (l'oggetto i) + # come argomento + print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given + + # Aggiorna la property (age) di questa istanza + i.age = 42 + # Leggi la property + i.say(i.age) # => "Ian: 42" + j.say(j.age) # => "Joel: 0" + # Cancella la property + del i.age + i.age # => questo genererà un AttributeError + + +#################################################### +## 6.1 Ereditarietà (Inheritance) +#################################################### + +# L'ereditarietà consente di definire nuove classi figlio che ereditano metodi e +# variabili dalla loro classe genitore. + +# Usando la classe Human definita sopra come classe base o genitore, possiamo +# definire una classe figlia, Superhero, che erediterà le variabili di classe +# come "species", "name" e "age", così come i metodi, come "sing" e "grunt", +# dalla classe Human, ma potrà anche avere le sue proprietà uniche. + +# Per importare le funzioni da altri file usa il seguente formato +# from "nomefile-senza-estensione" import "funzione-o-classe" + +from human import Human + +# Specificare le classi genitore come parametri della definizione della classe +class Superhero(Human): + + # Se la classe figlio deve ereditare tutte le definizioni del genitore + # senza alcuna modifica, puoi semplicemente usare la parola chiave "pass" + # (e nient'altro) + + #Le classi figlio possono sovrascrivere gli attributi dei loro genitori + species = 'Superhuman' + + # Le classi figlie ereditano automaticamente il costruttore della classe + # genitore, inclusi i suoi argomenti, ma possono anche definire ulteriori + # argomenti o definizioni e sovrascrivere i suoi metodi (compreso il + # costruttore della classe). + # Questo costruttore eredita l'argomento "nome" dalla classe "Human" e + # aggiunge gli argomenti "superpowers" e "movie": + + def __init__(self, name, movie=False, + superpowers=["super strength", "bulletproofing"]): + + # aggiungi ulteriori attributi della classe + self.fictional = True + self.movie = movie + self.superpowers = superpowers + + # La funzione "super" ti consente di accedere ai metodi della classe + # genitore che sono stati sovrascritti dalla classe figlia, + # in questo caso il metodo __init__. + # Il seguente codice esegue il costruttore della classe genitore: + super().__init__(name) + + # Sovrascrivere il metodo "sing" + def sing(self): + return 'Dun, dun, DUN!' + + # Aggiungi un ulteriore metodo dell'istanza + def boast(self): + for power in self.superpowers: + print("I wield the power of {pow}!".format(pow=power)) + + +if __name__ == '__main__': + sup = Superhero(name="Tick") + + # Controllo del tipo di istanza + if isinstance(sup, Human): + print('I am human') + if type(sup) is Superhero: + print('I am a superhero') + + # Ottieni il "Method Resolution search Order" usato sia da getattr () + # che da super (). Questo attributo è dinamico e può essere aggiornato + print(Superhero.__mro__) # => (, + # => , ) + + # Esegui il metodo principale ma utilizza il proprio attributo di classe + print(sup.get_species()) # => Superhuman + + # Esegui un metodo che è stato sovrascritto + print(sup.sing()) # => Dun, dun, DUN! + + # Esegui un metodo di Human + sup.say('Spoon') # => Tick: Spoon + + # Esegui un metodo che esiste solo in Superhero + sup.boast() # => I wield the power of super strength! + # => I wield the power of bulletproofing! + + # Attributo di classe ereditato + sup.age = 31 + print(sup.age) # => 31 + + # Attributo che esiste solo in Superhero + print('Am I Oscar eligible? ' + str(sup.movie)) + +#################################################### +## 6.2 Ereditarietà multipla +#################################################### + +# Un'altra definizione di classe +# bat.py +class Bat: + + species = 'Baty' + + def __init__(self, can_fly=True): + self.fly = can_fly + + # Questa classe ha anche un metodo "say" + def say(self, msg): + msg = '... ... ...' + return msg + + # E anche un suo metodo personale + def sonar(self): + return '))) ... (((' + +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) + +# Definizione di classe che eredita da Superhero e Bat +# superhero.py +from superhero import Superhero +from bat import Bat + +# Definisci Batman come classe figlia che eredita sia da Superhero che da Bat +class Batman(Superhero, Bat): + + def __init__(self, *args, **kwargs): + # In genere per ereditare gli attributi devi chiamare super: + # super(Batman, self).__init__(*args, **kwargs) + # Ma qui abbiamo a che fare con l'ereditarietà multipla, e super() + # funziona solo con la successiva classe nell'elenco MRO. + # Quindi, invece, chiamiamo esplicitamente __init__ per tutti gli + # antenati. L'uso di *args e **kwargs consente di passare in modo + # pulito gli argomenti, con ciascun genitore che "sbuccia un + # livello della cipolla". + Superhero.__init__(self, 'anonymous', movie=True, + superpowers=['Wealthy'], *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # sovrascrivere il valore per l'attributo name + self.name = 'Sad Affleck' + + def sing(self): + return 'nan nan nan nan nan batman!' + + +if __name__ == '__main__': + sup = Batman() + + # Ottieni il "Method Resolution search Order" utilizzato da getattr() e super(). + # Questo attributo è dinamico e può essere aggiornato + print(Batman.__mro__) # => (, + # => , + # => , + # => , ) + + # Esegui il metodo del genitore ma utilizza il proprio attributo di classe + print(sup.get_species()) # => Superhuman + + # Esegui un metodo che è stato sovrascritto + print(sup.sing()) # => nan nan nan nan nan batman! + + # Esegui un metodo da Human, perché l'ordine di ereditarietà è importante + sup.say('I agree') # => Sad Affleck: I agree + + # Esegui un metodo che esiste solo nel 2o antenato + print(sup.sonar()) # => ))) ... ((( + + # Attributo di classe ereditato + sup.age = 100 + print(sup.age) # => 100 + + # Attributo ereditato dal secondo antenato il cui valore predefinito + # è stato ignorato. + print('Can I fly? ' + str(sup.fly)) # => Can I fly? False + + + +#################################################### +## 7. Advanced +#################################################### + +# I generatori ti aiutano a creare codice pigro (lazy code). +# Codice che darà un risultato solo quando sarà "valutato" +def double_numbers(iterable): + for i in iterable: + yield i + i + +# I generatori sono efficienti in termini di memoria perché caricano +# solo i dati necessari per elaborare il valore successivo nell'iterabile. +# Ciò consente loro di eseguire operazioni su intervalli di valori +# altrimenti proibitivi. +# NOTA: `range` sostituisce` xrange` in Python 3. +for i in double_numbers(range(1, 900000000)): # `range` is a generator. + print(i) + if i >= 30: + break + +# Proprio come è possibile creare una "list comprehension", è possibile +# creare anche delle "generator comprehensions". +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # prints -1 -2 -3 -4 -5 to console/terminal + +# Puoi anche trasmettere una "generator comprehensions" direttamente +# ad un elenco. +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + + +# Decoratori +# In questo esempio "beg" avvolge/wrappa "say". +# Se say_please è True, cambierà il messaggio restituito. +from functools import wraps + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Per favore! Sono povero :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Puoi comprarmi una birra?" + return msg, say_please + + +print(say()) # Puoi comprarmi una birra? +print(say(say_please=True)) # Puoi comprarmi una birra? Per favore! Sono povero :( +``` + +## Pronto per qualcosa di più? + +### Gratis Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) +* [Dive Into Python 3](http://www.diveintopython3.net/index.html) +* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/it-it/python3-it.html.markdown b/it-it/python3-it.html.markdown deleted file mode 100644 index 04f78cff..00000000 --- a/it-it/python3-it.html.markdown +++ /dev/null @@ -1,1016 +0,0 @@ ---- -language: python3 -filename: learnpython3-it.py -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] - - ["evuez", "http://github.com/evuez"] - - ["Rommel Martinez", "https://ebzzry.io"] -translators: - - ["Draio", "http://github.com/Draio/"] - - ["Ale46", "http://github.com/Ale46/"] - - ["Tommaso Pifferi", "http://github.com/neslinesli93/"] -lang: it-it ---- - -Python è stato creato da Guido Van Rossum agli inizi degli anni 90. Oggi è uno dei più popolari linguaggi esistenti. Mi sono innamorato di Python per la sua chiarezza sintattica. E' sostanzialmente pseudocodice eseguibile. - -Feedback sono altamente apprezzati! Potete contattarmi su [@louiedinh](http://twitter.com/louiedinh) oppure [at] [google's email service] - -Nota: Questo articolo è riferito a Python 3 in modo specifico. Se volete avete la necessità di utilizzare Python 2.7 potete consultarla [qui](https://learnxinyminutes.com/docs/it-it/python-it/) - -```python - -# I commenti su una sola linea iniziano con un cancelletto - - -""" Più stringhe possono essere scritte - usando tre ", e sono spesso usate - come documentazione -""" - -#################################################### -## 1. Tipi di dati primitivi ed Operatori -#################################################### - -# Ci sono i numeri -3 # => 3 - -# La matematica è quello che vi aspettereste -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7.0 - -# Risultato della divisione intera troncata sia in positivo che in negativo -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # works on floats too --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Il risultato di una divisione è sempre un numero decimale (float) -10.0 / 3 # => 3.3333333333333335 - -# Operazione Modulo -7 % 3 # => 1 - -# Elevamento a potenza (x alla y-esima potenza) -2**3 # => 8 - -# Forzare le precedenze con le parentesi -(1 + 3) * 2 # => 8 - -# I valori booleani sono primitive del linguaggio (nota la maiuscola) -True -False - -# nega con not -not True # => False -not False # => True - -# Operatori Booleani -# Nota "and" e "or" sono case-sensitive -True and False # => False -False or True # => True - -# Note sull'uso di operatori Bool con interi -# False è 0 e True è 1 -# Non confonderti tra bool(ints) e le operazioni bitwise and/or (&,|) -0 and 2 # => 0 --5 or 0 # => -5 -0 == False # => True -2 == True # => False -1 == True # => True --5 != False != True #=> True - -# Uguaglianza è == -1 == 1 # => True -2 == 1 # => False - -# Disuguaglianza è != -1 != 1 # => False -2 != 1 # => True - -# Altri confronti -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# I confronti possono essere concatenati! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# ('is' vs. '==') -# 'is' controlla se due variabili si riferiscono allo stesso oggetto -# '==' controlla se gli oggetti puntati hanno lo stesso valore. -a = [1, 2, 3, 4] # a punta ad una nuova lista [1, 2, 3, 4] -b = a # b punta a ciò a cui punta a -b is a # => True, a e b puntano allo stesso oggeto -b == a # => True, gli oggetti di a e b sono uguali -b = [1, 2, 3, 4] # b punta ad una nuova lista [1, 2, 3, 4] -b is a # => False, a e b non puntano allo stesso oggetto -b == a # => True, gli oggetti di a e b sono uguali - -# Le stringhe sono create con " o ' -"Questa è una stringa." -'Anche questa è una stringa.' - -# Anche le stringhe possono essere sommate! Ma cerca di non farlo. -"Hello " + "world!" # => "Hello world!" -# Le stringhe (ma non le variabili contenenti stringhe) possono essere -# sommate anche senza '+' -"Hello " "world!" # => "Hello world!" - -# Una stringa può essere considerata come una lista di caratteri -"Questa è una stringa"[0] # => 'Q' - -# Puoi conoscere la lunghezza di una stringa -len("Questa è una stringa") # => 20 - -# .format può essere usato per formattare le stringhe, in questo modo: -"{} possono essere {}".format("Le stringhe", "interpolate") # => "Le stringhe possono essere interpolate" - -# Puoi ripetere gli argomenti di formattazione per risparmiare un po' di codice -"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" - -# Puoi usare dei nomi se non vuoi contare gli argomenti -"{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="le lasagne") # => "Bob vuole mangiare le lasagne" - -# Se il tuo codice Python 3 necessita di eseguire codice Python 2.x puoi ancora -# utilizzare il vecchio stile di formattazione: -"%s possono essere %s nel %s modo" % ("Le stringhe", "interpolate", "vecchio") # => "Le stringhe possono essere interpolate nel vecchio modo" - -# None è un oggetto -None # => None - -# Non usare il simbolo di uguaglianza "==" per comparare oggetti a None -# Usa "is" invece -"etc" is None # => False -None is None # => True - -# None, 0, e stringhe/liste/dizionari/tuple vuoti vengono considerati -# falsi (False). Tutti gli altri valori sono considerati veri (True). -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False -bool(()) # => False - -#################################################### -## 2. Variabili e Collections -#################################################### - -# Python ha una funzione per scrivere (sul tuo schermo) -print("Sono Python. Piacere di conoscerti!") # => Sono Python. Piacere di conoscerti! - -# Di default la funzione print() scrive e va a capo aggiungendo un carattere -# newline alla fine della stringa. È possibile utilizzare l'argomento opzionale -# end per cambiare quest'ultimo carattere aggiunto. -print("Hello, World", end="!") # => Hello, World! - -# Un modo semplice per ricevere dati in input dalla riga di comando -variabile_stringa_input = input("Inserisci del testo: ") # Restituisce i dati letti come stringa -# Nota: Nelle precedenti vesioni di Python, il metodo input() -# era chiamato raw_input() - -# Non c'è bisogno di dichiarare una variabile per assegnarle un valore -# Come convenzione, per i nomi delle variabili, si utilizzano i caratteri -# minuscoli separati, se necessario, da underscore -some_var = 5 -some_var # => 5 - -# Accedendo ad una variabile non precedentemente assegnata genera un'eccezione. -# Dai un'occhiata al Control Flow per imparare di più su come gestire -# le eccezioni. -some_unknown_var # Genera un errore di nome - -# if può essere usato come un'espressione -# È l'equivalente dell'operatore ternario in C -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# Le liste immagazzinano sequenze -li = [] -# Puoi partire con una lista pre-riempita -other_li = [4, 5, 6] - -# Aggiungere alla fine di una lista con append -li.append(1) # li ora è [1] -li.append(2) # li ora è [1, 2] -li.append(4) # li ora è [1, 2, 4] -li.append(3) # li ora è [1, 2, 4, 3] -# Rimuovi dalla fine della lista con pop -li.pop() # => 3 e li ora è [1, 2, 4] -# Rimettiamolo a posto -li.append(3) # li ora è [1, 2, 4, 3] di nuovo. - -# Accedi ad una lista come faresti con un array -li[0] # => 1 -# Guarda l'ultimo elemento -li[-1] # => 3 - -# Guardare al di fuori dei limiti genera un IndexError -li[4] # Genera IndexError - -# Puoi guardare gli intervalli con la sintassi slice (a fetta). -# (E' un intervallo chiuso/aperto per voi tipi matematici.) -li[1:3] # => [2, 4] -# Ometti l'inizio -li[2:] # => [4, 3] -# Ometti la fine -li[:3] # => [1, 2, 4] -# Seleziona ogni seconda voce -li[::2] # =>[1, 4] -# Copia al contrario della lista -li[::-1] # => [3, 4, 2, 1] -# Usa combinazioni per fare slices avanzate -# li[inizio:fine:passo] - -# Crea una copia (one layer deep copy) usando la sintassi slices -li2 = li[:] # => li2 = [1, 2, 4, 3] ma (li2 is li) risulterà falso. - -# Rimuovi arbitrariamente elementi da una lista con "del" -del li[2] # li è ora [1, 2, 3] - -# Rimuove la prima occorrenza di un elemento -li.remove(2) # Ora li è [1, 3, 4, 5, 6] -li.remove(2) # Emette un ValueError, poichè 2 non è contenuto nella lista - -# Inserisce un elemento all'indice specificato -li.insert(1, 2) # li è di nuovo [1, 2, 3, 4, 5, 6] - - Ritorna l'indice della prima occorrenza dell'elemento fornito -li.index(2) # => 1 -li.index(7) # Emette un ValueError, poichè 7 non è contenuto nella lista - -# Puoi sommare le liste -# Nota: i valori per li e per other_li non vengono modificati. -li + other_li # => [1, 2, 3, 4, 5, 6] - -# Concatena le liste con "extend()" -li.extend(other_li) # Adesso li è [1, 2, 3, 4, 5, 6] - -# Controlla l'esistenza di un valore in una lista con "in" -1 in li # => True - -# Esamina la lunghezza con "len()" -len(li) # => 6 - - -# Le tuple sono come le liste ma immutabili. -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # Genera un TypeError - -# Note that a tuple of length one has to have a comma after the last element but -# tuples of other lengths, even zero, do not. -type((1)) # => -type((1,)) # => -type(()) # => - -# Puoi fare tutte queste cose da lista anche sulle tuple -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# Puoi scompattare le tuple (o liste) in variabili -a, b, c = (1, 2, 3) # a è ora 1, b è ora 2 e c è ora 3 -d, e, f = 4, 5, 6 # puoi anche omettere le parentesi -# Le tuple sono create di default se non usi le parentesi -g = 4, 5, 6 # => (4, 5, 6) -# Guarda come è facile scambiare due valori -e, d = d, e # d è ora 5 ed e è ora 4 - -# I dizionari memorizzano insiemi di dati indicizzati da nomi arbitrari (chiavi) -empty_dict= {} -# Questo è un dizionario pre-caricato -filled_dict = {"uno": 1, "due": 2, "tre": 3} - -# Nota: le chiavi dei dizionari devono essere di tipo immutabile. Questo per -# assicurare che le chiavi possano essere convertite in calori hash costanti -# per un risposta più veloce. -invalid_dict = {[1,2,3]: "123"} # => Emette un TypeError: unhashable type: 'list' -valid_dict = {(1,2,3):[1,2,3]} # I valori, invece, possono essere di qualunque tipo - -# Accedi ai valori indicando la chiave tra [] -filled_dict["uno"] # => 1 - -# Puoi ottenere tutte le chiavi di un dizionario con "keys()" -# (come oggetto iterabile). Per averle in formato lista è necessario -# utilizzare list(). -# Nota - Nei dizionari l'ordine delle chiavi non è garantito. -# Il tuo risultato potrebbe non essere uguale a questo. -list(filled_dict.keys()) # => ["tre", "due", "uno"] - - -# Puoi ottenere tutti i valori di un dizionario con "values()" -# (come oggetto iterabile). -# Anche in questo caso, er averle in formato lista, è necessario utilizzare list() -# Anche in questo caso, come per le chiavi, l'ordine non è garantito -list(filled_dict.values()) # => [3, 2, 1] - -# Controlla l'esistenza delle chiavi in un dizionario con "in" -"uno" in filled_dict # => True -1 in filled_dict # => False - -# Cercando una chiave non esistente genera un KeyError -filled_dict["quattro"] # KeyError - -# Usa il metodo "get()" per evitare KeyError -filled_dict.get("uno") # => 1 -filled_dict.get("quattro") # => None -# Il metodo get supporta un argomento di default quando il valore è mancante -filled_dict.get("uno", 4) # => 1 -filled_dict.get("quattro", 4) # => 4 - - -# "setdefault()" inserisce un valore per una chiave in un dizionario -# solo se la chiave data non è già presente -filled_dict.setdefault("cinque", 5) # filled_dict["cinque"] viene impostato a 5 -filled_dict.setdefault("cinque", 6) # filled_dict["cinque"] rimane 5 - -# Aggiungere una coppia chiave->valore a un dizionario -filled_dict.update({"quattro":4}) # => {"uno": 1, "due": 2, "tre": 3, "quattro": 4} -filled_dict["quattro"] = 4 # un altro modo pe aggiungere a un dizionario - -# Rimuovi una chiave da un dizionario con del -del filled_dict["uno"] # Rimuove la chiave "uno" dal dizionario - -# Da Python 3.5 puoi anche usare ulteriori opzioni di spacchettamento -{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} -{'a': 1, **{'a': 2}} # => {'a': 2} - -# I set sono come le liste ma non possono contenere doppioni -empty_set = set() -# Inizializza un "set()" con un dei valori. Sì, sembra un dizionario. -some_set = {1, 1, 2, 2, 3, 4} # set_nuovo è {1, 2, 3, 4} - -# Come le chiavi di un dizionario, gli elementi di un set devono essere -# di tipo immutabile -invalid_set = {[1], 1} # => Genera un "TypeError: unhashable type: 'list'"" -valid_set = {(1,), 1} - -# Aggiungere uno o più elementi ad un set -some_set.add(5) # some_set ora è {1, 2, 3, 4, 5} - -# Fai intersezioni su un set con & -other_set = {3, 4, 5, 6} -some_set & other_set # => {3, 4, 5} - -# Fai unioni su set con | -some_set | other_set # => {1, 2, 3, 4, 5, 6} - -# Fai differenze su set con - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Effettua la differenza simmetrica con ^ -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# Controlla se il set a sinistra contiene quello a destra -{1, 2} >= {1, 2, 3} # => False - -# Controlla se il set a sinistra è un sottoinsieme di quello a destra -{1, 2} <= {1, 2, 3} # => True - -# Controlla l'esistenza in un set con in -2 in some_set # => True -10 in some_set # => False - - - -#################################################### -## 3. Control Flow e oggetti Iterabili -#################################################### - -# Dichiariamo una variabile -some_var = 5 - -# Questo è un controllo if. L'indentazione è molto importante in python! -# Come convenzione si utilizzano quattro spazi, non la tabulazione. -# Il seguente codice stampa "some_var è minore di 10" -if some_var > 10: - print("some_var è maggiore di 10") -elif some_var < 10: # La clausolo elif è opzionale - print("some_var è minore di 10") -else: # Anche else è opzionale - print("some_var è 10.") - -""" -I cicli for iterano sulle liste, cioè ripetono un codice per ogni elemento -di una lista. -Il seguente codice scriverà: - cane è un mammifero - gatto è un mammifero - topo è un mammifero -""" -for animale in ["cane", "gatto", "topo"]: - # Puoi usare format() per interpolare le stringhe formattate. - print("{} è un mammifero".format(animale)) - -""" -"range(numero)" restituisce una lista di numeri da zero al numero dato -Il seguente codice scriverà: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -"range(lower, upper)" restituisce una lista di numeri dal più piccolo (lower) -al più grande (upper). -Il seguente codice scriverà: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -"range(lower, upper, step)" rrestituisce una lista di numeri dal più piccolo -(lower) al più grande (upper), incrementando del valore step. -Se step non è indicato, avrà come valore di default 1. -Il seguente codice scriverà: - 4 - 6 -""" -for i in range(4, 8, 2): - print(i) -""" - -I cicli while vengono eseguiti finchè una condizione viene a mancare -Il seguente codice scriverà: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Forma compatta per x = x + 1 - -# Gestione delle eccezioni con un blocco try/except -try: - # Usa "raise" per generare un errore - raise IndexError("Questo è un IndexError") -except IndexError as e: - pass # Pass è solo una non-operazione. Solitamente vorrai rimediare all'errore. -except (TypeError, NameError): - pass # Eccezioni multiple possono essere gestite tutte insieme, se necessario. -else: # Clausola opzionale al blocco try/except. Deve essere dopo tutti i blocchi except - print("Tutto ok!") # Viene eseguita solo se il codice dentro try non genera eccezioni -finally: # Eseguito sempre - print("Possiamo liberare risorse qui") - -# Se ti serve solo un try/finally, per liberare risorse, puoi usare il metodo with -with open("myfile.txt") as f: - for line in f: - print(line) - -# In Python qualunque oggetto in grado di essere trattato come una -# sequenza è definito un oggetto Iterable (itarabile). -# L'oggetto restituito da una funzione range è un iterabile. - -filled_dict = {"uno": 1, "due": 2, "tre": 3} -our_iterable = filled_dict.keys() -print(our_iterable) # => dict_keys(['uno', 'due', 'tre']). -# Questo è un oggetto che implementa la nostra interfaccia Iterable. - -# È possibile utilizzarlo con i loop: -for i in our_iterable: - print(i) # Scrive uno, due, tre - -# Tuttavia non possiamo recuperarne i valori tramite indice. -our_iterable[1] # Genera un TypeError - -# Un oggetto iterabile è in grado di generare un iteratore -our_iterator = iter(our_iterable) - -# L'iteratore è un oggetto che ricorda il suo stato mentro lo si "attraversa" -# Possiamo accedere al successivo elemento con "next()". -next(our_iterator) # => "uno" - -# Mantiene il suo stato mentro eseguiamo l'iterazione -next(our_iterator) # => "due" -next(our_iterator) # => "tre" - -# Dopo che un iteratore ha restituito tutti i suoi dati, genera -# un'eccezione StopIteration -next(our_iterator) # Raises StopIteration - -# Puoi prendere tutti gli elementi di un iteratore utilizzando list(). -list(filled_dict.keys()) # => Returns ["one", "two", "three"] - - - -#################################################### -## 4. Funzioni -#################################################### - -# Usa "def" per creare nuove funzioni -def aggiungi(x, y): - print("x è {} e y è {}".format(x, y)) // Scrive i valori formattati in una stringa - return x + y # Restituisce la somma dei valori con il metodo return - -# Chiamare funzioni con parametri -aggiungi(5, 6) # => scrive "x è 5 e y è 6" e restituisce 11 - -# Un altro modo per chiamare funzioni è con parole chiave come argomenti -aggiungi(y=6, x=5) # In questo modo non è necessario rispettare l'ordine degli argomenti - -# Puoi definire funzioni che accettano un numero non definito di argomenti -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - -# Puoi definire funzioni che accettano un numero variabile di parole chiave -# come argomento, che saranno interpretati come un dizionario usando ** -def keyword_args(**kwargs): - return kwargs - -# Chiamiamola per vedere cosa succede -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# Puoi farle entrambi in una volta, se ti va -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) stampa: - (1, 2) - {"a": 3, "b": 4} -""" - -# Quando chiami funzioni, puoi fare l'opposto di args/kwargs! -# Usa * per sviluppare gli argomenti posizionale ed usa ** per -# espandere gli argomenti parola chiave -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalente a foo(1, 2, 3, 4) -all_the_args(**kwargs) # equivalente a foo(a=3, b=4) -all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4) - - -# Restituire valori multipli (with tuple assignments) -def swap(x, y): - return y, x # Restituisce valori multipli come tupla senza parentesi - # (Nota: le parentesi sono state escluse ma possono essere messe) - -x = 1 -y = 2 -x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # Le parentesi sono state escluse ma possono essere incluse. - -# Funzioni - Visibilità delle variabili (variable scope) -x = 5 - -def set_x(num): - # La variabile locale x non è la variabile globale x - x = num # => 43 - print(x) # => 43 - -def set_global_x(num): - global x - print(x) # => 5 - x = num # la variabile globable x è ora 6 - print(x) # => 6 - -set_x(43) -set_global_x(6) - - -# Python ha "first class functions" -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# Ci sono anche funzioni anonime -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# È possibile creare "mappe" e "filtri" -list(map(add_10, [1, 2, 3])) # => [11, 12, 13] -list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] - -list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] - -# Possiamo usare le "list comprehensions" per mappe e filtri -# Le "list comprehensions" memorizzano l'output come una lista che può essere -# di per sé una lista annidata -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -# Puoi fare anche la comprensione di set e dizionari -{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} -{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} - - -#################################################### -## 5. Modules -#################################################### - -# Puoi importare moduli -import math -print(math.sqrt(16)) # => 4.0 - -# Puoi ottenere specifiche funzione da un modulo -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# Puoi importare tutte le funzioni da un modulo -# Attenzione: questo non è raccomandato -from math import * - -# Puoi abbreviare i nomi dei moduli -import math as m -math.sqrt(16) == m.sqrt(16) # => True - - -# I moduli di Python sono normali file python. Ne puoi -# scrivere di tuoi ed importarli. Il nome del modulo -# è lo stesso del nome del file. - -# Potete scoprire quali funzioni e attributi -# sono definiti in un modulo -import math -dir(math) - -# Se nella cartella corrente hai uno script chiamato math.py, -# Python caricherà quello invece del modulo math. -# Questo succede perchè la cartella corrente ha priorità -# sulle librerie standard di Python - -# Se hai uno script Python chiamato math.py nella stessa -# cartella del tua script, Python caricherà quello al posto del -# comune modulo math. -# Questo accade perché la cartella locale ha la priorità -# sulle librerie built-in di Python. - - -#################################################### -## 6. Classes -#################################################### - -# Usiamo l'istruzione "class" per creare una classe -class Human: - - # Un attributo della classe. E' condiviso tra tutte le istanze delle classe - species = "H. sapiens" - - # Si noti che i doppi underscore iniziali e finali denotano gli oggetti o - # attributi utilizzati da Python ma che vivono nel namespace controllato - # dall'utente - # Metodi, oggetti o attributi come: __init__, __str__, __repr__, etc. sono - # chiamati metodi speciali (o talvolta chiamati "dunder methods"). - # Non dovresti inventare tali nomi da solo. - - def __init__(self, name): - # Assegna l'argomento all'attributo name dell'istanza - self.name = name - - # Inizializza una proprietà - self._age = 0 - - # Un metodo dell'istanza. Tutti i metodi prendo "self" come primo argomento - def say(self, msg): - print("{name}: {message}".format(name=self.name, message=msg)) - - # Un altro metodo dell'istanza - def sing(self): - return 'yo... yo... microphone check... one two... one two...' - - # Un metodo della classe è condiviso fra tutte le istanze - # Sono chiamati con la classe chiamante come primo argomento - @classmethod - def get_species(cls): - return cls.species - - # Un metodo statico è chiamato senza classe o istanza di riferimento - @staticmethod - def grunt(): - return "*grunt*" - - # Una property è come un metodo getter. - # Trasforma il metodo age() in un attributo in sola lettura, che ha - # lo stesso nome - # In Python non c'è bisogno di scrivere futili getter e setter. - @property - def age(self): - return self._age - - # Questo metodo permette di modificare una property - @age.setter - def age(self, age): - self._age = age - - # Questo metodo permette di cancellare una property - @age.deleter - def age(self): - del self._age - -# Quando l'interprete Python legge un sorgente esegue tutto il suo codice. -# Questo controllo su __name__ assicura che questo blocco di codice venga -# eseguito solo quando questo modulo è il programma principale. - -if __name__ == '__main__': - # Crea un'istanza della classe - i = Human(name="Ian") - i.say("hi") # "Ian: hi" - j = Human("Joel") - j.say("hello") # "Joel: hello" - # i e j sono istanze del tipo Human, o in altre parole sono oggetti Human - - # Chiama un metodo della classe - i.say(i.get_species()) # "Ian: H. sapiens" - # Cambia l'attributo condiviso - Human.species = "H. neanderthalensis" - i.say(i.get_species()) # => "Ian: H. neanderthalensis" - j.say(j.get_species()) # => "Joel: H. neanderthalensis" - - # Chiama un metodo statico - print(Human.grunt()) # => "*grunt*" - - # Non è possibile chiamare il metodo statico con l'istanza dell'oggetto - # poiché i.grunt() metterà automaticamente "self" (l'oggetto i) - # come argomento - print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given - - # Aggiorna la property (age) di questa istanza - i.age = 42 - # Leggi la property - i.say(i.age) # => "Ian: 42" - j.say(j.age) # => "Joel: 0" - # Cancella la property - del i.age - i.age # => questo genererà un AttributeError - - -#################################################### -## 6.1 Ereditarietà (Inheritance) -#################################################### - -# L'ereditarietà consente di definire nuove classi figlio che ereditano metodi e -# variabili dalla loro classe genitore. - -# Usando la classe Human definita sopra come classe base o genitore, possiamo -# definire una classe figlia, Superhero, che erediterà le variabili di classe -# come "species", "name" e "age", così come i metodi, come "sing" e "grunt", -# dalla classe Human, ma potrà anche avere le sue proprietà uniche. - -# Per importare le funzioni da altri file usa il seguente formato -# from "nomefile-senza-estensione" import "funzione-o-classe" - -from human import Human - -# Specificare le classi genitore come parametri della definizione della classe -class Superhero(Human): - - # Se la classe figlio deve ereditare tutte le definizioni del genitore - # senza alcuna modifica, puoi semplicemente usare la parola chiave "pass" - # (e nient'altro) - - #Le classi figlio possono sovrascrivere gli attributi dei loro genitori - species = 'Superhuman' - - # Le classi figlie ereditano automaticamente il costruttore della classe - # genitore, inclusi i suoi argomenti, ma possono anche definire ulteriori - # argomenti o definizioni e sovrascrivere i suoi metodi (compreso il - # costruttore della classe). - # Questo costruttore eredita l'argomento "nome" dalla classe "Human" e - # aggiunge gli argomenti "superpowers" e "movie": - - def __init__(self, name, movie=False, - superpowers=["super strength", "bulletproofing"]): - - # aggiungi ulteriori attributi della classe - self.fictional = True - self.movie = movie - self.superpowers = superpowers - - # La funzione "super" ti consente di accedere ai metodi della classe - # genitore che sono stati sovrascritti dalla classe figlia, - # in questo caso il metodo __init__. - # Il seguente codice esegue il costruttore della classe genitore: - super().__init__(name) - - # Sovrascrivere il metodo "sing" - def sing(self): - return 'Dun, dun, DUN!' - - # Aggiungi un ulteriore metodo dell'istanza - def boast(self): - for power in self.superpowers: - print("I wield the power of {pow}!".format(pow=power)) - - -if __name__ == '__main__': - sup = Superhero(name="Tick") - - # Controllo del tipo di istanza - if isinstance(sup, Human): - print('I am human') - if type(sup) is Superhero: - print('I am a superhero') - - # Ottieni il "Method Resolution search Order" usato sia da getattr () - # che da super (). Questo attributo è dinamico e può essere aggiornato - print(Superhero.__mro__) # => (, - # => , ) - - # Esegui il metodo principale ma utilizza il proprio attributo di classe - print(sup.get_species()) # => Superhuman - - # Esegui un metodo che è stato sovrascritto - print(sup.sing()) # => Dun, dun, DUN! - - # Esegui un metodo di Human - sup.say('Spoon') # => Tick: Spoon - - # Esegui un metodo che esiste solo in Superhero - sup.boast() # => I wield the power of super strength! - # => I wield the power of bulletproofing! - - # Attributo di classe ereditato - sup.age = 31 - print(sup.age) # => 31 - - # Attributo che esiste solo in Superhero - print('Am I Oscar eligible? ' + str(sup.movie)) - -#################################################### -## 6.2 Ereditarietà multipla -#################################################### - -# Un'altra definizione di classe -# bat.py -class Bat: - - species = 'Baty' - - def __init__(self, can_fly=True): - self.fly = can_fly - - # Questa classe ha anche un metodo "say" - def say(self, msg): - msg = '... ... ...' - return msg - - # E anche un suo metodo personale - def sonar(self): - return '))) ... (((' - -if __name__ == '__main__': - b = Bat() - print(b.say('hello')) - print(b.fly) - -# Definizione di classe che eredita da Superhero e Bat -# superhero.py -from superhero import Superhero -from bat import Bat - -# Definisci Batman come classe figlia che eredita sia da Superhero che da Bat -class Batman(Superhero, Bat): - - def __init__(self, *args, **kwargs): - # In genere per ereditare gli attributi devi chiamare super: - # super(Batman, self).__init__(*args, **kwargs) - # Ma qui abbiamo a che fare con l'ereditarietà multipla, e super() - # funziona solo con la successiva classe nell'elenco MRO. - # Quindi, invece, chiamiamo esplicitamente __init__ per tutti gli - # antenati. L'uso di *args e **kwargs consente di passare in modo - # pulito gli argomenti, con ciascun genitore che "sbuccia un - # livello della cipolla". - Superhero.__init__(self, 'anonymous', movie=True, - superpowers=['Wealthy'], *args, **kwargs) - Bat.__init__(self, *args, can_fly=False, **kwargs) - # sovrascrivere il valore per l'attributo name - self.name = 'Sad Affleck' - - def sing(self): - return 'nan nan nan nan nan batman!' - - -if __name__ == '__main__': - sup = Batman() - - # Ottieni il "Method Resolution search Order" utilizzato da getattr() e super(). - # Questo attributo è dinamico e può essere aggiornato - print(Batman.__mro__) # => (, - # => , - # => , - # => , ) - - # Esegui il metodo del genitore ma utilizza il proprio attributo di classe - print(sup.get_species()) # => Superhuman - - # Esegui un metodo che è stato sovrascritto - print(sup.sing()) # => nan nan nan nan nan batman! - - # Esegui un metodo da Human, perché l'ordine di ereditarietà è importante - sup.say('I agree') # => Sad Affleck: I agree - - # Esegui un metodo che esiste solo nel 2o antenato - print(sup.sonar()) # => ))) ... ((( - - # Attributo di classe ereditato - sup.age = 100 - print(sup.age) # => 100 - - # Attributo ereditato dal secondo antenato il cui valore predefinito - # è stato ignorato. - print('Can I fly? ' + str(sup.fly)) # => Can I fly? False - - - -#################################################### -## 7. Advanced -#################################################### - -# I generatori ti aiutano a creare codice pigro (lazy code). -# Codice che darà un risultato solo quando sarà "valutato" -def double_numbers(iterable): - for i in iterable: - yield i + i - -# I generatori sono efficienti in termini di memoria perché caricano -# solo i dati necessari per elaborare il valore successivo nell'iterabile. -# Ciò consente loro di eseguire operazioni su intervalli di valori -# altrimenti proibitivi. -# NOTA: `range` sostituisce` xrange` in Python 3. -for i in double_numbers(range(1, 900000000)): # `range` is a generator. - print(i) - if i >= 30: - break - -# Proprio come è possibile creare una "list comprehension", è possibile -# creare anche delle "generator comprehensions". -values = (-x for x in [1,2,3,4,5]) -for x in values: - print(x) # prints -1 -2 -3 -4 -5 to console/terminal - -# Puoi anche trasmettere una "generator comprehensions" direttamente -# ad un elenco. -values = (-x for x in [1,2,3,4,5]) -gen_to_list = list(values) -print(gen_to_list) # => [-1, -2, -3, -4, -5] - - -# Decoratori -# In questo esempio "beg" avvolge/wrappa "say". -# Se say_please è True, cambierà il messaggio restituito. -from functools import wraps - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Per favore! Sono povero :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Puoi comprarmi una birra?" - return msg, say_please - - -print(say()) # Puoi comprarmi una birra? -print(say(say_please=True)) # Puoi comprarmi una birra? Per favore! Sono povero :( -``` - -## Pronto per qualcosa di più? - -### Gratis Online - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) -* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) -* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) -* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) -* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) -* [Dive Into Python 3](http://www.diveintopython3.net/index.html) -* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/ja-jp/python-jp.html.markdown b/ja-jp/python-jp.html.markdown new file mode 100644 index 00000000..b9731411 --- /dev/null +++ b/ja-jp/python-jp.html.markdown @@ -0,0 +1,1008 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["evuez", "http://github.com/evuez"] + - ["Rommel Martinez", "https://ebzzry.io"] + - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] +translators: + - ["kakakaya", "https://github.com/kakakaya"] + - ["Ryota Kayanuma", "https://github.com/PicoSushi"] +filename: learnpython3-jp.py +lang: ja-jp +--- + +90年代の初め、Guido van RossumによってPythonは作成されました。現在となっては、最も有名な言語の1つです。 +私は構文の明快さによって、Pythonと恋に落ちました。 +以下は基本的に実行可能な疑似コードです。 + +フィードバッグは大歓迎です! [@louiedinh](http://twitter.com/louiedinh) または louiedinh [at] [google's email service] にご連絡下さい! + +Note: この記事はPython 3に内容を絞っています。もし古いPython 2.7を学習したいなら、 [こちら](http://learnxinyminutes.com/docs/python/) をご確認下さい。 + +```python +# 1行のコメントは番号記号(#)から始まります。 + +""" 複数行の文字は、"を3つ繋げることで + 書くことができます。 + また、これはドキュメントとしてもよく使われます。 +""" + +#################################################### +# 1. プリミティブ型と演算子 +#################################################### + +# 数字です +3 # => 3 + +# 四則演算はあなたの期待通りに動きます。 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 + +# 整数除算の結果は、正負に関わらず小数の切り捨てが行われます。 +5 // 3 # => 1 +-5 // 3 # => -2 +5.0 // 3.0 # => 1.0 # 浮動小数点でも同様に動作します。 +-5.0 // 3.0 # => -2.0 + +# 除算の結果は常に浮動小数点になります。 +10.0 / 3 # => 3.3333333333333335 + +# 剰余の計算 +7 % 3 # => 1 + +# 冪乗 (x**y, x の y 乗) +2**3 # => 8 + +# 括弧により、計算の順番を優先させられます。 +(1 + 3) * 2 # => 8 + +# 真偽値はプリミティブ型です(大文字から始まっていることに注意!) +True +False + +# not で真偽を反転させられます。 +not True # => False +not False # => True + +# ブール演算 +# 注意: "and" と "or" は小文字です。 +True and False # => False +False or True # => True + +# TrueとFalseは実際には1と0になるキーワードです。 +True + True # => 2 +True * 8 # => 8 +False - 5 # => -5 + +# 比較演算子はTrueとFalseを数値として扱います。 +0 == False # => True +1 == True # => True +2 == True # => False +-5 != True # => True + +# bool論理演算子を整数に対して使うことで整数を真偽値に変換して評価できますが、キャストされていない値が +# bool(int)とビット演算子(& や |)を混同しないようにうにしましょう。 +bool(0) # => False +bool(4) # => True +bool(-6) # => True +0 and 2 # => 0 +-5 or 0 # => -5 + +# 値が等しいか確認するには == +1 == 1 # => True +2 == 1 # => False + +# 値が等しくないか確認するには != +1 != 1 # => False +2 != 1 # => True + +# 他の比較方法 +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# 値がある範囲の中にあるか調べる方法 +1 < 2 and 2 < 3 # => True +2 < 3 and 3 < 2 # => False + +# 連結させるともっと見やすくなります。 +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (is vs. ==) +# "is" は、2つの変数が同一のオブジェクトを参照しているか確認します。 +# 一方 "==" は、それぞれが参照する2つのオブジェクトが同じ値を持つか確認します。 +a = [1, 2, 3, 4] # a は新しいリストの [1, 2, 3, 4] を指します。 +b = a # b は a が指すリストを指します。 +b is a # => True, a と b は同一のオブジェクトを参照しています。 +b == a # => True, a と b が参照するオブジェクトの値は等しいです。 +b = [1, 2, 3, 4] # b は新しいリストの [1, 2, 3, 4] を指します。 +b is a # => False, a と b は別々のオブジェクトを参照しています。 +b == a # => True, a と b が参照するオブジェクトの値は等しいです。 + +# " または ' を使って文字列を作成します。 +"This is a string." +'This is also a string.' + +# 文字列も加算をすることができます!でも、あまり行わないように。 +"Hello " + "world!" # => "Hello world!" +# '+' を使わなくても文字列リテラル(変数ではないもの)の連結ができます。 +"Hello " "world!" # => "Hello world!" + +# 文字列は文字のリストであるかのように扱うことができます。 +"This is a string"[0] # => 'T' + +# 文字列の長さを得るにはこのようにします。 +len("This is a string") # => 16 + +# .format で文字列のフォーマットを行えます +"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" + +# 入力を減らすために、フォーマットするときに引数を繰り返し使うことができます。 +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# 引数の順番を数えるのがお嫌い?キーワード引数をどうぞ。 +"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" + +# もし Python 3 のコードを Python 2.5以下でも使う必要があるなら、 +# 旧式のフォーマット方法を使うこともできます。 +"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" + +# Python3.6以上では、f-stringsやフォーマット文字列を使ってフォーマットすることもできます。 +name = "Reiko" +f"She said her name is {name}." # => "She said her name is Reiko" + +# 基本的に、任意のPythonの文を中括弧に書くことができ、それは評価されて出力されます。 +f"{name} is {len(name)} characters long." + +# None はオブジェクトです(大文字からです!) +None # => None + +# オブジェクトがNoneであるか確認するのに "==" 演算子を使わないように。 +# 代わりに "is" を使いましょう。オブジェクトの素性を確認できます。 +"etc" is None # => False +None is None # => True + +# None や 0 、空の 文字列/リスト/辞書/タプル は全て False として評価されます。 +# 他の全ての値は True になります。 +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False +bool(()) # => False + +#################################################### +# 2. Variables and Collections +#################################################### + +# Python にはprint関数があります。 +print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! + +# 標準では、print関数は最後に改行を出力します。 +# この動作を変更するためには、オプション引数を利用します。 +print("Hello, World", end="!") # => Hello, World! + +# コンソールから入力を得るための簡単な例 +input_string_var = input("Enter some data: ") # 入力を文字列として返します +# Note: Python の初期のバージョンでは、 input() は raw_input() という名前で存在します。 + +# Pythonでは変数の宣言は存在せず、代入のみです。 +# 慣例的に、小文字でアンダースコア区切り ( lower_case_with_underscores ) の変数が使われます。 +some_var = 5 +some_var # => 5 + +# 代入されていない変数へのアクセスは例外を引き起こします。 +# 例外の取り扱いについては、3章の制御の流れをご確認ください。 +some_unknown_var # NameError を送出します + +# ifは式として使用できます。 +# C言語の「?:(三項演算子)」に対応する例: +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# リストは順序を保存します。 +li = [] +# 値の入っているリストも作成できます。 +other_li = [4, 5, 6] + +# append により、リストの末尾にものを入れられます。 +li.append(1) # li is now [1] +li.append(2) # li is now [1, 2] +li.append(4) # li is now [1, 2, 4] +li.append(3) # li is now [1, 2, 4, 3] +# pop でリストの末尾から取り除けます。 +li.pop() # => 3 and li is now [1, 2, 4] +# 元に戻しましょう! +li.append(3) # li is now [1, 2, 4, 3] again. + +# 配列のように、リストにアクセスできます。 +li[0] # => 1 +# 最後の要素を参照できます。 +li[-1] # => 3 + +# 範囲外の要素を参照すると IndexError になります。 +li[4] # IndexError が発生します + +# スライス構文により範囲を参照できます。 +# 開始部分のインデックスに対応する部分は含まれますが、終了部分のインデックスに対応する部分は含まれません。 +li[1:3] # => [2, 4] +# 先端を取り除いたリスト +li[2:] # => [4, 3] +# 末尾を取り除いたリスト +li[:3] # => [1, 2, 4] +# 1つ飛ばしで選択する +li[::2] # =>[1, 4] +# 反転したリストを得る +li[::-1] # => [3, 4, 2, 1] +# これらの任意の組み合わせにより、より複雑なスライスを作ることができます。 +# li[start:end:step] + +# スライスにより、深いコピーを1階層分行うことができます。 +li2 = li[:] # => li2 = [1, 2, 4, 3] だが、 (li2 is li) はFalseになる。 + +# "del"によりリストから任意の要素を削除できます。 +del li[2] # li は [1, 2, 3] になりました。 + +# "remove"で最初に出現する要素を削除できます。 +li.remove(2) # li は [1, 3] になりました。 +li.remove(2) # 2はリストの中に存在しないので、 ValueError が発生します。 + +# 要素を好きなところに挿入できます。 +li.insert(1, 2) # li は [1, 2, 3] に戻りました。 + +# "index"で引数の要素が最初に出現する場所のインデックスを得られます。 +li.index(2) # => 1 +li.index(4) # 4はリストの中に存在しないので、 ValueError が発生します。 + +# リスト同士を足すこともできます。 +# Note: li と other_li の値は変更されません。 +li + other_li # => [1, 2, 3, 4, 5, 6] + +# "extend()"で他のリストを連結することができます。 +li.extend(other_li) # li は [1, 2, 3, 4, 5, 6] になります。 + +# リストの中に値が存在するか、 "in" で確認できます。 +1 in li # => True + +# 長さは "len()" で確認できます。 +len(li) # => 6 + + +# タプルはリストのようなものですが、不変であるという違いがあります。 +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # 内容を変更しようとすると TypeError が発生します。 + +# 長さが1のタプルを作成するには、要素の後にカンマを付ける必要があります。 +# しかし、それ以外の長さなら、例え長さが0でもそのようにする必要はありません。 +type((1)) # => +type((1,)) # => +type(()) # => + +# 大抵のリスト操作はタプルでも行うことができます。 +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# タプルやリストから複数の変数に代入することができます。 +a, b, c = (1, 2, 3) # a, b, c にはそれぞれ 1, 2, 3 が代入されました。 +# 拡張記法もあります。 +a, *b, c = (1, 2, 3, 4) # a は 1 、 b は [2, 3] 、c は4 になります。 +# 括弧を作成しなくてもデフォルトでタプルが作成されます。 +d, e, f = 4, 5, 6 # 4、5、6がそれぞれd、 e、 fに代入されます。 +# 2つの変数を交換するのがどれほど簡単か見てみましょう。 +e, d = d, e # d は 5 、 e は e になります。 + + +# 辞書はマップ(キーと値の組み合わせ)を保存できます。 +empty_dict = {} +# 値が入っている辞書を直接作成することもできます。 +filled_dict = {"one": 1, "two": 2, "three": 3} + +# キーは不変の型である必要があります。 +# これは、高速化のため、キーを定数のハッシュ値に変換できるようにするためです。 +# 不変の型の例として、int、float、string、tupleなどが上げられます。 +invalid_dict = {[1, 2, 3]: "123"} # => list はハッシュ化できないので、 TypeError が発生します。 +valid_dict = {(1, 2, 3): [1, 2, 3]} # 一方、キーに対応する値はどのような型でも利用できます。 + +# [] で 値を取り出せます。 +filled_dict["one"] # => 1 + +# "keys()"により、全てのキーを反復可能な形式で取り出せます。 +# これをリストにするために、"list()"で囲んでいます。これについては後程解説します。 +# Note: Python3.7未満では、辞書のキーの順番は考慮されていません。実行した結果がこれと異なる場合があります。 +# しかし、Python3.7以降ではキーの挿入順を保つようになりました。 +list(filled_dict.keys()) # => ["three", "two", "one"] in Python <3.7 +list(filled_dict.keys()) # => ["one", "two", "three"] in Python 3.7+ + + +# "values()"により、全ての値を反復可能な形式で取り出せます。 +# 前と同じように、これをリストにするために、"list()"で囲んでいます。 +# Note: 辞書の値の順番は考慮されていません。実行した結果がこれと異なる場合があります。 +list(filled_dict.values()) # => [3, 2, 1] in Python <3.7 +list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+ + +# "in" により、辞書のキーが存在するか確認できます。 +"one" in filled_dict # => True +1 in filled_dict # => False + +# 存在しないキーで辞書を参照すると KeyError になります。 +filled_dict["four"] # KeyError + +# "get()" メソッドを使うことで KeyError を回避できます。 +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# get ではキーが存在しなかったときのデフォルト値を指定できます。 +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# "setdefault()" で、キーが存在しなかった場合のみ、値を設定できます。 +filled_dict.setdefault("five", 5) # filled_dict["five"] は 5 になりました。 +filled_dict.setdefault("five", 6) # filled_dict["five"] は 5 のままです。 + +# 辞書にマップを追加する +filled_dict.update({"four": 4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} +filled_dict["four"] = 4 # 辞書に追加する別の方法 + +# del により辞書からキーを削除できます。 +del filled_dict["one"] # "one" キーを辞書から削除します。 + +# Python 3.5 以降では、追加の値を取り出す方法があります。 +{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} +{'a': 1, **{'a': 2}} # => {'a': 2} + + +# set では集合を表現できます。 +empty_set = set() +# 集合を一連の値で初期化する例です。辞書に似ていますね?ごめんなさい。 +some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} + +# 辞書のキーのように、集合の値は不変である必要があります。 +invalid_set = {[1], 1} # => list はハッシュ化できないので、 TypeError が送出されます。 +valid_set = {(1,), 1} + +# 集合に新しい要素を追加できます。 +filled_set = some_set +filled_set.add(5) # filled_set は {1, 2, 3, 4, 5} になりました。 +# 集合は重複した要素を持ちません。 +filled_set.add(5) # 以前の{1, 2, 3, 4, 5}のままです。 + +# & により、集合同士の共通部分が得られます。 +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# | により、集合同士の合併が得られます。 +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# - により、集合同士の差集合が得られます。 +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# ^ により、集合同士の対象差が得られます。 +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# 左の集合が右の集合の上位集合であるか確認。 +{1, 2} >= {1, 2, 3} # => False + +# 左の集合が右の集合の部分集合であるか確認。 +{1, 2} <= {1, 2, 3} # => True + +# in により値が集合の中に存在するか確認できます。 +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +# 3. 制御の流れとiterable +#################################################### + +# まずは変数を作りましょう。 +some_var = 5 + +# これはif文です。Pythonではインデントが特徴的ですね! +# 規約ではタブではなく4つのスペースでインデントすることが推奨されています。 +# 以下の例では"some_var is smaller than 10"と出力されます。 +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # この elif 節はオプションです。 + print("some_var is smaller than 10.") +else: # この else 節もオプションです。 + print("some_var is indeed 10.") + + +""" +for ループはリストの要素を反復することができます。 +出力: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # format() を使って文字列に変数を挿入して出力できます。 + print("{} is a mammal".format(animal)) + +""" +"range(数値)" は、ゼロから与えられた数値までのiterableを返します。 +出力: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(lower, upper)" は、 lower の数値から upper の数値までのiterableを返します。 +upper の数値は含まれません。 +出力: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(lower, upper, step)" は、lower の数値から upper の数値までが、 +step 刻みで表現されるiterableを返します +step が与えられない場合、デフォルトは1になります。 +出力: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) +""" + +while によるループは条件が成立しなくなるまで実行されます。 +出力: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # x = x + 1 の省略記法 + +# try/except ブロックにより、例外を扱う +try: + # "raise" により例外を発生させます。 + raise IndexError("This is an index error") +except IndexError as e: + pass # pass は、何もしないという命令(no-op)に相当します。普通、ここで例外に対処します。 +except (TypeError, NameError): + pass # もし必要なら、複数の種類の例外を一緒に処理できます。 +else: # try/except ブロックへのオプションの節。他の全てのexceptブロックより後に置かなければなりません。 + print("All good!") # tryで例外が発生しなかった場合のみ実行されます。 +finally: # 例外が発生したか、しなかったか、どのような例外だったかに関らず実行されます。 + print("We can clean up resources here") + +# try/finallyでリソースの始末をする代わりに、 with 文を使うこともできます。 +with open("myfile.txt") as f: + for line in f: + print(line) + +# Pythonは、iterableと呼ばれる基本的な抽象化が提供しています。 +# iterableは、シーケンスとして取り扱えるオブジェクトです。 +# range関数で返されるオブジェクトもiterableの一種です。 +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => dict_keys(['one', 'two', 'three']). これはiterableインタフェースを実装するオブジェクトです。 + +# iterableでループを行うことができます。 +for i in our_iterable: + print(i) # Prints one, two, three + +# しかし、インデックスで要素を参照することはできません。 +our_iterable[1] # TypeError が発生します。 + +# iterableは、iteratorの作り方がわかるオブジェクトです。 +our_iterator = iter(our_iterable) + +# iterator は、要素を取り出したときの状態を覚えるオブジェクトです。 +# "next()"により次の要素を取り出せます。 +next(our_iterator) # => "one" + +# 反復(iterate)する度に、状態を更新します。 +next(our_iterator) # => "two" +next(our_iterator) # => "three" + +# iteratorが自身の持つ全てのデータを返したあとは、 StopIteration 例外を発生させます。 +next(our_iterator) # StopIteration が発生します。 + +# "list()"を呼ぶことにより、iteratorの全ての要素を得られます。 +list(filled_dict.keys()) # => ["one", "two", "three"] + + +#################################################### +# 4. 関数 +#################################################### + +# 新しい関数を作成するには "def" を使います。 +def add(x, y): + print("x is {} and y is {}".format(x, y)) + return x + y # return 文で値を返します。 + +# 引数付きで関数を呼んでみましょう。 +add(5, 6) # => "x is 5 and y is 6" と出力し、 11 を返します。 + +# キーワード引数で関数を呼ぶこともできます。 +add(y=6, x=5) # キーワード引数を使うと任意の順番で引数を指定できます。 + + +# 可変数の位置引数を持つ関数を定義できます。 +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + + +# 可変数のキーワード引数を持つ関数を定義できます。 +def keyword_args(**kwargs): + return kwargs + +# 何が起こるか、試してみましょう +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# お望みなら、両方一気にやることもできます。 +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# 関数を呼ぶとき、 args/kwargs の逆のことをすることができます! +# * を使ってタプルを展開したり、 ** を使って辞書を展開できます。 +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # all_the_args(1, 2, 3, 4) と等しいです。 +all_the_args(**kwargs) # all_the_args(a=3, b=4) と等しいです。 +all_the_args(*args, **kwargs) # all_the_args(1, 2, 3, 4, a=3, b=4) と等しいです。 + + +# タプルで複数の値を返す +def swap(x, y): # 括弧を使わずに、複数の値をタプルとして返すことができます。 + return y, x # (Note: 括弧は使わなくてもいいですが、使うこともできます。) + + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # このように、括弧は使っても使わなくてもいいです。 + + +# 関数のスコープ +x = 5 + + +def set_x(num): + # ローカル変数の x はグローバル変数の x とは異なります + x = num # => 43 + print(x) # => 43 + + +def set_global_x(num): + global x + print(x) # => 5 + x = num # グローバル変数の x に 6 が代入されました。 + print(x) # => 6 + +set_x(43) +set_global_x(6) + + +# Pythonは第一級関数をサポートします。 +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# 無名関数もサポートしています。 +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# 高階関数も組込まれています。 +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] + +list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] + +# map や filter の代わりに、リスト内包表記を使うことができます。 +# リスト内包表記は、出力を別のリスト内包表記にネストさせることができます。 +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# 集合(set)や辞書も内包表記ができます。 +{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +# 5. モジュール +#################################################### + +# Pythonではモジュールをインポートできます。 +import math +print(math.sqrt(16)) # => 4.0 + +# モジュールの中から特定の関数をインポートすることもできます。 +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# 全部の関数をモジュールからインポートすることができます。 +# Warning: この方法は推奨されません。 +from math import * + +# 短い名前でモジュールをインポートすることができます。 +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Pythonのモジュールは実際には単なるPythonのファイルです。 +# 自分で書くことも、インポートすることもできます。 +# ファイル名がそのままモジュール名になります。 + +# モジュールで定義されている関数と属性を調べることができます。 +import math +dir(math) + +# もし、現在書いているスクリプトと同じフォルダに「math.py」という +# Pythonのスクリプトが存在する場合、そのmath.pyが +# 組み込みのPythonモジュールの代わりに読み込まれるでしょう。 +# これは、ローカルのフォルダはPythonの組み込みライブラリよりも +# 優先度が高いため発生するのです。 + + +#################################################### +# 6. クラス +#################################################### + +# クラスを作成するために、class文を使います。 +class Human: + + # クラスの属性です。このクラスの全てのインスタンスで共有されます。 + species = "H. sapiens" + + # 標準的なイニシャライザで、このクラスがインスタンスを作成するときは毎回呼ばれます。 + # 2つのアンダースコアがオブジェクトや属性の前後についているとき、これらはPythonによって利用され、 + # ユーザーの名前空間には存在しないということに注意してください。 + # __init__ や __str__ 、 __repr__ のようなメソッド(やオブジェクト、属性)は、 + # special methods (または dunder methods)と呼ばれます。 + # 同じような名前を自分で発明しないほうがよいでしょう。 + def __init__(self, name): + # 引数をインスタンスのname属性に設定します。 + self.name = name + + # プロパティの初期化 + self._age = 0 + + # インスタンスメソッド。全てのメソッドは"self"を最初の引数に取ります。 + def say(self, msg): + print("{name}: {message}".format(name=self.name, message=msg)) + + # 別のインスタンスメソッドの例。 + def sing(self): + return 'yo... yo... microphone check... one two... one two...' + + # クラスメソッドは全てのインスタンスで共有されます。 + # クラスメソッドではクラスを最初の引数として呼ばれます。 + @classmethod + def get_species(cls): + return cls.species + + # スタティックメソッドはクラスやインスタンスを参照せずに呼ばれます。 + @staticmethod + def grunt(): + return "*grunt*" + + # プロパティはgetterのようなものです。 + # age() メソッドを同名の読取専用属性に変換します。 + # Pythonではわざわざgetterやsetterを書く必要はありません。 + @property + def age(self): + return self._age + + # プロパティを設定できるようにします。 + @age.setter + def age(self, age): + self._age = age + + # プロパティを削除できるようにします。 + @age.deleter + def age(self): + del self._age + + +# Pythonインタプリタがソースファイルを読み込んだとき、全てのコードを実行します。 +# この __name__ による確認により、このモジュールがメインのプログラムである場合にのみ、 +# このコードブロックが実行されるようにします。 +if __name__ == '__main__': + # クラスのインスタンスを作成します。 + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # i と j はHumanのインスタンスです。別の言葉で言うなら、これらはHumanのオブジェクトです。 + + # クラスメソッドを呼んでみましょう。 + i.say(i.get_species()) # "Ian: H. sapiens" + # 共有属性を変更してみましょう。 + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # スタティックメソッドを呼んでみましょう。 + print(Human.grunt()) # => "*grunt*" + + # スタティックメソッドはインスタンスから呼ぶことはできません。 + # なぜならば、 i.grunt() は自動的に"self" ( i オブジェクト ) を引数として渡してしまうからです。 + print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given + + # インスタンスのプロパティを更新してみましょう。 + i.age = 42 + # プロパティを取得してみましょう。 + i.say(i.age) # => "Ian: 42" + j.say(j.age) # => "Joel: 0" + # プロパティを削除してみましょう。 + del i.age + # i.age # => AttributeError が発生します。 + + +#################################################### +# 6.1 継承 +#################################################### +# 継承を行うことで、親クラスからメソッドと変数を継承する新しい子クラスを定義できます。 + +# 上記で定義されたHumanクラスを親クラス(基底クラス)として使い、Superheroという子クラスを定義します。 +# これは"species"、"name"や"age"といった変数や、"sing"や"grunt"のようなメソッドをHumanから継承しますが、 +# Superhero独自のプロパティを持つこともできます。 + +# ファイルを分割してモジュール化の利点を活用するために、上記のHumanクラスを独自のファイル、ここでは human.py に記述ましょう。 + +# 別のファイルから関数をインポートするには次の形式を利用してください: +# from "拡張子なしのファイル名" import "関数やクラス" + +from human import Human + + +# 親クラスを子クラスのパラメータとして指定します +class Superhero(Human): + + # もし子クラスが親クラスの全ての定義を変更なしで継承する場合、"pass"キーワードのみを書くだけで良いです。 + # しかし、今回は親クラスとは異なる子クラスを作成するので、今回は以下の通りコメントアウトしています。 + # pass + + # 子クラスは親クラスの属性を上書きできます。 + species = 'Superhuman' + + # 子クラスは親クラスのコンストラクタを引数含めて自動的に継承しますが、 + # 追加の引数や定義を行ってコンストラクタのようなメソッドを上書きすることもできます。 + # このコンストラクタは"name"引数を"Human"クラスから継承し、"superpower"と"movie"という引数を追加します。 + def __init__(self, name, movie=False, + superpowers=["super strength", "bulletproofing"]): + + # 追加のクラス属性を作成する + self.fictional = True + self.movie = movie + # デフォルト値は共有されるので、可変のデフォルト値には注意してください。 + self.superpowers = superpowers + + # "super"関数を使うと子クラスに上書きされた親クラスのメソッド(今回は "__init__")にアクセスできます。 + # これで、親クラスのコンストラクタを呼んでいます。 + super().__init__(name) + + # singメソッドを上書きし、 + def sing(self): + return 'Dun, dun, DUN!' + + # 追加のインスタンスメソッドを作成します。 + def boast(self): + for power in self.superpowers: + print("I wield the power of {pow}!".format(pow=power)) + + +if __name__ == '__main__': + sup = Superhero(name="Tick") + + # インスタンスの型を調べる + if isinstance(sup, Human): + print('I am human') + if type(sup) is Superhero: + print('I am a superhero') + + # getattr()とsuper()で使われるメソッドの解決順序を調べてみます。 + # この属性は動的であり、変更可能です。 + print(Superhero.__mro__) # => (, + # => , ) + + # 親のメソッドを呼びだすものの、独自のクラス属性を参照します。 + print(sup.get_species()) # => Superhuman + + # 上書きされたメソッドを呼ぶ + print(sup.sing()) # => Dun, dun, DUN! + + # Humanのメソッドを呼ぶ + sup.say('Spoon') # => Tick: Spoon + + # Superhero限定のメソッドを呼ぶ + sup.boast() # => I wield the power of super strength! + # => I wield the power of bulletproofing! + + # 継承されたクラス属性 + sup.age = 31 + print(sup.age) # => 31 + + # Superhero限定の属性 + print('Am I Oscar eligible? ' + str(sup.movie)) + + + +#################################################### +# 6.2 多重継承 +#################################################### + +# 別のクラスを定義します。 +# bat.py +class Bat: + + species = 'Baty' + + def __init__(self, can_fly=True): + self.fly = can_fly + + # このクラスも say メソッドを持ちます。 + def say(self, msg): + msg = '... ... ...' + return msg + + # 同様に、独自のメソッドも与えましょう。 + def sonar(self): + return '))) ... (((' + +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) + +# superhero.py +from superhero import Superhero +from bat import Bat + +# BatmanをSuperheroとBatの両方を継承した子クラスとして定義します。 +class Batman(Superhero, Bat): + + def __init__(self, *args, **kwargs): + # 通常、属性を継承するにはsuper()を呼び出します。 + # super(Batman, self).__init__(*args, **kwargs) + # しかし、ここでは多重継承を行っているので、 super() はMRO(メソッド解決順序)の次の基本クラスにのみ動作します。 + # なので、全ての祖先に対して明示的に __init__ を呼ぶことにします。 + # *args と **kwargs を使うことで、それぞれの継承元が + # たまねぎの皮を剥がすごとく、引数を用いることができます。 + Superhero.__init__(self, 'anonymous', movie=True, + superpowers=['Wealthy'], *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # 名前の属性の値を上書きします。 + self.name = 'Sad Affleck' + + def sing(self): + return 'nan nan nan nan nan batman!' + + +if __name__ == '__main__': + sup = Batman() + + # getattr() や super() の両方で使われるMROを取得します。 + # この属性は動的であり、更新が可能です。 + print(Batman.__mro__) # => (, + # => , + # => , + # => , ) + + + # 親メソッドを呼び出しますが、独自のクラス属性を参照します。 + print(sup.get_species()) # => Superhuman + + # 上書きされたメソッドを呼び出します。 + print(sup.sing()) # => nan nan nan nan nan batman! + + # 継承順により、Humanから継承されたメソッドを呼び出します。 + sup.say('I agree') # => Sad Affleck: I agree + + # 2番目の先祖にのみ存在するメソッドを呼び出してみます。 + print(sup.sonar()) # => ))) ... ((( + + # 継承されたクラス属性 + sup.age = 100 + print(sup.age) # => 100 + + # デフォルト値が上書きされて、2番目の先祖から継承された属性 + print('Can I fly? ' + str(sup.fly)) # => Can I fly? False + + +#################################################### +# 7. 発展的内容 +#################################################### + +# ジェネレータは遅延をするコードの作成に役立ちます。 +def double_numbers(iterable): + for i in iterable: + yield i + i + +# 次の値を処理するのに必要なデータしか読み込まないので、ジェネレータはメモリをあまり消費しません。 +# この性質により、他の方法では非常に多くのメモリを消費するような操作が可能になります。 +for i in double_numbers(range(1, 900000000)): # `range` もジェネレータの1つです。 + print(i) + if i >= 30: + break + +# リスト内包表記のように、ジェネータ内包表記を作成することもできます。 +values = (-x for x in [1, 2, 3, 4, 5]) +for x in values: + print(x) # prints -1 -2 -3 -4 -5 + +# ジェネレータ内包表記から直接リストを作成することもできます。 +values = (-x for x in [1, 2, 3, 4, 5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + +# デコレータ +# この例では`beg` が `say` を `wraps`します。 +# もし say_please が True なら、出力が変更されます。 +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # Can you buy me a beer? +print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( +``` + +## Ready For More? + +### Free Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) +* [Dive Into Python 3](http://www.diveintopython3.net/index.html) +* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/ja-jp/python3-jp.html.markdown b/ja-jp/python3-jp.html.markdown deleted file mode 100644 index b9731411..00000000 --- a/ja-jp/python3-jp.html.markdown +++ /dev/null @@ -1,1008 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] - - ["evuez", "http://github.com/evuez"] - - ["Rommel Martinez", "https://ebzzry.io"] - - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] -translators: - - ["kakakaya", "https://github.com/kakakaya"] - - ["Ryota Kayanuma", "https://github.com/PicoSushi"] -filename: learnpython3-jp.py -lang: ja-jp ---- - -90年代の初め、Guido van RossumによってPythonは作成されました。現在となっては、最も有名な言語の1つです。 -私は構文の明快さによって、Pythonと恋に落ちました。 -以下は基本的に実行可能な疑似コードです。 - -フィードバッグは大歓迎です! [@louiedinh](http://twitter.com/louiedinh) または louiedinh [at] [google's email service] にご連絡下さい! - -Note: この記事はPython 3に内容を絞っています。もし古いPython 2.7を学習したいなら、 [こちら](http://learnxinyminutes.com/docs/python/) をご確認下さい。 - -```python -# 1行のコメントは番号記号(#)から始まります。 - -""" 複数行の文字は、"を3つ繋げることで - 書くことができます。 - また、これはドキュメントとしてもよく使われます。 -""" - -#################################################### -# 1. プリミティブ型と演算子 -#################################################### - -# 数字です -3 # => 3 - -# 四則演算はあなたの期待通りに動きます。 -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7.0 - -# 整数除算の結果は、正負に関わらず小数の切り捨てが行われます。 -5 // 3 # => 1 --5 // 3 # => -2 -5.0 // 3.0 # => 1.0 # 浮動小数点でも同様に動作します。 --5.0 // 3.0 # => -2.0 - -# 除算の結果は常に浮動小数点になります。 -10.0 / 3 # => 3.3333333333333335 - -# 剰余の計算 -7 % 3 # => 1 - -# 冪乗 (x**y, x の y 乗) -2**3 # => 8 - -# 括弧により、計算の順番を優先させられます。 -(1 + 3) * 2 # => 8 - -# 真偽値はプリミティブ型です(大文字から始まっていることに注意!) -True -False - -# not で真偽を反転させられます。 -not True # => False -not False # => True - -# ブール演算 -# 注意: "and" と "or" は小文字です。 -True and False # => False -False or True # => True - -# TrueとFalseは実際には1と0になるキーワードです。 -True + True # => 2 -True * 8 # => 8 -False - 5 # => -5 - -# 比較演算子はTrueとFalseを数値として扱います。 -0 == False # => True -1 == True # => True -2 == True # => False --5 != True # => True - -# bool論理演算子を整数に対して使うことで整数を真偽値に変換して評価できますが、キャストされていない値が -# bool(int)とビット演算子(& や |)を混同しないようにうにしましょう。 -bool(0) # => False -bool(4) # => True -bool(-6) # => True -0 and 2 # => 0 --5 or 0 # => -5 - -# 値が等しいか確認するには == -1 == 1 # => True -2 == 1 # => False - -# 値が等しくないか確認するには != -1 != 1 # => False -2 != 1 # => True - -# 他の比較方法 -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# 値がある範囲の中にあるか調べる方法 -1 < 2 and 2 < 3 # => True -2 < 3 and 3 < 2 # => False - -# 連結させるともっと見やすくなります。 -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# (is vs. ==) -# "is" は、2つの変数が同一のオブジェクトを参照しているか確認します。 -# 一方 "==" は、それぞれが参照する2つのオブジェクトが同じ値を持つか確認します。 -a = [1, 2, 3, 4] # a は新しいリストの [1, 2, 3, 4] を指します。 -b = a # b は a が指すリストを指します。 -b is a # => True, a と b は同一のオブジェクトを参照しています。 -b == a # => True, a と b が参照するオブジェクトの値は等しいです。 -b = [1, 2, 3, 4] # b は新しいリストの [1, 2, 3, 4] を指します。 -b is a # => False, a と b は別々のオブジェクトを参照しています。 -b == a # => True, a と b が参照するオブジェクトの値は等しいです。 - -# " または ' を使って文字列を作成します。 -"This is a string." -'This is also a string.' - -# 文字列も加算をすることができます!でも、あまり行わないように。 -"Hello " + "world!" # => "Hello world!" -# '+' を使わなくても文字列リテラル(変数ではないもの)の連結ができます。 -"Hello " "world!" # => "Hello world!" - -# 文字列は文字のリストであるかのように扱うことができます。 -"This is a string"[0] # => 'T' - -# 文字列の長さを得るにはこのようにします。 -len("This is a string") # => 16 - -# .format で文字列のフォーマットを行えます -"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" - -# 入力を減らすために、フォーマットするときに引数を繰り返し使うことができます。 -"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" - -# 引数の順番を数えるのがお嫌い?キーワード引数をどうぞ。 -"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" - -# もし Python 3 のコードを Python 2.5以下でも使う必要があるなら、 -# 旧式のフォーマット方法を使うこともできます。 -"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" - -# Python3.6以上では、f-stringsやフォーマット文字列を使ってフォーマットすることもできます。 -name = "Reiko" -f"She said her name is {name}." # => "She said her name is Reiko" - -# 基本的に、任意のPythonの文を中括弧に書くことができ、それは評価されて出力されます。 -f"{name} is {len(name)} characters long." - -# None はオブジェクトです(大文字からです!) -None # => None - -# オブジェクトがNoneであるか確認するのに "==" 演算子を使わないように。 -# 代わりに "is" を使いましょう。オブジェクトの素性を確認できます。 -"etc" is None # => False -None is None # => True - -# None や 0 、空の 文字列/リスト/辞書/タプル は全て False として評価されます。 -# 他の全ての値は True になります。 -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False -bool(()) # => False - -#################################################### -# 2. Variables and Collections -#################################################### - -# Python にはprint関数があります。 -print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! - -# 標準では、print関数は最後に改行を出力します。 -# この動作を変更するためには、オプション引数を利用します。 -print("Hello, World", end="!") # => Hello, World! - -# コンソールから入力を得るための簡単な例 -input_string_var = input("Enter some data: ") # 入力を文字列として返します -# Note: Python の初期のバージョンでは、 input() は raw_input() という名前で存在します。 - -# Pythonでは変数の宣言は存在せず、代入のみです。 -# 慣例的に、小文字でアンダースコア区切り ( lower_case_with_underscores ) の変数が使われます。 -some_var = 5 -some_var # => 5 - -# 代入されていない変数へのアクセスは例外を引き起こします。 -# 例外の取り扱いについては、3章の制御の流れをご確認ください。 -some_unknown_var # NameError を送出します - -# ifは式として使用できます。 -# C言語の「?:(三項演算子)」に対応する例: -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# リストは順序を保存します。 -li = [] -# 値の入っているリストも作成できます。 -other_li = [4, 5, 6] - -# append により、リストの末尾にものを入れられます。 -li.append(1) # li is now [1] -li.append(2) # li is now [1, 2] -li.append(4) # li is now [1, 2, 4] -li.append(3) # li is now [1, 2, 4, 3] -# pop でリストの末尾から取り除けます。 -li.pop() # => 3 and li is now [1, 2, 4] -# 元に戻しましょう! -li.append(3) # li is now [1, 2, 4, 3] again. - -# 配列のように、リストにアクセスできます。 -li[0] # => 1 -# 最後の要素を参照できます。 -li[-1] # => 3 - -# 範囲外の要素を参照すると IndexError になります。 -li[4] # IndexError が発生します - -# スライス構文により範囲を参照できます。 -# 開始部分のインデックスに対応する部分は含まれますが、終了部分のインデックスに対応する部分は含まれません。 -li[1:3] # => [2, 4] -# 先端を取り除いたリスト -li[2:] # => [4, 3] -# 末尾を取り除いたリスト -li[:3] # => [1, 2, 4] -# 1つ飛ばしで選択する -li[::2] # =>[1, 4] -# 反転したリストを得る -li[::-1] # => [3, 4, 2, 1] -# これらの任意の組み合わせにより、より複雑なスライスを作ることができます。 -# li[start:end:step] - -# スライスにより、深いコピーを1階層分行うことができます。 -li2 = li[:] # => li2 = [1, 2, 4, 3] だが、 (li2 is li) はFalseになる。 - -# "del"によりリストから任意の要素を削除できます。 -del li[2] # li は [1, 2, 3] になりました。 - -# "remove"で最初に出現する要素を削除できます。 -li.remove(2) # li は [1, 3] になりました。 -li.remove(2) # 2はリストの中に存在しないので、 ValueError が発生します。 - -# 要素を好きなところに挿入できます。 -li.insert(1, 2) # li は [1, 2, 3] に戻りました。 - -# "index"で引数の要素が最初に出現する場所のインデックスを得られます。 -li.index(2) # => 1 -li.index(4) # 4はリストの中に存在しないので、 ValueError が発生します。 - -# リスト同士を足すこともできます。 -# Note: li と other_li の値は変更されません。 -li + other_li # => [1, 2, 3, 4, 5, 6] - -# "extend()"で他のリストを連結することができます。 -li.extend(other_li) # li は [1, 2, 3, 4, 5, 6] になります。 - -# リストの中に値が存在するか、 "in" で確認できます。 -1 in li # => True - -# 長さは "len()" で確認できます。 -len(li) # => 6 - - -# タプルはリストのようなものですが、不変であるという違いがあります。 -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # 内容を変更しようとすると TypeError が発生します。 - -# 長さが1のタプルを作成するには、要素の後にカンマを付ける必要があります。 -# しかし、それ以外の長さなら、例え長さが0でもそのようにする必要はありません。 -type((1)) # => -type((1,)) # => -type(()) # => - -# 大抵のリスト操作はタプルでも行うことができます。 -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# タプルやリストから複数の変数に代入することができます。 -a, b, c = (1, 2, 3) # a, b, c にはそれぞれ 1, 2, 3 が代入されました。 -# 拡張記法もあります。 -a, *b, c = (1, 2, 3, 4) # a は 1 、 b は [2, 3] 、c は4 になります。 -# 括弧を作成しなくてもデフォルトでタプルが作成されます。 -d, e, f = 4, 5, 6 # 4、5、6がそれぞれd、 e、 fに代入されます。 -# 2つの変数を交換するのがどれほど簡単か見てみましょう。 -e, d = d, e # d は 5 、 e は e になります。 - - -# 辞書はマップ(キーと値の組み合わせ)を保存できます。 -empty_dict = {} -# 値が入っている辞書を直接作成することもできます。 -filled_dict = {"one": 1, "two": 2, "three": 3} - -# キーは不変の型である必要があります。 -# これは、高速化のため、キーを定数のハッシュ値に変換できるようにするためです。 -# 不変の型の例として、int、float、string、tupleなどが上げられます。 -invalid_dict = {[1, 2, 3]: "123"} # => list はハッシュ化できないので、 TypeError が発生します。 -valid_dict = {(1, 2, 3): [1, 2, 3]} # 一方、キーに対応する値はどのような型でも利用できます。 - -# [] で 値を取り出せます。 -filled_dict["one"] # => 1 - -# "keys()"により、全てのキーを反復可能な形式で取り出せます。 -# これをリストにするために、"list()"で囲んでいます。これについては後程解説します。 -# Note: Python3.7未満では、辞書のキーの順番は考慮されていません。実行した結果がこれと異なる場合があります。 -# しかし、Python3.7以降ではキーの挿入順を保つようになりました。 -list(filled_dict.keys()) # => ["three", "two", "one"] in Python <3.7 -list(filled_dict.keys()) # => ["one", "two", "three"] in Python 3.7+ - - -# "values()"により、全ての値を反復可能な形式で取り出せます。 -# 前と同じように、これをリストにするために、"list()"で囲んでいます。 -# Note: 辞書の値の順番は考慮されていません。実行した結果がこれと異なる場合があります。 -list(filled_dict.values()) # => [3, 2, 1] in Python <3.7 -list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+ - -# "in" により、辞書のキーが存在するか確認できます。 -"one" in filled_dict # => True -1 in filled_dict # => False - -# 存在しないキーで辞書を参照すると KeyError になります。 -filled_dict["four"] # KeyError - -# "get()" メソッドを使うことで KeyError を回避できます。 -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# get ではキーが存在しなかったときのデフォルト値を指定できます。 -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 - -# "setdefault()" で、キーが存在しなかった場合のみ、値を設定できます。 -filled_dict.setdefault("five", 5) # filled_dict["five"] は 5 になりました。 -filled_dict.setdefault("five", 6) # filled_dict["five"] は 5 のままです。 - -# 辞書にマップを追加する -filled_dict.update({"four": 4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} -filled_dict["four"] = 4 # 辞書に追加する別の方法 - -# del により辞書からキーを削除できます。 -del filled_dict["one"] # "one" キーを辞書から削除します。 - -# Python 3.5 以降では、追加の値を取り出す方法があります。 -{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} -{'a': 1, **{'a': 2}} # => {'a': 2} - - -# set では集合を表現できます。 -empty_set = set() -# 集合を一連の値で初期化する例です。辞書に似ていますね?ごめんなさい。 -some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} - -# 辞書のキーのように、集合の値は不変である必要があります。 -invalid_set = {[1], 1} # => list はハッシュ化できないので、 TypeError が送出されます。 -valid_set = {(1,), 1} - -# 集合に新しい要素を追加できます。 -filled_set = some_set -filled_set.add(5) # filled_set は {1, 2, 3, 4, 5} になりました。 -# 集合は重複した要素を持ちません。 -filled_set.add(5) # 以前の{1, 2, 3, 4, 5}のままです。 - -# & により、集合同士の共通部分が得られます。 -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# | により、集合同士の合併が得られます。 -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# - により、集合同士の差集合が得られます。 -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# ^ により、集合同士の対象差が得られます。 -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# 左の集合が右の集合の上位集合であるか確認。 -{1, 2} >= {1, 2, 3} # => False - -# 左の集合が右の集合の部分集合であるか確認。 -{1, 2} <= {1, 2, 3} # => True - -# in により値が集合の中に存在するか確認できます。 -2 in filled_set # => True -10 in filled_set # => False - - -#################################################### -# 3. 制御の流れとiterable -#################################################### - -# まずは変数を作りましょう。 -some_var = 5 - -# これはif文です。Pythonではインデントが特徴的ですね! -# 規約ではタブではなく4つのスペースでインデントすることが推奨されています。 -# 以下の例では"some_var is smaller than 10"と出力されます。 -if some_var > 10: - print("some_var is totally bigger than 10.") -elif some_var < 10: # この elif 節はオプションです。 - print("some_var is smaller than 10.") -else: # この else 節もオプションです。 - print("some_var is indeed 10.") - - -""" -for ループはリストの要素を反復することができます。 -出力: - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - # format() を使って文字列に変数を挿入して出力できます。 - print("{} is a mammal".format(animal)) - -""" -"range(数値)" は、ゼロから与えられた数値までのiterableを返します。 -出力: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -"range(lower, upper)" は、 lower の数値から upper の数値までのiterableを返します。 -upper の数値は含まれません。 -出力: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -"range(lower, upper, step)" は、lower の数値から upper の数値までが、 -step 刻みで表現されるiterableを返します -step が与えられない場合、デフォルトは1になります。 -出力: - 4 - 6 -""" -for i in range(4, 8, 2): - print(i) -""" - -while によるループは条件が成立しなくなるまで実行されます。 -出力: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # x = x + 1 の省略記法 - -# try/except ブロックにより、例外を扱う -try: - # "raise" により例外を発生させます。 - raise IndexError("This is an index error") -except IndexError as e: - pass # pass は、何もしないという命令(no-op)に相当します。普通、ここで例外に対処します。 -except (TypeError, NameError): - pass # もし必要なら、複数の種類の例外を一緒に処理できます。 -else: # try/except ブロックへのオプションの節。他の全てのexceptブロックより後に置かなければなりません。 - print("All good!") # tryで例外が発生しなかった場合のみ実行されます。 -finally: # 例外が発生したか、しなかったか、どのような例外だったかに関らず実行されます。 - print("We can clean up resources here") - -# try/finallyでリソースの始末をする代わりに、 with 文を使うこともできます。 -with open("myfile.txt") as f: - for line in f: - print(line) - -# Pythonは、iterableと呼ばれる基本的な抽象化が提供しています。 -# iterableは、シーケンスとして取り扱えるオブジェクトです。 -# range関数で返されるオブジェクトもiterableの一種です。 -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) # => dict_keys(['one', 'two', 'three']). これはiterableインタフェースを実装するオブジェクトです。 - -# iterableでループを行うことができます。 -for i in our_iterable: - print(i) # Prints one, two, three - -# しかし、インデックスで要素を参照することはできません。 -our_iterable[1] # TypeError が発生します。 - -# iterableは、iteratorの作り方がわかるオブジェクトです。 -our_iterator = iter(our_iterable) - -# iterator は、要素を取り出したときの状態を覚えるオブジェクトです。 -# "next()"により次の要素を取り出せます。 -next(our_iterator) # => "one" - -# 反復(iterate)する度に、状態を更新します。 -next(our_iterator) # => "two" -next(our_iterator) # => "three" - -# iteratorが自身の持つ全てのデータを返したあとは、 StopIteration 例外を発生させます。 -next(our_iterator) # StopIteration が発生します。 - -# "list()"を呼ぶことにより、iteratorの全ての要素を得られます。 -list(filled_dict.keys()) # => ["one", "two", "three"] - - -#################################################### -# 4. 関数 -#################################################### - -# 新しい関数を作成するには "def" を使います。 -def add(x, y): - print("x is {} and y is {}".format(x, y)) - return x + y # return 文で値を返します。 - -# 引数付きで関数を呼んでみましょう。 -add(5, 6) # => "x is 5 and y is 6" と出力し、 11 を返します。 - -# キーワード引数で関数を呼ぶこともできます。 -add(y=6, x=5) # キーワード引数を使うと任意の順番で引数を指定できます。 - - -# 可変数の位置引数を持つ関数を定義できます。 -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - - -# 可変数のキーワード引数を持つ関数を定義できます。 -def keyword_args(**kwargs): - return kwargs - -# 何が起こるか、試してみましょう -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# お望みなら、両方一気にやることもできます。 -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) prints: - (1, 2) - {"a": 3, "b": 4} -""" - -# 関数を呼ぶとき、 args/kwargs の逆のことをすることができます! -# * を使ってタプルを展開したり、 ** を使って辞書を展開できます。 -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # all_the_args(1, 2, 3, 4) と等しいです。 -all_the_args(**kwargs) # all_the_args(a=3, b=4) と等しいです。 -all_the_args(*args, **kwargs) # all_the_args(1, 2, 3, 4, a=3, b=4) と等しいです。 - - -# タプルで複数の値を返す -def swap(x, y): # 括弧を使わずに、複数の値をタプルとして返すことができます。 - return y, x # (Note: 括弧は使わなくてもいいですが、使うこともできます。) - - -x = 1 -y = 2 -x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # このように、括弧は使っても使わなくてもいいです。 - - -# 関数のスコープ -x = 5 - - -def set_x(num): - # ローカル変数の x はグローバル変数の x とは異なります - x = num # => 43 - print(x) # => 43 - - -def set_global_x(num): - global x - print(x) # => 5 - x = num # グローバル変数の x に 6 が代入されました。 - print(x) # => 6 - -set_x(43) -set_global_x(6) - - -# Pythonは第一級関数をサポートします。 -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# 無名関数もサポートしています。 -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# 高階関数も組込まれています。 -list(map(add_10, [1, 2, 3])) # => [11, 12, 13] -list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] - -list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] - -# map や filter の代わりに、リスト内包表記を使うことができます。 -# リスト内包表記は、出力を別のリスト内包表記にネストさせることができます。 -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -# 集合(set)や辞書も内包表記ができます。 -{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} -{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} - - -#################################################### -# 5. モジュール -#################################################### - -# Pythonではモジュールをインポートできます。 -import math -print(math.sqrt(16)) # => 4.0 - -# モジュールの中から特定の関数をインポートすることもできます。 -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# 全部の関数をモジュールからインポートすることができます。 -# Warning: この方法は推奨されません。 -from math import * - -# 短い名前でモジュールをインポートすることができます。 -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Pythonのモジュールは実際には単なるPythonのファイルです。 -# 自分で書くことも、インポートすることもできます。 -# ファイル名がそのままモジュール名になります。 - -# モジュールで定義されている関数と属性を調べることができます。 -import math -dir(math) - -# もし、現在書いているスクリプトと同じフォルダに「math.py」という -# Pythonのスクリプトが存在する場合、そのmath.pyが -# 組み込みのPythonモジュールの代わりに読み込まれるでしょう。 -# これは、ローカルのフォルダはPythonの組み込みライブラリよりも -# 優先度が高いため発生するのです。 - - -#################################################### -# 6. クラス -#################################################### - -# クラスを作成するために、class文を使います。 -class Human: - - # クラスの属性です。このクラスの全てのインスタンスで共有されます。 - species = "H. sapiens" - - # 標準的なイニシャライザで、このクラスがインスタンスを作成するときは毎回呼ばれます。 - # 2つのアンダースコアがオブジェクトや属性の前後についているとき、これらはPythonによって利用され、 - # ユーザーの名前空間には存在しないということに注意してください。 - # __init__ や __str__ 、 __repr__ のようなメソッド(やオブジェクト、属性)は、 - # special methods (または dunder methods)と呼ばれます。 - # 同じような名前を自分で発明しないほうがよいでしょう。 - def __init__(self, name): - # 引数をインスタンスのname属性に設定します。 - self.name = name - - # プロパティの初期化 - self._age = 0 - - # インスタンスメソッド。全てのメソッドは"self"を最初の引数に取ります。 - def say(self, msg): - print("{name}: {message}".format(name=self.name, message=msg)) - - # 別のインスタンスメソッドの例。 - def sing(self): - return 'yo... yo... microphone check... one two... one two...' - - # クラスメソッドは全てのインスタンスで共有されます。 - # クラスメソッドではクラスを最初の引数として呼ばれます。 - @classmethod - def get_species(cls): - return cls.species - - # スタティックメソッドはクラスやインスタンスを参照せずに呼ばれます。 - @staticmethod - def grunt(): - return "*grunt*" - - # プロパティはgetterのようなものです。 - # age() メソッドを同名の読取専用属性に変換します。 - # Pythonではわざわざgetterやsetterを書く必要はありません。 - @property - def age(self): - return self._age - - # プロパティを設定できるようにします。 - @age.setter - def age(self, age): - self._age = age - - # プロパティを削除できるようにします。 - @age.deleter - def age(self): - del self._age - - -# Pythonインタプリタがソースファイルを読み込んだとき、全てのコードを実行します。 -# この __name__ による確認により、このモジュールがメインのプログラムである場合にのみ、 -# このコードブロックが実行されるようにします。 -if __name__ == '__main__': - # クラスのインスタンスを作成します。 - i = Human(name="Ian") - i.say("hi") # "Ian: hi" - j = Human("Joel") - j.say("hello") # "Joel: hello" - # i と j はHumanのインスタンスです。別の言葉で言うなら、これらはHumanのオブジェクトです。 - - # クラスメソッドを呼んでみましょう。 - i.say(i.get_species()) # "Ian: H. sapiens" - # 共有属性を変更してみましょう。 - Human.species = "H. neanderthalensis" - i.say(i.get_species()) # => "Ian: H. neanderthalensis" - j.say(j.get_species()) # => "Joel: H. neanderthalensis" - - # スタティックメソッドを呼んでみましょう。 - print(Human.grunt()) # => "*grunt*" - - # スタティックメソッドはインスタンスから呼ぶことはできません。 - # なぜならば、 i.grunt() は自動的に"self" ( i オブジェクト ) を引数として渡してしまうからです。 - print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given - - # インスタンスのプロパティを更新してみましょう。 - i.age = 42 - # プロパティを取得してみましょう。 - i.say(i.age) # => "Ian: 42" - j.say(j.age) # => "Joel: 0" - # プロパティを削除してみましょう。 - del i.age - # i.age # => AttributeError が発生します。 - - -#################################################### -# 6.1 継承 -#################################################### -# 継承を行うことで、親クラスからメソッドと変数を継承する新しい子クラスを定義できます。 - -# 上記で定義されたHumanクラスを親クラス(基底クラス)として使い、Superheroという子クラスを定義します。 -# これは"species"、"name"や"age"といった変数や、"sing"や"grunt"のようなメソッドをHumanから継承しますが、 -# Superhero独自のプロパティを持つこともできます。 - -# ファイルを分割してモジュール化の利点を活用するために、上記のHumanクラスを独自のファイル、ここでは human.py に記述ましょう。 - -# 別のファイルから関数をインポートするには次の形式を利用してください: -# from "拡張子なしのファイル名" import "関数やクラス" - -from human import Human - - -# 親クラスを子クラスのパラメータとして指定します -class Superhero(Human): - - # もし子クラスが親クラスの全ての定義を変更なしで継承する場合、"pass"キーワードのみを書くだけで良いです。 - # しかし、今回は親クラスとは異なる子クラスを作成するので、今回は以下の通りコメントアウトしています。 - # pass - - # 子クラスは親クラスの属性を上書きできます。 - species = 'Superhuman' - - # 子クラスは親クラスのコンストラクタを引数含めて自動的に継承しますが、 - # 追加の引数や定義を行ってコンストラクタのようなメソッドを上書きすることもできます。 - # このコンストラクタは"name"引数を"Human"クラスから継承し、"superpower"と"movie"という引数を追加します。 - def __init__(self, name, movie=False, - superpowers=["super strength", "bulletproofing"]): - - # 追加のクラス属性を作成する - self.fictional = True - self.movie = movie - # デフォルト値は共有されるので、可変のデフォルト値には注意してください。 - self.superpowers = superpowers - - # "super"関数を使うと子クラスに上書きされた親クラスのメソッド(今回は "__init__")にアクセスできます。 - # これで、親クラスのコンストラクタを呼んでいます。 - super().__init__(name) - - # singメソッドを上書きし、 - def sing(self): - return 'Dun, dun, DUN!' - - # 追加のインスタンスメソッドを作成します。 - def boast(self): - for power in self.superpowers: - print("I wield the power of {pow}!".format(pow=power)) - - -if __name__ == '__main__': - sup = Superhero(name="Tick") - - # インスタンスの型を調べる - if isinstance(sup, Human): - print('I am human') - if type(sup) is Superhero: - print('I am a superhero') - - # getattr()とsuper()で使われるメソッドの解決順序を調べてみます。 - # この属性は動的であり、変更可能です。 - print(Superhero.__mro__) # => (, - # => , ) - - # 親のメソッドを呼びだすものの、独自のクラス属性を参照します。 - print(sup.get_species()) # => Superhuman - - # 上書きされたメソッドを呼ぶ - print(sup.sing()) # => Dun, dun, DUN! - - # Humanのメソッドを呼ぶ - sup.say('Spoon') # => Tick: Spoon - - # Superhero限定のメソッドを呼ぶ - sup.boast() # => I wield the power of super strength! - # => I wield the power of bulletproofing! - - # 継承されたクラス属性 - sup.age = 31 - print(sup.age) # => 31 - - # Superhero限定の属性 - print('Am I Oscar eligible? ' + str(sup.movie)) - - - -#################################################### -# 6.2 多重継承 -#################################################### - -# 別のクラスを定義します。 -# bat.py -class Bat: - - species = 'Baty' - - def __init__(self, can_fly=True): - self.fly = can_fly - - # このクラスも say メソッドを持ちます。 - def say(self, msg): - msg = '... ... ...' - return msg - - # 同様に、独自のメソッドも与えましょう。 - def sonar(self): - return '))) ... (((' - -if __name__ == '__main__': - b = Bat() - print(b.say('hello')) - print(b.fly) - -# superhero.py -from superhero import Superhero -from bat import Bat - -# BatmanをSuperheroとBatの両方を継承した子クラスとして定義します。 -class Batman(Superhero, Bat): - - def __init__(self, *args, **kwargs): - # 通常、属性を継承するにはsuper()を呼び出します。 - # super(Batman, self).__init__(*args, **kwargs) - # しかし、ここでは多重継承を行っているので、 super() はMRO(メソッド解決順序)の次の基本クラスにのみ動作します。 - # なので、全ての祖先に対して明示的に __init__ を呼ぶことにします。 - # *args と **kwargs を使うことで、それぞれの継承元が - # たまねぎの皮を剥がすごとく、引数を用いることができます。 - Superhero.__init__(self, 'anonymous', movie=True, - superpowers=['Wealthy'], *args, **kwargs) - Bat.__init__(self, *args, can_fly=False, **kwargs) - # 名前の属性の値を上書きします。 - self.name = 'Sad Affleck' - - def sing(self): - return 'nan nan nan nan nan batman!' - - -if __name__ == '__main__': - sup = Batman() - - # getattr() や super() の両方で使われるMROを取得します。 - # この属性は動的であり、更新が可能です。 - print(Batman.__mro__) # => (, - # => , - # => , - # => , ) - - - # 親メソッドを呼び出しますが、独自のクラス属性を参照します。 - print(sup.get_species()) # => Superhuman - - # 上書きされたメソッドを呼び出します。 - print(sup.sing()) # => nan nan nan nan nan batman! - - # 継承順により、Humanから継承されたメソッドを呼び出します。 - sup.say('I agree') # => Sad Affleck: I agree - - # 2番目の先祖にのみ存在するメソッドを呼び出してみます。 - print(sup.sonar()) # => ))) ... ((( - - # 継承されたクラス属性 - sup.age = 100 - print(sup.age) # => 100 - - # デフォルト値が上書きされて、2番目の先祖から継承された属性 - print('Can I fly? ' + str(sup.fly)) # => Can I fly? False - - -#################################################### -# 7. 発展的内容 -#################################################### - -# ジェネレータは遅延をするコードの作成に役立ちます。 -def double_numbers(iterable): - for i in iterable: - yield i + i - -# 次の値を処理するのに必要なデータしか読み込まないので、ジェネレータはメモリをあまり消費しません。 -# この性質により、他の方法では非常に多くのメモリを消費するような操作が可能になります。 -for i in double_numbers(range(1, 900000000)): # `range` もジェネレータの1つです。 - print(i) - if i >= 30: - break - -# リスト内包表記のように、ジェネータ内包表記を作成することもできます。 -values = (-x for x in [1, 2, 3, 4, 5]) -for x in values: - print(x) # prints -1 -2 -3 -4 -5 - -# ジェネレータ内包表記から直接リストを作成することもできます。 -values = (-x for x in [1, 2, 3, 4, 5]) -gen_to_list = list(values) -print(gen_to_list) # => [-1, -2, -3, -4, -5] - -# デコレータ -# この例では`beg` が `say` を `wraps`します。 -# もし say_please が True なら、出力が変更されます。 -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please - - -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( -``` - -## Ready For More? - -### Free Online - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) -* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) -* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) -* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) -* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) -* [Dive Into Python 3](http://www.diveintopython3.net/index.html) -* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/pt-br/python-pt.html.markdown b/pt-br/python-pt.html.markdown new file mode 100644 index 00000000..bc5f801c --- /dev/null +++ b/pt-br/python-pt.html.markdown @@ -0,0 +1,746 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] +translators: + - ["Paulo Henrique Rodrigues Pinheiro", "http://www.sysincloud.it"] + - ["Monique Baptista", "https://github.com/bfmonique"] +lang: pt-br +filename: learnpython3-pt.py +--- + +Python foi criada por Guido Van Rossum nos anos 1990. Ela é atualmente uma +das linguagens mais populares existentes. Eu me apaixonei por +Python por sua clareza sintática. É praticamente pseudocódigo executável. + +Opniões são muito bem vindas. Você pode encontrar-me em +[@louiedinh](http://twitter.com/louiedinh) ou louiedinh [em] +[serviço de e-mail do google]. + +Observação: Este artigo trata de Python 3 especificamente. Verifique +[aqui](http://learnxinyminutes.com/docs/pt-br/python-pt/) se você pretende +aprender o velho Python 2.7. + +```python + +# Comentários em uma única linha começam com uma cerquilha (também conhecido por sustenido). + +""" Strings de várias linhas podem ser escritas + usando três ", e são comumente usadas + como comentários. +""" + +#################################################### +## 1. Tipos de dados primitivos e operadores +#################################################### + +# Você usa números normalmente +3 # => 3 + +# Matemática é como você espera que seja +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Números são inteiros por padrão, exceto na divisão, que retorna número +# de ponto flutuante (float). +35 / 5 # => 7.0 + +# O resultado da divisão inteira arredonda para baixo tanto para números +# positivos como para negativos. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # funciona em float também +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Quando você usa um float, o resultado é float. +3 * 2.0 # => 6.0 + +# operador módulo +7 % 3 # => 1 + +# Exponenciação (x**y, x elevado à potência y) +2**4 # => 16 + +# Determine a precedência usando parênteses +(1 + 3) * 2 # => 8 + +# Valores lógicos são primitivos (Atenção à primeira letra maiúscula) +True +False + +# negação lógica com not +not True # => False +not False # => True + +# Operadores lógicos +# Observe que "and" e "or" são sensíveis a maiúsculas e minúsculas +True and False # => False +False or True # => True + +# Observe a utilização de operadores lógicos com números inteiros +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True + +# Igualdade é == +1 == 1 # => True +2 == 1 # => False + +# Diferença é != +1 != 1 # => False +2 != 1 # => True + +# Mais comparações +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Comparações podem ser agrupadas +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# 'is' verifica se duas variáveis representam o mesmo endereço +# na memória; '==' verifica se duas variáveis têm o mesmo valor +a = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4] +b = a # b referencia o que está referenciado por a +b is a # => True, a e b referenciam o mesmo objeto +b == a # => True, objetos a e b tem o mesmo conteúdo +b = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4] +b is a # => False, a e b não referenciam o mesmo objeto +b == a # => True, objetos a e b tem o mesmo conteúdo + +# Strings são criadas com " ou ' +"Isto é uma string." +'Isto também é uma string.' + +# Strings também podem ser somadas! Mas tente não fazer isso. +"Olá " + "mundo!" # => "Olá mundo!" +# Strings podem ser somadas sem usar o '+' +"Olá " "mundo!" # => "Olá mundo!" + +# Uma string pode ser manipulada como se fosse uma lista de caracteres +"Isso é uma string"[0] # => 'I' + +# .format pode ser usado para formatar strings, dessa forma: +"{} podem ser {}".format("Strings", "interpoladas") # => "Strings podem ser interpoladas" + +# Você pode repetir os argumentos para digitar menos. +"Seja ágil {0}, seja rápido {0}, salte sobre o {1} {0}".format("Jack", "castiçal") +# => "Seja ágil Jack, seja rápido Jack, salte sobre o castiçal Jack." + +# Você pode usar palavras-chave se quiser contar. +"{nome} quer comer {comida}".format(nome="Beto", comida="lasanha") # => "Beto quer comer lasanha" + +# Se você precisa executar seu código Python3 com um interpretador Python 2.5 ou acima, você pode usar a velha forma para formatação de texto: +"%s podem ser %s da forma %s" % ("Strings", "interpoladas", "antiga") # => "Strings podem ser interpoladas da forma antiga" + + +# None é um objeto +None # => None + +# Não use o operador de igualdade "==" para comparar objetos com None +# Use "is" para isso. Ele checará pela identidade dos objetos. +"etc" is None # => False +None is None # => True + +# None, 0, e strings/listas/dicionários vazios todos retornam False. +# Qualquer outra coisa retorna True +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False + + +#################################################### +## 2. Variáveis e coleções +#################################################### + +# Python tem uma função print +print("Eu sou o Python. Prazer em conhecer!") # => Eu sou o Python. Prazer em conhecer! + +# Por padrão a função print também imprime o caractere de nova linha ao final. +# Use o argumento opcional end para mudar o caractere final. +print("Olá, Mundo", end="!") # => Olá, Mundo! + +# Forma simples para capturar dados de entrada via console +input_string_var = input("Digite alguma coisa: ") # Retorna o que foi digitado em uma string +# Observação: Em versões antigas do Python, o método input() era chamado raw_input() + +# Não é necessário declarar variáveis antes de iniciá-las +# É uma convenção usar letras_minúsculas_com_sublinhados +alguma_variavel = 5 +alguma_variavel # => 5 + +# Acessar uma variável que não tenha sido inicializada gera uma exceção. +# Veja Controle de Fluxo para aprender mais sobre tratamento de exceções. +alguma_variavel_nao_inicializada # Gera a exceção NameError + +# Listas armazenam sequências +li = [] +# Você pode iniciar uma lista com valores +outra_li = [4, 5, 6] + +# Adicione conteúdo ao fim da lista com append +li.append(1) # li agora é [1] +li.append(2) # li agora é [1, 2] +li.append(4) # li agora é [1, 2, 4] +li.append(3) # li agora é [1, 2, 4, 3] +# Remova do final da lista com pop +li.pop() # => 3 e agora li é [1, 2, 4] +# Vamos colocá-lo lá novamente! +li.append(3) # li agora é [1, 2, 4, 3] novamente. + +# Acesse uma lista da mesma forma que você faz com um array +li[0] # => 1 +# Acessando o último elemento +li[-1] # => 3 + +# Acessar além dos limites gera um IndexError +li[4] # Gera o IndexError + +# Você pode acessar vários elementos com a sintaxe de limites +# Inclusivo para o primeiro termo, exclusivo para o segundo +li[1:3] # => [2, 4] +# Omitindo o final +li[2:] # => [4, 3] +# Omitindo o início +li[:3] # => [1, 2, 4] +# Selecione cada segunda entrada +li[::2] # => [1, 4] +# Tenha uma cópia em ordem invertida da lista +li[::-1] # => [3, 4, 2, 1] +# Use qualquer combinação dessas para indicar limites complexos +# li[inicio:fim:passo] + +# Faça uma cópia profunda de um nível usando limites +li2 = li[:] # => li2 = [1, 2, 4, 3] mas (li2 is li) resultará em False. + +# Apague elementos específicos da lista com "del" +del li[2] # li agora é [1, 2, 3] + +# Você pode somar listas +# Observação: valores em li e other_li não são modificados. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Concatene listas com "extend()" +li.extend(other_li) # Agora li é [1, 2, 3, 4, 5, 6] + +# Verifique se algo existe na lista com "in" +1 in li # => True + +# Examine tamanho com "len()" +len(li) # => 6 + + +# Tuplas são como l istas, mas imutáveis. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Gera um TypeError + +# Observe que uma tupla de tamanho um precisa ter uma vírgula depois do +# último elemento mas tuplas de outros tamanhos, mesmo vazias, não precisa,. +type((1)) # => +type((1,)) # => +type(()) # => + +# Você pode realizar com tuplas a maior parte das operações que faz com listas +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Você pode desmembrar tuplas (ou listas) em variáveis. +a, b, c = (1, 2, 3) # a é 1, b é 2 e c é 3 +# Por padrão, tuplas são criadas se você não coloca parêntesis. +d, e, f = 4, 5, 6 +# Veja como é fácil permutar dois valores +e, d = d, e # d é 5, e é 4 + +# Dicionários armazenam mapeamentos +empty_dict = {} +# Aqui está um dicionário preenchido na definição da referência +filled_dict = {"um": 1, "dois": 2, "três": 3} + +# Observe que chaves para dicionários devem ser tipos imutáveis. Isto é para +# assegurar que a chave pode ser convertida para uma valor hash constante para +# buscas rápidas. +# Tipos imutáveis incluem inteiros, flotas, strings e tuplas. +invalid_dict = {[1,2,3]: "123"} # => Gera um TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Já os valores, podem ser de qualquer tipo. + +# Acesse valores com [] +filled_dict["um"] # => 1 + +# Acesse todas as chaves como um iterável com "keys()". É necessário encapsular +# a chamada com um list() para transformá-las em uma lista. Falaremos sobre isso +# mais adiante. Observe que a ordem de uma chave de dicionário não é garantida. +# Por isso, os resultados aqui apresentados podem não ser exatamente como os +# aqui apresentados. +list(filled_dict.keys()) # => ["três", "dois", "um"] + + +# Acesse todos os valores de um iterável com "values()". Novamente, é +# necessário encapsular ele com list() para não termos um iterável, e sim os +# valores. Observe que, como foi dito acima, a ordem dos elementos não é +# garantida. +list(filled_dict.values()) # => [3, 2, 1] + + +# Verifique a existência de chaves em um dicionário com "in" +"um" in filled_dict # => True +1 in filled_dict # => False + +# Acessar uma chave inexistente gera um KeyError +filled_dict["quatro"] # KeyError + +# Use o método "get()" para evitar um KeyError +filled_dict.get("um") # => 1 +filled_dict.get("quatro") # => None +# O método get permite um parâmetro padrão para quando não existir a chave +filled_dict.get("um", 4) # => 1 +filled_dict.get("quatro", 4) # => 4 + +# "setdefault()" insere em dicionário apenas se a dada chave não existir +filled_dict.setdefault("cinco", 5) # filled_dict["cinco"] tem valor 5 +filled_dict.setdefault("cinco", 6) # filled_dict["cinco"] continua 5 + +# Inserindo em um dicionário +filled_dict.update({"quatro":4}) # => {"um": 1, "dois": 2, "três": 3, "quatro": 4} +#filled_dict["quatro"] = 4 #outra forma de inserir em um dicionário + +# Remova chaves de um dicionário com del +del filled_dict["um"] # Remove a chave "um" de filled_dict + + +# Armazenamento em sets... bem, são conjuntos +empty_set = set() +# Inicializa um set com alguns valores. Sim, ele parece um dicionário. Desculpe. +some_set = {1, 1, 2, 2, 3, 4} # some_set agora é {1, 2, 3, 4} + +# Da mesma forma que chaves em um dicionário, elementos de um set devem ser +# imutáveis. +invalid_set = {[1], 1} # => Gera um TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# Pode definir novas variáveis para um conjunto +filled_set = some_set + +# Inclua mais um item no set +filled_set.add(5) # filled_set agora é {1, 2, 3, 4, 5} + +# Faça interseção de conjuntos com & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Faça união de conjuntos com | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Faça a diferença entre conjuntos com - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Verifique a existência em um conjunto com in +2 in filled_set # => True +10 in filled_set # => False + + + +#################################################### +## 3. Controle de fluxo e iteráveis +#################################################### + +# Iniciemos um variável +some_var = 5 + +# Aqui está uma expressão if. Indentação é significante em python! +# imprime "somevar é menor que10" +if some_var > 10: + print("some_var é absolutamente maior que 10.") +elif some_var < 10: # Esta cláusula elif é opcional. + print("some_var é menor que 10.") +else: # Isto também é opcional. + print("some_var é, de fato, 10.") + + +""" +Laços for iteram sobre listas +imprime: + cachorro é um mamífero + gato é um mamífero + rato é um mamífero +""" +for animal in ["cachorro", "gato", "rato"]: + # Você pode usar format() para interpolar strings formatadas + print("{} é um mamífero".format(animal)) + +""" +"range(número)" retorna um iterável de números +de zero até o número escolhido +imprime: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(menor, maior)" gera um iterável de números +começando pelo menor até o maior +imprime: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(menor, maior, passo)" retorna um iterável de números +começando pelo menor número até o maior númeno, pulando de +passo em passo. Se o passo não for indicado, o valor padrão é um. +imprime: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) +""" + +Laços while executam até que a condição não seja mais válida. +imprime: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Maneira mais curta para for x = x + 1 + +# Lide com exceções com um bloco try/except +try: + # Use "raise" para gerar um erro + raise IndexError("Isto é um erro de índice") +except IndexError as e: + pass # Pass é um não-operador. Normalmente você usa algum código de recuperação aqui. +except (TypeError, NameError): + pass # Varias exceções podem ser gerenciadas, se necessário. +else: # Cláusula opcional para o bloco try/except. Deve estar após todos os blocos de exceção. + print("Tudo certo!") # Executa apenas se o código em try não gera exceção +finally: # Sempre é executado + print("Nós podemos fazer o código de limpeza aqui.") + +# Ao invés de try/finally para limpeza você pode usar a cláusula with +with open("myfile.txt") as f: + for line in f: + print(line) + +# Python provê uma abstração fundamental chamada Iterável. +# Um iterável é um objeto que pode ser tratado como uma sequência. +# O objeto retornou a função range, um iterável. + +filled_dict = {"um": 1, "dois": 2, "três": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => range(1,10). Esse é um objeto que implementa nossa interface iterável. + +# Nós podemos percorrê-la. +for i in our_iterable: + print(i) # Imprime um, dois, três + +# Mas não podemos acessar os elementos pelo seu índice. +our_iterable[1] # Gera um TypeError + +# Um iterável é um objeto que sabe como criar um iterador. +our_iterator = iter(our_iterable) + +# Nosso iterador é um objeto que pode lembrar o estado enquanto nós o percorremos. +# Nós acessamos o próximo objeto com "next()". +next(our_iterator) # => "um" + +# Ele mantém o estado enquanto nós o percorremos. +next(our_iterator) # => "dois" +next(our_iterator) # => "três" + +# Após o iterador retornar todos os seus dados, ele gera a exceção StopIterator +next(our_iterator) # Gera StopIteration + +# Você pode capturar todos os elementos de um iterador aplicando list() nele. +list(filled_dict.keys()) # => Retorna ["um", "dois", "três"] + + +#################################################### +## 4. Funções +#################################################### + +# Use "def" para criar novas funções. +def add(x, y): + print("x é {} e y é {}".format(x, y)) + return x + y # Retorne valores com a cláusula return + +# Chamando funções com parâmetros +add(5, 6) # => imprime "x é 5 e y é 6" e retorna 11 + +# Outro meio de chamar funções é com argumentos nomeados +add(y=6, x=5) # Argumentos nomeados podem aparecer em qualquer ordem. + +# Você pode definir funções que pegam um número variável de argumentos +# posicionais +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# Você pode definir funções que pegam um número variável de argumentos nomeados +# também +def keyword_args(**kwargs): + return kwargs + +# Vamos chamá-lo para ver o que acontece +keyword_args(peh="grande", lago="ness") # => {"peh": "grande", "lago": "ness"} + + +# Você pode fazer ambos simultaneamente, se você quiser +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) imprime: + (1, 2) + {"a": 3, "b": 4} +""" + +# Quando chamar funções, você pode fazer o oposto de args/kwargs! +# Use * para expandir tuplas e use ** para expandir dicionários! +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalente a foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalente a foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4) + +# Retornando múltiplos valores (com atribuição de tuplas) +def swap(x, y): + return y, x # Retorna múltiplos valores como uma tupla sem os parêntesis. + # (Observação: os parêntesis foram excluídos mas podem estar + # presentes) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Novamente, os parêntesis foram excluídos mas podem estar presentes. + +# Escopo de função +x = 5 + +def setX(num): + # A variável local x não é a mesma variável global x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # variável global x agora é 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# Python tem funções de primeira classe +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Também existem as funções anônimas +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# TODO - Fix for iterables +# Existem funções internas de alta ordem +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Nós podemos usar compreensão de lista para interessantes mapas e filtros +# Compreensão de lista armazena a saída como uma lista que pode ser uma lista +# aninhada +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. Classes +#################################################### + + +# Nós usamos o operador "class" para ter uma classe +class Human: + + # Um atributo de classe. Ele é compartilhado por todas as instâncias dessa + # classe. + species = "H. sapiens" + + # Construtor básico, é chamado quando esta classe é instanciada. + # Note que dois sublinhados no início e no final de uma identificados + # significa objetos ou atributos que são usados pelo python mas vivem em + # um namespace controlado pelo usuário. Métodos (ou objetos ou atributos) + # como: __init__, __str__, __repr__, etc. são chamados métodos mágicos (ou + # algumas vezes chamados métodos dunder - "double underscore") + # Você não deve usar nomes assim por sua vontade. + def __init__(self, name): + @ Atribui o argumento ao atributo da instância + self.name = name + + # Um método de instância. Todos os métodos tem "self" como primeiro + # argumento + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # Um método de classe é compartilhado por todas as instâncias + # Eles são chamados com a classe requisitante como primeiro argumento + @classmethod + def get_species(cls): + return cls.species + + # Um método estático é chamado sem uma referência a classe ou instância + @staticmethod + def grunt(): + return "*grunt*" + + +# Instancie uma classe +i = Human(name="Ian") +print(i.say("oi")) # imprime "Ian: oi" + +j = Human("Joel") +print(j.say("olá")) # imprime "Joel: olá" + +# Chama nosso método de classe +i.get_species() # => "H. sapiens" + +# Altera um atributo compartilhado +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Chama o método estático +Human.grunt() # => "*grunt*" + + +#################################################### +## 6. Módulos +#################################################### + +# Você pode importar módulos +import math +print(math.sqrt(16)) # => 4.0 + +# Você pode importar apenas funções específicas de um módulo +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Você pode importar todas as funções de um módulo para o namespace atual +# Atenção: isso não é recomendado +from math import * + +# Você pode encurtar o nome dos módulos +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Módulos python são apenas arquivos python comuns. Você +# pode escrever os seus, e importá-los. O nome do +# módulo é o mesmo nome do arquivo. + +# Você pode procurar que atributos e funções definem um módulo. +import math +dir(math) + + +#################################################### +## 7. Avançado +#################################################### + +# Geradores podem ajudar você a escrever código "preguiçoso" +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Um gerador cria valores conforme necessário. +# Ao invés de gerar e retornar todos os valores de uma só vez ele cria um em +# cada interação. Isto significa que valores maiores que 15 não serão +# processados em double_numbers. +# Nós usamos um sublinhado ao final do nome das variáveis quando queremos usar +# um nome que normalmente colide com uma palavra reservada do python. +range_ = range(1, 900000000) +# Multiplica por 2 todos os números até encontrar um resultado >= 30 +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Decoradores +# Neste exemplo beg encapsula say +# beg irá chamar say. Se say_please é verdade então ele irá mudar a mensagem +# retornada +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Por favor! Eu sou pobre :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Você me paga uma cerveja?" + return msg, say_please + + +print(say()) # Você me paga uma cerveja? +print(say(say_please=True)) # Você me paga uma cerveja? Por favor! Eu sou pobre :( +``` + +## Pronto para mais? + +### Free Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) + +### Dead Tree + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/pt-br/python3-pt.html.markdown b/pt-br/python3-pt.html.markdown deleted file mode 100644 index bc5f801c..00000000 --- a/pt-br/python3-pt.html.markdown +++ /dev/null @@ -1,746 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] -translators: - - ["Paulo Henrique Rodrigues Pinheiro", "http://www.sysincloud.it"] - - ["Monique Baptista", "https://github.com/bfmonique"] -lang: pt-br -filename: learnpython3-pt.py ---- - -Python foi criada por Guido Van Rossum nos anos 1990. Ela é atualmente uma -das linguagens mais populares existentes. Eu me apaixonei por -Python por sua clareza sintática. É praticamente pseudocódigo executável. - -Opniões são muito bem vindas. Você pode encontrar-me em -[@louiedinh](http://twitter.com/louiedinh) ou louiedinh [em] -[serviço de e-mail do google]. - -Observação: Este artigo trata de Python 3 especificamente. Verifique -[aqui](http://learnxinyminutes.com/docs/pt-br/python-pt/) se você pretende -aprender o velho Python 2.7. - -```python - -# Comentários em uma única linha começam com uma cerquilha (também conhecido por sustenido). - -""" Strings de várias linhas podem ser escritas - usando três ", e são comumente usadas - como comentários. -""" - -#################################################### -## 1. Tipos de dados primitivos e operadores -#################################################### - -# Você usa números normalmente -3 # => 3 - -# Matemática é como você espera que seja -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 - -# Números são inteiros por padrão, exceto na divisão, que retorna número -# de ponto flutuante (float). -35 / 5 # => 7.0 - -# O resultado da divisão inteira arredonda para baixo tanto para números -# positivos como para negativos. -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # funciona em float também --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Quando você usa um float, o resultado é float. -3 * 2.0 # => 6.0 - -# operador módulo -7 % 3 # => 1 - -# Exponenciação (x**y, x elevado à potência y) -2**4 # => 16 - -# Determine a precedência usando parênteses -(1 + 3) * 2 # => 8 - -# Valores lógicos são primitivos (Atenção à primeira letra maiúscula) -True -False - -# negação lógica com not -not True # => False -not False # => True - -# Operadores lógicos -# Observe que "and" e "or" são sensíveis a maiúsculas e minúsculas -True and False # => False -False or True # => True - -# Observe a utilização de operadores lógicos com números inteiros -0 and 2 # => 0 --5 or 0 # => -5 -0 == False # => True -2 == True # => False -1 == True # => True - -# Igualdade é == -1 == 1 # => True -2 == 1 # => False - -# Diferença é != -1 != 1 # => False -2 != 1 # => True - -# Mais comparações -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# Comparações podem ser agrupadas -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# 'is' verifica se duas variáveis representam o mesmo endereço -# na memória; '==' verifica se duas variáveis têm o mesmo valor -a = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4] -b = a # b referencia o que está referenciado por a -b is a # => True, a e b referenciam o mesmo objeto -b == a # => True, objetos a e b tem o mesmo conteúdo -b = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4] -b is a # => False, a e b não referenciam o mesmo objeto -b == a # => True, objetos a e b tem o mesmo conteúdo - -# Strings são criadas com " ou ' -"Isto é uma string." -'Isto também é uma string.' - -# Strings também podem ser somadas! Mas tente não fazer isso. -"Olá " + "mundo!" # => "Olá mundo!" -# Strings podem ser somadas sem usar o '+' -"Olá " "mundo!" # => "Olá mundo!" - -# Uma string pode ser manipulada como se fosse uma lista de caracteres -"Isso é uma string"[0] # => 'I' - -# .format pode ser usado para formatar strings, dessa forma: -"{} podem ser {}".format("Strings", "interpoladas") # => "Strings podem ser interpoladas" - -# Você pode repetir os argumentos para digitar menos. -"Seja ágil {0}, seja rápido {0}, salte sobre o {1} {0}".format("Jack", "castiçal") -# => "Seja ágil Jack, seja rápido Jack, salte sobre o castiçal Jack." - -# Você pode usar palavras-chave se quiser contar. -"{nome} quer comer {comida}".format(nome="Beto", comida="lasanha") # => "Beto quer comer lasanha" - -# Se você precisa executar seu código Python3 com um interpretador Python 2.5 ou acima, você pode usar a velha forma para formatação de texto: -"%s podem ser %s da forma %s" % ("Strings", "interpoladas", "antiga") # => "Strings podem ser interpoladas da forma antiga" - - -# None é um objeto -None # => None - -# Não use o operador de igualdade "==" para comparar objetos com None -# Use "is" para isso. Ele checará pela identidade dos objetos. -"etc" is None # => False -None is None # => True - -# None, 0, e strings/listas/dicionários vazios todos retornam False. -# Qualquer outra coisa retorna True -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False - - -#################################################### -## 2. Variáveis e coleções -#################################################### - -# Python tem uma função print -print("Eu sou o Python. Prazer em conhecer!") # => Eu sou o Python. Prazer em conhecer! - -# Por padrão a função print também imprime o caractere de nova linha ao final. -# Use o argumento opcional end para mudar o caractere final. -print("Olá, Mundo", end="!") # => Olá, Mundo! - -# Forma simples para capturar dados de entrada via console -input_string_var = input("Digite alguma coisa: ") # Retorna o que foi digitado em uma string -# Observação: Em versões antigas do Python, o método input() era chamado raw_input() - -# Não é necessário declarar variáveis antes de iniciá-las -# É uma convenção usar letras_minúsculas_com_sublinhados -alguma_variavel = 5 -alguma_variavel # => 5 - -# Acessar uma variável que não tenha sido inicializada gera uma exceção. -# Veja Controle de Fluxo para aprender mais sobre tratamento de exceções. -alguma_variavel_nao_inicializada # Gera a exceção NameError - -# Listas armazenam sequências -li = [] -# Você pode iniciar uma lista com valores -outra_li = [4, 5, 6] - -# Adicione conteúdo ao fim da lista com append -li.append(1) # li agora é [1] -li.append(2) # li agora é [1, 2] -li.append(4) # li agora é [1, 2, 4] -li.append(3) # li agora é [1, 2, 4, 3] -# Remova do final da lista com pop -li.pop() # => 3 e agora li é [1, 2, 4] -# Vamos colocá-lo lá novamente! -li.append(3) # li agora é [1, 2, 4, 3] novamente. - -# Acesse uma lista da mesma forma que você faz com um array -li[0] # => 1 -# Acessando o último elemento -li[-1] # => 3 - -# Acessar além dos limites gera um IndexError -li[4] # Gera o IndexError - -# Você pode acessar vários elementos com a sintaxe de limites -# Inclusivo para o primeiro termo, exclusivo para o segundo -li[1:3] # => [2, 4] -# Omitindo o final -li[2:] # => [4, 3] -# Omitindo o início -li[:3] # => [1, 2, 4] -# Selecione cada segunda entrada -li[::2] # => [1, 4] -# Tenha uma cópia em ordem invertida da lista -li[::-1] # => [3, 4, 2, 1] -# Use qualquer combinação dessas para indicar limites complexos -# li[inicio:fim:passo] - -# Faça uma cópia profunda de um nível usando limites -li2 = li[:] # => li2 = [1, 2, 4, 3] mas (li2 is li) resultará em False. - -# Apague elementos específicos da lista com "del" -del li[2] # li agora é [1, 2, 3] - -# Você pode somar listas -# Observação: valores em li e other_li não são modificados. -li + other_li # => [1, 2, 3, 4, 5, 6] - -# Concatene listas com "extend()" -li.extend(other_li) # Agora li é [1, 2, 3, 4, 5, 6] - -# Verifique se algo existe na lista com "in" -1 in li # => True - -# Examine tamanho com "len()" -len(li) # => 6 - - -# Tuplas são como l istas, mas imutáveis. -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # Gera um TypeError - -# Observe que uma tupla de tamanho um precisa ter uma vírgula depois do -# último elemento mas tuplas de outros tamanhos, mesmo vazias, não precisa,. -type((1)) # => -type((1,)) # => -type(()) # => - -# Você pode realizar com tuplas a maior parte das operações que faz com listas -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# Você pode desmembrar tuplas (ou listas) em variáveis. -a, b, c = (1, 2, 3) # a é 1, b é 2 e c é 3 -# Por padrão, tuplas são criadas se você não coloca parêntesis. -d, e, f = 4, 5, 6 -# Veja como é fácil permutar dois valores -e, d = d, e # d é 5, e é 4 - -# Dicionários armazenam mapeamentos -empty_dict = {} -# Aqui está um dicionário preenchido na definição da referência -filled_dict = {"um": 1, "dois": 2, "três": 3} - -# Observe que chaves para dicionários devem ser tipos imutáveis. Isto é para -# assegurar que a chave pode ser convertida para uma valor hash constante para -# buscas rápidas. -# Tipos imutáveis incluem inteiros, flotas, strings e tuplas. -invalid_dict = {[1,2,3]: "123"} # => Gera um TypeError: unhashable type: 'list' -valid_dict = {(1,2,3):[1,2,3]} # Já os valores, podem ser de qualquer tipo. - -# Acesse valores com [] -filled_dict["um"] # => 1 - -# Acesse todas as chaves como um iterável com "keys()". É necessário encapsular -# a chamada com um list() para transformá-las em uma lista. Falaremos sobre isso -# mais adiante. Observe que a ordem de uma chave de dicionário não é garantida. -# Por isso, os resultados aqui apresentados podem não ser exatamente como os -# aqui apresentados. -list(filled_dict.keys()) # => ["três", "dois", "um"] - - -# Acesse todos os valores de um iterável com "values()". Novamente, é -# necessário encapsular ele com list() para não termos um iterável, e sim os -# valores. Observe que, como foi dito acima, a ordem dos elementos não é -# garantida. -list(filled_dict.values()) # => [3, 2, 1] - - -# Verifique a existência de chaves em um dicionário com "in" -"um" in filled_dict # => True -1 in filled_dict # => False - -# Acessar uma chave inexistente gera um KeyError -filled_dict["quatro"] # KeyError - -# Use o método "get()" para evitar um KeyError -filled_dict.get("um") # => 1 -filled_dict.get("quatro") # => None -# O método get permite um parâmetro padrão para quando não existir a chave -filled_dict.get("um", 4) # => 1 -filled_dict.get("quatro", 4) # => 4 - -# "setdefault()" insere em dicionário apenas se a dada chave não existir -filled_dict.setdefault("cinco", 5) # filled_dict["cinco"] tem valor 5 -filled_dict.setdefault("cinco", 6) # filled_dict["cinco"] continua 5 - -# Inserindo em um dicionário -filled_dict.update({"quatro":4}) # => {"um": 1, "dois": 2, "três": 3, "quatro": 4} -#filled_dict["quatro"] = 4 #outra forma de inserir em um dicionário - -# Remova chaves de um dicionário com del -del filled_dict["um"] # Remove a chave "um" de filled_dict - - -# Armazenamento em sets... bem, são conjuntos -empty_set = set() -# Inicializa um set com alguns valores. Sim, ele parece um dicionário. Desculpe. -some_set = {1, 1, 2, 2, 3, 4} # some_set agora é {1, 2, 3, 4} - -# Da mesma forma que chaves em um dicionário, elementos de um set devem ser -# imutáveis. -invalid_set = {[1], 1} # => Gera um TypeError: unhashable type: 'list' -valid_set = {(1,), 1} - -# Pode definir novas variáveis para um conjunto -filled_set = some_set - -# Inclua mais um item no set -filled_set.add(5) # filled_set agora é {1, 2, 3, 4, 5} - -# Faça interseção de conjuntos com & -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# Faça união de conjuntos com | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# Faça a diferença entre conjuntos com - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Verifique a existência em um conjunto com in -2 in filled_set # => True -10 in filled_set # => False - - - -#################################################### -## 3. Controle de fluxo e iteráveis -#################################################### - -# Iniciemos um variável -some_var = 5 - -# Aqui está uma expressão if. Indentação é significante em python! -# imprime "somevar é menor que10" -if some_var > 10: - print("some_var é absolutamente maior que 10.") -elif some_var < 10: # Esta cláusula elif é opcional. - print("some_var é menor que 10.") -else: # Isto também é opcional. - print("some_var é, de fato, 10.") - - -""" -Laços for iteram sobre listas -imprime: - cachorro é um mamífero - gato é um mamífero - rato é um mamífero -""" -for animal in ["cachorro", "gato", "rato"]: - # Você pode usar format() para interpolar strings formatadas - print("{} é um mamífero".format(animal)) - -""" -"range(número)" retorna um iterável de números -de zero até o número escolhido -imprime: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -"range(menor, maior)" gera um iterável de números -começando pelo menor até o maior -imprime: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -"range(menor, maior, passo)" retorna um iterável de números -começando pelo menor número até o maior númeno, pulando de -passo em passo. Se o passo não for indicado, o valor padrão é um. -imprime: - 4 - 6 -""" -for i in range(4, 8, 2): - print(i) -""" - -Laços while executam até que a condição não seja mais válida. -imprime: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Maneira mais curta para for x = x + 1 - -# Lide com exceções com um bloco try/except -try: - # Use "raise" para gerar um erro - raise IndexError("Isto é um erro de índice") -except IndexError as e: - pass # Pass é um não-operador. Normalmente você usa algum código de recuperação aqui. -except (TypeError, NameError): - pass # Varias exceções podem ser gerenciadas, se necessário. -else: # Cláusula opcional para o bloco try/except. Deve estar após todos os blocos de exceção. - print("Tudo certo!") # Executa apenas se o código em try não gera exceção -finally: # Sempre é executado - print("Nós podemos fazer o código de limpeza aqui.") - -# Ao invés de try/finally para limpeza você pode usar a cláusula with -with open("myfile.txt") as f: - for line in f: - print(line) - -# Python provê uma abstração fundamental chamada Iterável. -# Um iterável é um objeto que pode ser tratado como uma sequência. -# O objeto retornou a função range, um iterável. - -filled_dict = {"um": 1, "dois": 2, "três": 3} -our_iterable = filled_dict.keys() -print(our_iterable) # => range(1,10). Esse é um objeto que implementa nossa interface iterável. - -# Nós podemos percorrê-la. -for i in our_iterable: - print(i) # Imprime um, dois, três - -# Mas não podemos acessar os elementos pelo seu índice. -our_iterable[1] # Gera um TypeError - -# Um iterável é um objeto que sabe como criar um iterador. -our_iterator = iter(our_iterable) - -# Nosso iterador é um objeto que pode lembrar o estado enquanto nós o percorremos. -# Nós acessamos o próximo objeto com "next()". -next(our_iterator) # => "um" - -# Ele mantém o estado enquanto nós o percorremos. -next(our_iterator) # => "dois" -next(our_iterator) # => "três" - -# Após o iterador retornar todos os seus dados, ele gera a exceção StopIterator -next(our_iterator) # Gera StopIteration - -# Você pode capturar todos os elementos de um iterador aplicando list() nele. -list(filled_dict.keys()) # => Retorna ["um", "dois", "três"] - - -#################################################### -## 4. Funções -#################################################### - -# Use "def" para criar novas funções. -def add(x, y): - print("x é {} e y é {}".format(x, y)) - return x + y # Retorne valores com a cláusula return - -# Chamando funções com parâmetros -add(5, 6) # => imprime "x é 5 e y é 6" e retorna 11 - -# Outro meio de chamar funções é com argumentos nomeados -add(y=6, x=5) # Argumentos nomeados podem aparecer em qualquer ordem. - -# Você pode definir funções que pegam um número variável de argumentos -# posicionais -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - -# Você pode definir funções que pegam um número variável de argumentos nomeados -# também -def keyword_args(**kwargs): - return kwargs - -# Vamos chamá-lo para ver o que acontece -keyword_args(peh="grande", lago="ness") # => {"peh": "grande", "lago": "ness"} - - -# Você pode fazer ambos simultaneamente, se você quiser -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) imprime: - (1, 2) - {"a": 3, "b": 4} -""" - -# Quando chamar funções, você pode fazer o oposto de args/kwargs! -# Use * para expandir tuplas e use ** para expandir dicionários! -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalente a foo(1, 2, 3, 4) -all_the_args(**kwargs) # equivalente a foo(a=3, b=4) -all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4) - -# Retornando múltiplos valores (com atribuição de tuplas) -def swap(x, y): - return y, x # Retorna múltiplos valores como uma tupla sem os parêntesis. - # (Observação: os parêntesis foram excluídos mas podem estar - # presentes) - -x = 1 -y = 2 -x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # Novamente, os parêntesis foram excluídos mas podem estar presentes. - -# Escopo de função -x = 5 - -def setX(num): - # A variável local x não é a mesma variável global x - x = num # => 43 - print (x) # => 43 - -def setGlobalX(num): - global x - print (x) # => 5 - x = num # variável global x agora é 6 - print (x) # => 6 - -setX(43) -setGlobalX(6) - - -# Python tem funções de primeira classe -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# Também existem as funções anônimas -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# TODO - Fix for iterables -# Existem funções internas de alta ordem -map(add_10, [1, 2, 3]) # => [11, 12, 13] -map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] - -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] - -# Nós podemos usar compreensão de lista para interessantes mapas e filtros -# Compreensão de lista armazena a saída como uma lista que pode ser uma lista -# aninhada -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -#################################################### -## 5. Classes -#################################################### - - -# Nós usamos o operador "class" para ter uma classe -class Human: - - # Um atributo de classe. Ele é compartilhado por todas as instâncias dessa - # classe. - species = "H. sapiens" - - # Construtor básico, é chamado quando esta classe é instanciada. - # Note que dois sublinhados no início e no final de uma identificados - # significa objetos ou atributos que são usados pelo python mas vivem em - # um namespace controlado pelo usuário. Métodos (ou objetos ou atributos) - # como: __init__, __str__, __repr__, etc. são chamados métodos mágicos (ou - # algumas vezes chamados métodos dunder - "double underscore") - # Você não deve usar nomes assim por sua vontade. - def __init__(self, name): - @ Atribui o argumento ao atributo da instância - self.name = name - - # Um método de instância. Todos os métodos tem "self" como primeiro - # argumento - def say(self, msg): - return "{name}: {message}".format(name=self.name, message=msg) - - # Um método de classe é compartilhado por todas as instâncias - # Eles são chamados com a classe requisitante como primeiro argumento - @classmethod - def get_species(cls): - return cls.species - - # Um método estático é chamado sem uma referência a classe ou instância - @staticmethod - def grunt(): - return "*grunt*" - - -# Instancie uma classe -i = Human(name="Ian") -print(i.say("oi")) # imprime "Ian: oi" - -j = Human("Joel") -print(j.say("olá")) # imprime "Joel: olá" - -# Chama nosso método de classe -i.get_species() # => "H. sapiens" - -# Altera um atributo compartilhado -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" - -# Chama o método estático -Human.grunt() # => "*grunt*" - - -#################################################### -## 6. Módulos -#################################################### - -# Você pode importar módulos -import math -print(math.sqrt(16)) # => 4.0 - -# Você pode importar apenas funções específicas de um módulo -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# Você pode importar todas as funções de um módulo para o namespace atual -# Atenção: isso não é recomendado -from math import * - -# Você pode encurtar o nome dos módulos -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Módulos python são apenas arquivos python comuns. Você -# pode escrever os seus, e importá-los. O nome do -# módulo é o mesmo nome do arquivo. - -# Você pode procurar que atributos e funções definem um módulo. -import math -dir(math) - - -#################################################### -## 7. Avançado -#################################################### - -# Geradores podem ajudar você a escrever código "preguiçoso" -def double_numbers(iterable): - for i in iterable: - yield i + i - -# Um gerador cria valores conforme necessário. -# Ao invés de gerar e retornar todos os valores de uma só vez ele cria um em -# cada interação. Isto significa que valores maiores que 15 não serão -# processados em double_numbers. -# Nós usamos um sublinhado ao final do nome das variáveis quando queremos usar -# um nome que normalmente colide com uma palavra reservada do python. -range_ = range(1, 900000000) -# Multiplica por 2 todos os números até encontrar um resultado >= 30 -for i in double_numbers(range_): - print(i) - if i >= 30: - break - - -# Decoradores -# Neste exemplo beg encapsula say -# beg irá chamar say. Se say_please é verdade então ele irá mudar a mensagem -# retornada -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Por favor! Eu sou pobre :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Você me paga uma cerveja?" - return msg, say_please - - -print(say()) # Você me paga uma cerveja? -print(say(say_please=True)) # Você me paga uma cerveja? Por favor! Eu sou pobre :( -``` - -## Pronto para mais? - -### Free Online - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) -* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) -* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) -* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) - -### Dead Tree - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/python.html.markdown b/python.html.markdown new file mode 100644 index 00000000..f69ffb14 --- /dev/null +++ b/python.html.markdown @@ -0,0 +1,1042 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["evuez", "http://github.com/evuez"] + - ["Rommel Martinez", "https://ebzzry.io"] + - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] + - ["caminsha", "https://github.com/caminsha"] +filename: learnpython3.py +--- + +Python was created by Guido van Rossum in the early 90s. It is now one of the most popular +languages in existence. I fell in love with Python for its syntactic clarity. It's basically +executable pseudocode. + +Note: This article applies to Python 3 specifically. Check out [here](http://learnxinyminutes.com/docs/python/) if you want to learn the old Python 2.7 + +```python + +# Single line comments start with a number symbol. + +""" Multiline strings can be written + using three "s, and are often used + as documentation. +""" + +#################################################### +## 1. Primitive Datatypes and Operators +#################################################### + +# You have numbers +3 # => 3 + +# Math is what you would expect +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 + +# Integer division rounds down for both positive and negative numbers. +5 // 3 # => 1 +-5 // 3 # => -2 +5.0 // 3.0 # => 1.0 # works on floats too +-5.0 // 3.0 # => -2.0 + +# The result of division is always a float +10.0 / 3 # => 3.3333333333333335 + +# Modulo operation +7 % 3 # => 1 + +# Exponentiation (x**y, x to the yth power) +2**3 # => 8 + +# Enforce precedence with parentheses +1 + 3 * 2 # => 7 +(1 + 3) * 2 # => 8 + +# Boolean values are primitives (Note: the capitalization) +True # => True +False # => False + +# negate with not +not True # => False +not False # => True + +# Boolean Operators +# Note "and" and "or" are case-sensitive +True and False # => False +False or True # => True + +# True and False are actually 1 and 0 but with different keywords +True + True # => 2 +True * 8 # => 8 +False - 5 # => -5 + +# Comparison operators look at the numerical value of True and False +0 == False # => True +1 == True # => True +2 == True # => False +-5 != False # => True + +# Using boolean logical operators on ints casts them to booleans for evaluation, but their non-cast value is returned +# Don't mix up with bool(ints) and bitwise and/or (&,|) +bool(0) # => False +bool(4) # => True +bool(-6) # => True +0 and 2 # => 0 +-5 or 0 # => -5 + +# Equality is == +1 == 1 # => True +2 == 1 # => False + +# Inequality is != +1 != 1 # => False +2 != 1 # => True + +# More comparisons +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Seeing whether a value is in a range +1 < 2 and 2 < 3 # => True +2 < 3 and 3 < 2 # => False +# Chaining makes this look nicer +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (is vs. ==) is checks if two variables refer to the same object, but == checks +# if the objects pointed to have the same values. +a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] +b = a # Point b at what a is pointing to +b is a # => True, a and b refer to the same object +b == a # => True, a's and b's objects are equal +b = [1, 2, 3, 4] # Point b at a new list, [1, 2, 3, 4] +b is a # => False, a and b do not refer to the same object +b == a # => True, a's and b's objects are equal + +# Strings are created with " or ' +"This is a string." +'This is also a string.' + +# Strings can be added too! But try not to do this. +"Hello " + "world!" # => "Hello world!" +# String literals (but not variables) can be concatenated without using '+' +"Hello " "world!" # => "Hello world!" + +# A string can be treated like a list of characters +"This is a string"[0] # => 'T' + +# You can find the length of a string +len("This is a string") # => 16 + +# You can also format using f-strings or formatted string literals (in Python 3.6+) +name = "Reiko" +f"She said her name is {name}." # => "She said her name is Reiko" +# You can basically put any Python statement inside the braces and it will be output in the string. +f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long." + + +# None is an object +None # => None + +# Don't use the equality "==" symbol to compare objects to None +# Use "is" instead. This checks for equality of object identity. +"etc" is None # => False +None is None # => True + +# None, 0, and empty strings/lists/dicts/tuples all evaluate to False. +# All other values are True +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False +bool(()) # => False + +#################################################### +## 2. Variables and Collections +#################################################### + +# Python has a print function +print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! + +# By default the print function also prints out a newline at the end. +# Use the optional argument end to change the end string. +print("Hello, World", end="!") # => Hello, World! + +# Simple way to get input data from console +input_string_var = input("Enter some data: ") # Returns the data as a string +# Note: In earlier versions of Python, input() method was named as raw_input() + +# There are no declarations, only assignments. +# Convention is to use lower_case_with_underscores +some_var = 5 +some_var # => 5 + +# Accessing a previously unassigned variable is an exception. +# See Control Flow to learn more about exception handling. +some_unknown_var # Raises a NameError + +# if can be used as an expression +# Equivalent of C's '?:' ternary operator +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Lists store sequences +li = [] +# You can start with a prefilled list +other_li = [4, 5, 6] + +# Add stuff to the end of a list with append +li.append(1) # li is now [1] +li.append(2) # li is now [1, 2] +li.append(4) # li is now [1, 2, 4] +li.append(3) # li is now [1, 2, 4, 3] +# Remove from the end with pop +li.pop() # => 3 and li is now [1, 2, 4] +# Let's put it back +li.append(3) # li is now [1, 2, 4, 3] again. + +# Access a list like you would any array +li[0] # => 1 +# Look at the last element +li[-1] # => 3 + +# Looking out of bounds is an IndexError +li[4] # Raises an IndexError + +# You can look at ranges with slice syntax. +# The start index is included, the end index is not +# (It's a closed/open range for you mathy types.) +li[1:3] # Return list from index 1 to 3 => [2, 4] +li[2:] # Return list starting from index 2 => [4, 3] +li[:3] # Return list from beginning until index 3 => [1, 2, 4] +li[::2] # Return list selecting every second entry => [1, 4] +li[::-1] # Return list in reverse order => [3, 4, 2, 1] +# Use any combination of these to make advanced slices +# li[start:end:step] + +# Make a one layer deep copy using slices +li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. + +# Remove arbitrary elements from a list with "del" +del li[2] # li is now [1, 2, 3] + +# Remove first occurrence of a value +li.remove(2) # li is now [1, 3] +li.remove(2) # Raises a ValueError as 2 is not in the list + +# Insert an element at a specific index +li.insert(1, 2) # li is now [1, 2, 3] again + +# Get the index of the first item found matching the argument +li.index(2) # => 1 +li.index(4) # Raises a ValueError as 4 is not in the list + +# You can add lists +# Note: values for li and for other_li are not modified. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Concatenate lists with "extend()" +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] + +# Check for existence in a list with "in" +1 in li # => True + +# Examine the length with "len()" +len(li) # => 6 + + +# Tuples are like lists but are immutable. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Raises a TypeError + +# Note that a tuple of length one has to have a comma after the last element but +# tuples of other lengths, even zero, do not. +type((1)) # => +type((1,)) # => +type(()) # => + +# You can do most of the list operations on tuples too +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# You can unpack tuples (or lists) into variables +a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +# You can also do extended unpacking +a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4 +# Tuples are created by default if you leave out the parentheses +d, e, f = 4, 5, 6 # tuple 4, 5, 6 is unpacked into variables d, e and f +# respectively such that d = 4, e = 5 and f = 6 +# Now look how easy it is to swap two values +e, d = d, e # d is now 5 and e is now 4 + + +# Dictionaries store mappings from keys to values +empty_dict = {} +# Here is a prefilled dictionary +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Note keys for dictionaries have to be immutable types. This is to ensure that +# the key can be converted to a constant hash value for quick look-ups. +# Immutable types include ints, floats, strings, tuples. +invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. + +# Look up values with [] +filled_dict["one"] # => 1 + +# Get all keys as an iterable with "keys()". We need to wrap the call in list() +# to turn it into a list. We'll talk about those later. Note - for Python +# versions <3.7, dictionary key ordering is not guaranteed. Your results might +# not match the example below exactly. However, as of Python 3.7, dictionary +# items maintain the order at which they are inserted into the dictionary. +list(filled_dict.keys()) # => ["three", "two", "one"] in Python <3.7 +list(filled_dict.keys()) # => ["one", "two", "three"] in Python 3.7+ + + +# Get all values as an iterable with "values()". Once again we need to wrap it +# in list() to get it out of the iterable. Note - Same as above regarding key +# ordering. +list(filled_dict.values()) # => [3, 2, 1] in Python <3.7 +list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+ + +# Check for existence of keys in a dictionary with "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# Looking up a non-existing key is a KeyError +filled_dict["four"] # KeyError + +# Use "get()" method to avoid the KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# The get method supports a default argument when the value is missing +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# "setdefault()" inserts into a dictionary only if the given key isn't present +filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 + +# Adding to a dictionary +filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} +filled_dict["four"] = 4 # another way to add to dict + +# Remove keys from a dictionary with del +del filled_dict["one"] # Removes the key "one" from filled dict + +# From Python 3.5 you can also use the additional unpacking options +{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} +{'a': 1, **{'a': 2}} # => {'a': 2} + + + +# Sets store ... well sets +empty_set = set() +# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. +some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} + +# Similar to keys of a dictionary, elements of a set have to be immutable. +invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# Add one more item to the set +filled_set = some_set +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} +# Sets do not have duplicate elements +filled_set.add(5) # it remains as before {1, 2, 3, 4, 5} + +# Do set intersection with & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Do set union with | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Do set difference with - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Do set symmetric difference with ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Check if set on the left is a superset of set on the right +{1, 2} >= {1, 2, 3} # => False + +# Check if set on the left is a subset of set on the right +{1, 2} <= {1, 2, 3} # => True + +# Check for existence in a set with in +2 in filled_set # => True +10 in filled_set # => False + +# Make a one layer deep copy +filled_set = some_set.copy() # filled_set is {1, 2, 3, 4, 5} +filled_set is some_set # => False + + +#################################################### +## 3. Control Flow and Iterables +#################################################### + +# Let's just make a variable +some_var = 5 + +# Here is an if statement. Indentation is significant in Python! +# Convention is to use four spaces, not tabs. +# This prints "some_var is smaller than 10" +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # This elif clause is optional. + print("some_var is smaller than 10.") +else: # This is optional too. + print("some_var is indeed 10.") + + +""" +For loops iterate over lists +prints: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # You can use format() to interpolate formatted strings + print("{} is a mammal".format(animal)) + +""" +"range(number)" returns an iterable of numbers +from zero to the given number +prints: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(lower, upper)" returns an iterable of numbers +from the lower number to the upper number +prints: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(lower, upper, step)" returns an iterable of numbers +from the lower number to the upper number, while incrementing +by step. If step is not indicated, the default value is 1. +prints: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) + +""" +To loop over a list, and retrieve both the index and the value of each item in the list +prints: + 0 dog + 1 cat + 2 mouse +""" +animals = ["dog", "cat", "mouse"] +for i, value in enumerate(animals): + print(i, value) + +""" +While loops go until a condition is no longer met. +prints: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Shorthand for x = x + 1 + +# Handle exceptions with a try/except block +try: + # Use "raise" to raise an error + raise IndexError("This is an index error") +except IndexError as e: + pass # Pass is just a no-op. Usually you would do recovery here. +except (TypeError, NameError): + pass # Multiple exceptions can be handled together, if required. +else: # Optional clause to the try/except block. Must follow all except blocks + print("All good!") # Runs only if the code in try raises no exceptions +finally: # Execute under all circumstances + print("We can clean up resources here") + +# Instead of try/finally to cleanup resources you can use a with statement +with open("myfile.txt") as f: + for line in f: + print(line) + +# Writing to a file +contents = {"aa": 12, "bb": 21} +with open("myfile1.txt", "w+") as file: + file.write(str(contents)) # writes a string to a file + +with open("myfile2.txt", "w+") as file: + file.write(json.dumps(contents)) # writes an object to a file + +# Reading from a file +with open('myfile1.txt', "r+") as file: + contents = file.read() # reads a string from a file +print(contents) +# print: {"aa": 12, "bb": 21} + +with open('myfile2.txt', "r+") as file: + contents = json.load(file) # reads a json object from a file +print(contents) +# print: {"aa": 12, "bb": 21} + + +# Python offers a fundamental abstraction called the Iterable. +# An iterable is an object that can be treated as a sequence. +# The object returned by the range function, is an iterable. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface. + +# We can loop over it. +for i in our_iterable: + print(i) # Prints one, two, three + +# However we cannot address elements by index. +our_iterable[1] # Raises a TypeError + +# An iterable is an object that knows how to create an iterator. +our_iterator = iter(our_iterable) + +# Our iterator is an object that can remember the state as we traverse through it. +# We get the next object with "next()". +next(our_iterator) # => "one" + +# It maintains state as we iterate. +next(our_iterator) # => "two" +next(our_iterator) # => "three" + +# After the iterator has returned all of its data, it raises a StopIteration exception +next(our_iterator) # Raises StopIteration + +# We can also loop over it, in fact, "for" does this implicitly! +our_iterator = iter(our_iterable) +for i in our_iterator: + print(i) # Prints one, two, three + +# You can grab all the elements of an iterable or iterator by calling list() on it. +list(our_iterable) # => Returns ["one", "two", "three"] +list(our_iterator) # => Returns [] because state is saved + + +#################################################### +## 4. Functions +#################################################### + +# Use "def" to create new functions +def add(x, y): + print("x is {} and y is {}".format(x, y)) + return x + y # Return values with a return statement + +# Calling functions with parameters +add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 + +# Another way to call functions is with keyword arguments +add(y=6, x=5) # Keyword arguments can arrive in any order. + +# You can define functions that take a variable number of +# positional arguments +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# You can define functions that take a variable number of +# keyword arguments, as well +def keyword_args(**kwargs): + return kwargs + +# Let's call it to see what happens +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# You can do both at once, if you like +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# When calling functions, you can do the opposite of args/kwargs! +# Use * to expand tuples and use ** to expand kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalent to all_the_args(1, 2, 3, 4) +all_the_args(**kwargs) # equivalent to all_the_args(a=3, b=4) +all_the_args(*args, **kwargs) # equivalent to all_the_args(1, 2, 3, 4, a=3, b=4) + +# Returning multiple values (with tuple assignments) +def swap(x, y): + return y, x # Return multiple values as a tuple without the parenthesis. + # (Note: parenthesis have been excluded but can be included) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included. + +# Function Scope +x = 5 + +def set_x(num): + # Local var x not the same as global variable x + x = num # => 43 + print(x) # => 43 + +def set_global_x(num): + global x + print(x) # => 5 + x = num # global var x is now set to 6 + print(x) # => 6 + +set_x(43) +set_global_x(6) + + +# Python has first class functions +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# There are also anonymous functions +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# There are built-in higher order functions +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] + +list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] + +# We can use list comprehensions for nice maps and filters +# List comprehension stores the output as a list which can itself be a nested list +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# You can construct set and dict comprehensions as well. +{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +## 5. Modules +#################################################### + +# You can import modules +import math +print(math.sqrt(16)) # => 4.0 + +# You can get specific functions from a module +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# You can import all functions from a module. +# Warning: this is not recommended +from math import * + +# You can shorten module names +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Python modules are just ordinary Python files. You +# can write your own, and import them. The name of the +# module is the same as the name of the file. + +# You can find out which functions and attributes +# are defined in a module. +import math +dir(math) + +# If you have a Python script named math.py in the same +# folder as your current script, the file math.py will +# be loaded instead of the built-in Python module. +# This happens because the local folder has priority +# over Python's built-in libraries. + + +#################################################### +## 6. Classes +#################################################### + +# We use the "class" statement to create a class +class Human: + + # A class attribute. It is shared by all instances of this class + species = "H. sapiens" + + # Basic initializer, this is called when this class is instantiated. + # Note that the double leading and trailing underscores denote objects + # or attributes that are used by Python but that live in user-controlled + # namespaces. Methods(or objects or attributes) like: __init__, __str__, + # __repr__ etc. are called special methods (or sometimes called dunder methods) + # You should not invent such names on your own. + def __init__(self, name): + # Assign the argument to the instance's name attribute + self.name = name + + # Initialize property + self._age = 0 + + # An instance method. All methods take "self" as the first argument + def say(self, msg): + print("{name}: {message}".format(name=self.name, message=msg)) + + # Another instance method + def sing(self): + return 'yo... yo... microphone check... one two... one two...' + + # A class method is shared among all instances + # They are called with the calling class as the first argument + @classmethod + def get_species(cls): + return cls.species + + # A static method is called without a class or instance reference + @staticmethod + def grunt(): + return "*grunt*" + + # A property is just like a getter. + # It turns the method age() into an read-only attribute of the same name. + # There's no need to write trivial getters and setters in Python, though. + @property + def age(self): + return self._age + + # This allows the property to be set + @age.setter + def age(self, age): + self._age = age + + # This allows the property to be deleted + @age.deleter + def age(self): + del self._age + + +# When a Python interpreter reads a source file it executes all its code. +# This __name__ check makes sure this code block is only executed when this +# module is the main program. +if __name__ == '__main__': + # Instantiate a class + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # i and j are instances of type Human, or in other words: they are Human objects + + # Call our class method + i.say(i.get_species()) # "Ian: H. sapiens" + # Change the shared attribute + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # Call the static method + print(Human.grunt()) # => "*grunt*" + + # Cannot call static method with instance of object + # because i.grunt() will automatically put "self" (the object i) as an argument + print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given + + # Update the property for this instance + i.age = 42 + # Get the property + i.say(i.age) # => "Ian: 42" + j.say(j.age) # => "Joel: 0" + # Delete the property + del i.age + # i.age # => this would raise an AttributeError + + +#################################################### +## 6.1 Inheritance +#################################################### + +# Inheritance allows new child classes to be defined that inherit methods and +# variables from their parent class. + +# Using the Human class defined above as the base or parent class, we can +# define a child class, Superhero, which inherits the class variables like +# "species", "name", and "age", as well as methods, like "sing" and "grunt" +# from the Human class, but can also have its own unique properties. + +# To take advantage of modularization by file you could place the classes above in their own files, +# say, human.py + +# To import functions from other files use the following format +# from "filename-without-extension" import "function-or-class" + +from human import Human + + +# Specify the parent class(es) as parameters to the class definition +class Superhero(Human): + + # If the child class should inherit all of the parent's definitions without + # any modifications, you can just use the "pass" keyword (and nothing else) + # but in this case it is commented out to allow for a unique child class: + # pass + + # Child classes can override their parents' attributes + species = 'Superhuman' + + # Children automatically inherit their parent class's constructor including + # its arguments, but can also define additional arguments or definitions + # and override its methods such as the class constructor. + # This constructor inherits the "name" argument from the "Human" class and + # adds the "superpower" and "movie" arguments: + def __init__(self, name, movie=False, + superpowers=["super strength", "bulletproofing"]): + + # add additional class attributes: + self.fictional = True + self.movie = movie + # be aware of mutable default values, since defaults are shared + self.superpowers = superpowers + + # The "super" function lets you access the parent class's methods + # that are overridden by the child, in this case, the __init__ method. + # This calls the parent class constructor: + super().__init__(name) + + # override the sing method + def sing(self): + return 'Dun, dun, DUN!' + + # add an additional instance method + def boast(self): + for power in self.superpowers: + print("I wield the power of {pow}!".format(pow=power)) + + +if __name__ == '__main__': + sup = Superhero(name="Tick") + + # Instance type checks + if isinstance(sup, Human): + print('I am human') + if type(sup) is Superhero: + print('I am a superhero') + + # Get the Method Resolution search Order used by both getattr() and super() + # This attribute is dynamic and can be updated + print(Superhero.__mro__) # => (, + # => , ) + + # Calls parent method but uses its own class attribute + print(sup.get_species()) # => Superhuman + + # Calls overridden method + print(sup.sing()) # => Dun, dun, DUN! + + # Calls method from Human + sup.say('Spoon') # => Tick: Spoon + + # Call method that exists only in Superhero + sup.boast() # => I wield the power of super strength! + # => I wield the power of bulletproofing! + + # Inherited class attribute + sup.age = 31 + print(sup.age) # => 31 + + # Attribute that only exists within Superhero + print('Am I Oscar eligible? ' + str(sup.movie)) + +#################################################### +## 6.2 Multiple Inheritance +#################################################### + +# Another class definition +# bat.py +class Bat: + + species = 'Baty' + + def __init__(self, can_fly=True): + self.fly = can_fly + + # This class also has a say method + def say(self, msg): + msg = '... ... ...' + return msg + + # And its own method as well + def sonar(self): + return '))) ... (((' + +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) + + +# And yet another class definition that inherits from Superhero and Bat +# superhero.py +from superhero import Superhero +from bat import Bat + +# Define Batman as a child that inherits from both Superhero and Bat +class Batman(Superhero, Bat): + + def __init__(self, *args, **kwargs): + # Typically to inherit attributes you have to call super: + # super(Batman, self).__init__(*args, **kwargs) + # However we are dealing with multiple inheritance here, and super() + # only works with the next base class in the MRO list. + # So instead we explicitly call __init__ for all ancestors. + # The use of *args and **kwargs allows for a clean way to pass arguments, + # with each parent "peeling a layer of the onion". + Superhero.__init__(self, 'anonymous', movie=True, + superpowers=['Wealthy'], *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # override the value for the name attribute + self.name = 'Sad Affleck' + + def sing(self): + return 'nan nan nan nan nan batman!' + + +if __name__ == '__main__': + sup = Batman() + + # Get the Method Resolution search Order used by both getattr() and super(). + # This attribute is dynamic and can be updated + print(Batman.__mro__) # => (, + # => , + # => , + # => , ) + + # Calls parent method but uses its own class attribute + print(sup.get_species()) # => Superhuman + + # Calls overridden method + print(sup.sing()) # => nan nan nan nan nan batman! + + # Calls method from Human, because inheritance order matters + sup.say('I agree') # => Sad Affleck: I agree + + # Call method that exists only in 2nd ancestor + print(sup.sonar()) # => ))) ... ((( + + # Inherited class attribute + sup.age = 100 + print(sup.age) # => 100 + + # Inherited attribute from 2nd ancestor whose default value was overridden. + print('Can I fly? ' + str(sup.fly)) # => Can I fly? False + + + +#################################################### +## 7. Advanced +#################################################### + +# Generators help you make lazy code. +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Generators are memory-efficient because they only load the data needed to +# process the next value in the iterable. This allows them to perform +# operations on otherwise prohibitively large value ranges. +# NOTE: `range` replaces `xrange` in Python 3. +for i in double_numbers(range(1, 900000000)): # `range` is a generator. + print(i) + if i >= 30: + break + +# Just as you can create a list comprehension, you can create generator +# comprehensions as well. +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # prints -1 -2 -3 -4 -5 to console/terminal + +# You can also cast a generator comprehension directly to a list. +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + + +# Decorators +# In this example `beg` wraps `say`. If say_please is True then it +# will change the returned message. +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # Can you buy me a beer? +print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( +``` + +## Ready For More? + +### Free Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) +* [Dive Into Python 3](http://www.diveintopython3.net/index.html) +* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/python3.html.markdown b/python3.html.markdown deleted file mode 100644 index f69ffb14..00000000 --- a/python3.html.markdown +++ /dev/null @@ -1,1042 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] - - ["evuez", "http://github.com/evuez"] - - ["Rommel Martinez", "https://ebzzry.io"] - - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] - - ["caminsha", "https://github.com/caminsha"] -filename: learnpython3.py ---- - -Python was created by Guido van Rossum in the early 90s. It is now one of the most popular -languages in existence. I fell in love with Python for its syntactic clarity. It's basically -executable pseudocode. - -Note: This article applies to Python 3 specifically. Check out [here](http://learnxinyminutes.com/docs/python/) if you want to learn the old Python 2.7 - -```python - -# Single line comments start with a number symbol. - -""" Multiline strings can be written - using three "s, and are often used - as documentation. -""" - -#################################################### -## 1. Primitive Datatypes and Operators -#################################################### - -# You have numbers -3 # => 3 - -# Math is what you would expect -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7.0 - -# Integer division rounds down for both positive and negative numbers. -5 // 3 # => 1 --5 // 3 # => -2 -5.0 // 3.0 # => 1.0 # works on floats too --5.0 // 3.0 # => -2.0 - -# The result of division is always a float -10.0 / 3 # => 3.3333333333333335 - -# Modulo operation -7 % 3 # => 1 - -# Exponentiation (x**y, x to the yth power) -2**3 # => 8 - -# Enforce precedence with parentheses -1 + 3 * 2 # => 7 -(1 + 3) * 2 # => 8 - -# Boolean values are primitives (Note: the capitalization) -True # => True -False # => False - -# negate with not -not True # => False -not False # => True - -# Boolean Operators -# Note "and" and "or" are case-sensitive -True and False # => False -False or True # => True - -# True and False are actually 1 and 0 but with different keywords -True + True # => 2 -True * 8 # => 8 -False - 5 # => -5 - -# Comparison operators look at the numerical value of True and False -0 == False # => True -1 == True # => True -2 == True # => False --5 != False # => True - -# Using boolean logical operators on ints casts them to booleans for evaluation, but their non-cast value is returned -# Don't mix up with bool(ints) and bitwise and/or (&,|) -bool(0) # => False -bool(4) # => True -bool(-6) # => True -0 and 2 # => 0 --5 or 0 # => -5 - -# Equality is == -1 == 1 # => True -2 == 1 # => False - -# Inequality is != -1 != 1 # => False -2 != 1 # => True - -# More comparisons -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# Seeing whether a value is in a range -1 < 2 and 2 < 3 # => True -2 < 3 and 3 < 2 # => False -# Chaining makes this look nicer -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# (is vs. ==) is checks if two variables refer to the same object, but == checks -# if the objects pointed to have the same values. -a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] -b = a # Point b at what a is pointing to -b is a # => True, a and b refer to the same object -b == a # => True, a's and b's objects are equal -b = [1, 2, 3, 4] # Point b at a new list, [1, 2, 3, 4] -b is a # => False, a and b do not refer to the same object -b == a # => True, a's and b's objects are equal - -# Strings are created with " or ' -"This is a string." -'This is also a string.' - -# Strings can be added too! But try not to do this. -"Hello " + "world!" # => "Hello world!" -# String literals (but not variables) can be concatenated without using '+' -"Hello " "world!" # => "Hello world!" - -# A string can be treated like a list of characters -"This is a string"[0] # => 'T' - -# You can find the length of a string -len("This is a string") # => 16 - -# You can also format using f-strings or formatted string literals (in Python 3.6+) -name = "Reiko" -f"She said her name is {name}." # => "She said her name is Reiko" -# You can basically put any Python statement inside the braces and it will be output in the string. -f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long." - - -# None is an object -None # => None - -# Don't use the equality "==" symbol to compare objects to None -# Use "is" instead. This checks for equality of object identity. -"etc" is None # => False -None is None # => True - -# None, 0, and empty strings/lists/dicts/tuples all evaluate to False. -# All other values are True -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False -bool(()) # => False - -#################################################### -## 2. Variables and Collections -#################################################### - -# Python has a print function -print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! - -# By default the print function also prints out a newline at the end. -# Use the optional argument end to change the end string. -print("Hello, World", end="!") # => Hello, World! - -# Simple way to get input data from console -input_string_var = input("Enter some data: ") # Returns the data as a string -# Note: In earlier versions of Python, input() method was named as raw_input() - -# There are no declarations, only assignments. -# Convention is to use lower_case_with_underscores -some_var = 5 -some_var # => 5 - -# Accessing a previously unassigned variable is an exception. -# See Control Flow to learn more about exception handling. -some_unknown_var # Raises a NameError - -# if can be used as an expression -# Equivalent of C's '?:' ternary operator -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# Lists store sequences -li = [] -# You can start with a prefilled list -other_li = [4, 5, 6] - -# Add stuff to the end of a list with append -li.append(1) # li is now [1] -li.append(2) # li is now [1, 2] -li.append(4) # li is now [1, 2, 4] -li.append(3) # li is now [1, 2, 4, 3] -# Remove from the end with pop -li.pop() # => 3 and li is now [1, 2, 4] -# Let's put it back -li.append(3) # li is now [1, 2, 4, 3] again. - -# Access a list like you would any array -li[0] # => 1 -# Look at the last element -li[-1] # => 3 - -# Looking out of bounds is an IndexError -li[4] # Raises an IndexError - -# You can look at ranges with slice syntax. -# The start index is included, the end index is not -# (It's a closed/open range for you mathy types.) -li[1:3] # Return list from index 1 to 3 => [2, 4] -li[2:] # Return list starting from index 2 => [4, 3] -li[:3] # Return list from beginning until index 3 => [1, 2, 4] -li[::2] # Return list selecting every second entry => [1, 4] -li[::-1] # Return list in reverse order => [3, 4, 2, 1] -# Use any combination of these to make advanced slices -# li[start:end:step] - -# Make a one layer deep copy using slices -li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. - -# Remove arbitrary elements from a list with "del" -del li[2] # li is now [1, 2, 3] - -# Remove first occurrence of a value -li.remove(2) # li is now [1, 3] -li.remove(2) # Raises a ValueError as 2 is not in the list - -# Insert an element at a specific index -li.insert(1, 2) # li is now [1, 2, 3] again - -# Get the index of the first item found matching the argument -li.index(2) # => 1 -li.index(4) # Raises a ValueError as 4 is not in the list - -# You can add lists -# Note: values for li and for other_li are not modified. -li + other_li # => [1, 2, 3, 4, 5, 6] - -# Concatenate lists with "extend()" -li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] - -# Check for existence in a list with "in" -1 in li # => True - -# Examine the length with "len()" -len(li) # => 6 - - -# Tuples are like lists but are immutable. -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # Raises a TypeError - -# Note that a tuple of length one has to have a comma after the last element but -# tuples of other lengths, even zero, do not. -type((1)) # => -type((1,)) # => -type(()) # => - -# You can do most of the list operations on tuples too -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# You can unpack tuples (or lists) into variables -a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 -# You can also do extended unpacking -a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4 -# Tuples are created by default if you leave out the parentheses -d, e, f = 4, 5, 6 # tuple 4, 5, 6 is unpacked into variables d, e and f -# respectively such that d = 4, e = 5 and f = 6 -# Now look how easy it is to swap two values -e, d = d, e # d is now 5 and e is now 4 - - -# Dictionaries store mappings from keys to values -empty_dict = {} -# Here is a prefilled dictionary -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Note keys for dictionaries have to be immutable types. This is to ensure that -# the key can be converted to a constant hash value for quick look-ups. -# Immutable types include ints, floats, strings, tuples. -invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list' -valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. - -# Look up values with [] -filled_dict["one"] # => 1 - -# Get all keys as an iterable with "keys()". We need to wrap the call in list() -# to turn it into a list. We'll talk about those later. Note - for Python -# versions <3.7, dictionary key ordering is not guaranteed. Your results might -# not match the example below exactly. However, as of Python 3.7, dictionary -# items maintain the order at which they are inserted into the dictionary. -list(filled_dict.keys()) # => ["three", "two", "one"] in Python <3.7 -list(filled_dict.keys()) # => ["one", "two", "three"] in Python 3.7+ - - -# Get all values as an iterable with "values()". Once again we need to wrap it -# in list() to get it out of the iterable. Note - Same as above regarding key -# ordering. -list(filled_dict.values()) # => [3, 2, 1] in Python <3.7 -list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+ - -# Check for existence of keys in a dictionary with "in" -"one" in filled_dict # => True -1 in filled_dict # => False - -# Looking up a non-existing key is a KeyError -filled_dict["four"] # KeyError - -# Use "get()" method to avoid the KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# The get method supports a default argument when the value is missing -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 - -# "setdefault()" inserts into a dictionary only if the given key isn't present -filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 - -# Adding to a dictionary -filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} -filled_dict["four"] = 4 # another way to add to dict - -# Remove keys from a dictionary with del -del filled_dict["one"] # Removes the key "one" from filled dict - -# From Python 3.5 you can also use the additional unpacking options -{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} -{'a': 1, **{'a': 2}} # => {'a': 2} - - - -# Sets store ... well sets -empty_set = set() -# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. -some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} - -# Similar to keys of a dictionary, elements of a set have to be immutable. -invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list' -valid_set = {(1,), 1} - -# Add one more item to the set -filled_set = some_set -filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} -# Sets do not have duplicate elements -filled_set.add(5) # it remains as before {1, 2, 3, 4, 5} - -# Do set intersection with & -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# Do set union with | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# Do set difference with - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Do set symmetric difference with ^ -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# Check if set on the left is a superset of set on the right -{1, 2} >= {1, 2, 3} # => False - -# Check if set on the left is a subset of set on the right -{1, 2} <= {1, 2, 3} # => True - -# Check for existence in a set with in -2 in filled_set # => True -10 in filled_set # => False - -# Make a one layer deep copy -filled_set = some_set.copy() # filled_set is {1, 2, 3, 4, 5} -filled_set is some_set # => False - - -#################################################### -## 3. Control Flow and Iterables -#################################################### - -# Let's just make a variable -some_var = 5 - -# Here is an if statement. Indentation is significant in Python! -# Convention is to use four spaces, not tabs. -# This prints "some_var is smaller than 10" -if some_var > 10: - print("some_var is totally bigger than 10.") -elif some_var < 10: # This elif clause is optional. - print("some_var is smaller than 10.") -else: # This is optional too. - print("some_var is indeed 10.") - - -""" -For loops iterate over lists -prints: - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - # You can use format() to interpolate formatted strings - print("{} is a mammal".format(animal)) - -""" -"range(number)" returns an iterable of numbers -from zero to the given number -prints: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -"range(lower, upper)" returns an iterable of numbers -from the lower number to the upper number -prints: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -"range(lower, upper, step)" returns an iterable of numbers -from the lower number to the upper number, while incrementing -by step. If step is not indicated, the default value is 1. -prints: - 4 - 6 -""" -for i in range(4, 8, 2): - print(i) - -""" -To loop over a list, and retrieve both the index and the value of each item in the list -prints: - 0 dog - 1 cat - 2 mouse -""" -animals = ["dog", "cat", "mouse"] -for i, value in enumerate(animals): - print(i, value) - -""" -While loops go until a condition is no longer met. -prints: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Shorthand for x = x + 1 - -# Handle exceptions with a try/except block -try: - # Use "raise" to raise an error - raise IndexError("This is an index error") -except IndexError as e: - pass # Pass is just a no-op. Usually you would do recovery here. -except (TypeError, NameError): - pass # Multiple exceptions can be handled together, if required. -else: # Optional clause to the try/except block. Must follow all except blocks - print("All good!") # Runs only if the code in try raises no exceptions -finally: # Execute under all circumstances - print("We can clean up resources here") - -# Instead of try/finally to cleanup resources you can use a with statement -with open("myfile.txt") as f: - for line in f: - print(line) - -# Writing to a file -contents = {"aa": 12, "bb": 21} -with open("myfile1.txt", "w+") as file: - file.write(str(contents)) # writes a string to a file - -with open("myfile2.txt", "w+") as file: - file.write(json.dumps(contents)) # writes an object to a file - -# Reading from a file -with open('myfile1.txt', "r+") as file: - contents = file.read() # reads a string from a file -print(contents) -# print: {"aa": 12, "bb": 21} - -with open('myfile2.txt', "r+") as file: - contents = json.load(file) # reads a json object from a file -print(contents) -# print: {"aa": 12, "bb": 21} - - -# Python offers a fundamental abstraction called the Iterable. -# An iterable is an object that can be treated as a sequence. -# The object returned by the range function, is an iterable. - -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface. - -# We can loop over it. -for i in our_iterable: - print(i) # Prints one, two, three - -# However we cannot address elements by index. -our_iterable[1] # Raises a TypeError - -# An iterable is an object that knows how to create an iterator. -our_iterator = iter(our_iterable) - -# Our iterator is an object that can remember the state as we traverse through it. -# We get the next object with "next()". -next(our_iterator) # => "one" - -# It maintains state as we iterate. -next(our_iterator) # => "two" -next(our_iterator) # => "three" - -# After the iterator has returned all of its data, it raises a StopIteration exception -next(our_iterator) # Raises StopIteration - -# We can also loop over it, in fact, "for" does this implicitly! -our_iterator = iter(our_iterable) -for i in our_iterator: - print(i) # Prints one, two, three - -# You can grab all the elements of an iterable or iterator by calling list() on it. -list(our_iterable) # => Returns ["one", "two", "three"] -list(our_iterator) # => Returns [] because state is saved - - -#################################################### -## 4. Functions -#################################################### - -# Use "def" to create new functions -def add(x, y): - print("x is {} and y is {}".format(x, y)) - return x + y # Return values with a return statement - -# Calling functions with parameters -add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 - -# Another way to call functions is with keyword arguments -add(y=6, x=5) # Keyword arguments can arrive in any order. - -# You can define functions that take a variable number of -# positional arguments -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - -# You can define functions that take a variable number of -# keyword arguments, as well -def keyword_args(**kwargs): - return kwargs - -# Let's call it to see what happens -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# You can do both at once, if you like -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) prints: - (1, 2) - {"a": 3, "b": 4} -""" - -# When calling functions, you can do the opposite of args/kwargs! -# Use * to expand tuples and use ** to expand kwargs. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalent to all_the_args(1, 2, 3, 4) -all_the_args(**kwargs) # equivalent to all_the_args(a=3, b=4) -all_the_args(*args, **kwargs) # equivalent to all_the_args(1, 2, 3, 4, a=3, b=4) - -# Returning multiple values (with tuple assignments) -def swap(x, y): - return y, x # Return multiple values as a tuple without the parenthesis. - # (Note: parenthesis have been excluded but can be included) - -x = 1 -y = 2 -x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included. - -# Function Scope -x = 5 - -def set_x(num): - # Local var x not the same as global variable x - x = num # => 43 - print(x) # => 43 - -def set_global_x(num): - global x - print(x) # => 5 - x = num # global var x is now set to 6 - print(x) # => 6 - -set_x(43) -set_global_x(6) - - -# Python has first class functions -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# There are also anonymous functions -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# There are built-in higher order functions -list(map(add_10, [1, 2, 3])) # => [11, 12, 13] -list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] - -list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] - -# We can use list comprehensions for nice maps and filters -# List comprehension stores the output as a list which can itself be a nested list -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -# You can construct set and dict comprehensions as well. -{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} -{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} - - -#################################################### -## 5. Modules -#################################################### - -# You can import modules -import math -print(math.sqrt(16)) # => 4.0 - -# You can get specific functions from a module -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# You can import all functions from a module. -# Warning: this is not recommended -from math import * - -# You can shorten module names -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Python modules are just ordinary Python files. You -# can write your own, and import them. The name of the -# module is the same as the name of the file. - -# You can find out which functions and attributes -# are defined in a module. -import math -dir(math) - -# If you have a Python script named math.py in the same -# folder as your current script, the file math.py will -# be loaded instead of the built-in Python module. -# This happens because the local folder has priority -# over Python's built-in libraries. - - -#################################################### -## 6. Classes -#################################################### - -# We use the "class" statement to create a class -class Human: - - # A class attribute. It is shared by all instances of this class - species = "H. sapiens" - - # Basic initializer, this is called when this class is instantiated. - # Note that the double leading and trailing underscores denote objects - # or attributes that are used by Python but that live in user-controlled - # namespaces. Methods(or objects or attributes) like: __init__, __str__, - # __repr__ etc. are called special methods (or sometimes called dunder methods) - # You should not invent such names on your own. - def __init__(self, name): - # Assign the argument to the instance's name attribute - self.name = name - - # Initialize property - self._age = 0 - - # An instance method. All methods take "self" as the first argument - def say(self, msg): - print("{name}: {message}".format(name=self.name, message=msg)) - - # Another instance method - def sing(self): - return 'yo... yo... microphone check... one two... one two...' - - # A class method is shared among all instances - # They are called with the calling class as the first argument - @classmethod - def get_species(cls): - return cls.species - - # A static method is called without a class or instance reference - @staticmethod - def grunt(): - return "*grunt*" - - # A property is just like a getter. - # It turns the method age() into an read-only attribute of the same name. - # There's no need to write trivial getters and setters in Python, though. - @property - def age(self): - return self._age - - # This allows the property to be set - @age.setter - def age(self, age): - self._age = age - - # This allows the property to be deleted - @age.deleter - def age(self): - del self._age - - -# When a Python interpreter reads a source file it executes all its code. -# This __name__ check makes sure this code block is only executed when this -# module is the main program. -if __name__ == '__main__': - # Instantiate a class - i = Human(name="Ian") - i.say("hi") # "Ian: hi" - j = Human("Joel") - j.say("hello") # "Joel: hello" - # i and j are instances of type Human, or in other words: they are Human objects - - # Call our class method - i.say(i.get_species()) # "Ian: H. sapiens" - # Change the shared attribute - Human.species = "H. neanderthalensis" - i.say(i.get_species()) # => "Ian: H. neanderthalensis" - j.say(j.get_species()) # => "Joel: H. neanderthalensis" - - # Call the static method - print(Human.grunt()) # => "*grunt*" - - # Cannot call static method with instance of object - # because i.grunt() will automatically put "self" (the object i) as an argument - print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given - - # Update the property for this instance - i.age = 42 - # Get the property - i.say(i.age) # => "Ian: 42" - j.say(j.age) # => "Joel: 0" - # Delete the property - del i.age - # i.age # => this would raise an AttributeError - - -#################################################### -## 6.1 Inheritance -#################################################### - -# Inheritance allows new child classes to be defined that inherit methods and -# variables from their parent class. - -# Using the Human class defined above as the base or parent class, we can -# define a child class, Superhero, which inherits the class variables like -# "species", "name", and "age", as well as methods, like "sing" and "grunt" -# from the Human class, but can also have its own unique properties. - -# To take advantage of modularization by file you could place the classes above in their own files, -# say, human.py - -# To import functions from other files use the following format -# from "filename-without-extension" import "function-or-class" - -from human import Human - - -# Specify the parent class(es) as parameters to the class definition -class Superhero(Human): - - # If the child class should inherit all of the parent's definitions without - # any modifications, you can just use the "pass" keyword (and nothing else) - # but in this case it is commented out to allow for a unique child class: - # pass - - # Child classes can override their parents' attributes - species = 'Superhuman' - - # Children automatically inherit their parent class's constructor including - # its arguments, but can also define additional arguments or definitions - # and override its methods such as the class constructor. - # This constructor inherits the "name" argument from the "Human" class and - # adds the "superpower" and "movie" arguments: - def __init__(self, name, movie=False, - superpowers=["super strength", "bulletproofing"]): - - # add additional class attributes: - self.fictional = True - self.movie = movie - # be aware of mutable default values, since defaults are shared - self.superpowers = superpowers - - # The "super" function lets you access the parent class's methods - # that are overridden by the child, in this case, the __init__ method. - # This calls the parent class constructor: - super().__init__(name) - - # override the sing method - def sing(self): - return 'Dun, dun, DUN!' - - # add an additional instance method - def boast(self): - for power in self.superpowers: - print("I wield the power of {pow}!".format(pow=power)) - - -if __name__ == '__main__': - sup = Superhero(name="Tick") - - # Instance type checks - if isinstance(sup, Human): - print('I am human') - if type(sup) is Superhero: - print('I am a superhero') - - # Get the Method Resolution search Order used by both getattr() and super() - # This attribute is dynamic and can be updated - print(Superhero.__mro__) # => (, - # => , ) - - # Calls parent method but uses its own class attribute - print(sup.get_species()) # => Superhuman - - # Calls overridden method - print(sup.sing()) # => Dun, dun, DUN! - - # Calls method from Human - sup.say('Spoon') # => Tick: Spoon - - # Call method that exists only in Superhero - sup.boast() # => I wield the power of super strength! - # => I wield the power of bulletproofing! - - # Inherited class attribute - sup.age = 31 - print(sup.age) # => 31 - - # Attribute that only exists within Superhero - print('Am I Oscar eligible? ' + str(sup.movie)) - -#################################################### -## 6.2 Multiple Inheritance -#################################################### - -# Another class definition -# bat.py -class Bat: - - species = 'Baty' - - def __init__(self, can_fly=True): - self.fly = can_fly - - # This class also has a say method - def say(self, msg): - msg = '... ... ...' - return msg - - # And its own method as well - def sonar(self): - return '))) ... (((' - -if __name__ == '__main__': - b = Bat() - print(b.say('hello')) - print(b.fly) - - -# And yet another class definition that inherits from Superhero and Bat -# superhero.py -from superhero import Superhero -from bat import Bat - -# Define Batman as a child that inherits from both Superhero and Bat -class Batman(Superhero, Bat): - - def __init__(self, *args, **kwargs): - # Typically to inherit attributes you have to call super: - # super(Batman, self).__init__(*args, **kwargs) - # However we are dealing with multiple inheritance here, and super() - # only works with the next base class in the MRO list. - # So instead we explicitly call __init__ for all ancestors. - # The use of *args and **kwargs allows for a clean way to pass arguments, - # with each parent "peeling a layer of the onion". - Superhero.__init__(self, 'anonymous', movie=True, - superpowers=['Wealthy'], *args, **kwargs) - Bat.__init__(self, *args, can_fly=False, **kwargs) - # override the value for the name attribute - self.name = 'Sad Affleck' - - def sing(self): - return 'nan nan nan nan nan batman!' - - -if __name__ == '__main__': - sup = Batman() - - # Get the Method Resolution search Order used by both getattr() and super(). - # This attribute is dynamic and can be updated - print(Batman.__mro__) # => (, - # => , - # => , - # => , ) - - # Calls parent method but uses its own class attribute - print(sup.get_species()) # => Superhuman - - # Calls overridden method - print(sup.sing()) # => nan nan nan nan nan batman! - - # Calls method from Human, because inheritance order matters - sup.say('I agree') # => Sad Affleck: I agree - - # Call method that exists only in 2nd ancestor - print(sup.sonar()) # => ))) ... ((( - - # Inherited class attribute - sup.age = 100 - print(sup.age) # => 100 - - # Inherited attribute from 2nd ancestor whose default value was overridden. - print('Can I fly? ' + str(sup.fly)) # => Can I fly? False - - - -#################################################### -## 7. Advanced -#################################################### - -# Generators help you make lazy code. -def double_numbers(iterable): - for i in iterable: - yield i + i - -# Generators are memory-efficient because they only load the data needed to -# process the next value in the iterable. This allows them to perform -# operations on otherwise prohibitively large value ranges. -# NOTE: `range` replaces `xrange` in Python 3. -for i in double_numbers(range(1, 900000000)): # `range` is a generator. - print(i) - if i >= 30: - break - -# Just as you can create a list comprehension, you can create generator -# comprehensions as well. -values = (-x for x in [1,2,3,4,5]) -for x in values: - print(x) # prints -1 -2 -3 -4 -5 to console/terminal - -# You can also cast a generator comprehension directly to a list. -values = (-x for x in [1,2,3,4,5]) -gen_to_list = list(values) -print(gen_to_list) # => [-1, -2, -3, -4, -5] - - -# Decorators -# In this example `beg` wraps `say`. If say_please is True then it -# will change the returned message. -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please - - -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( -``` - -## Ready For More? - -### Free Online - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) -* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) -* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) -* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) -* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) -* [Dive Into Python 3](http://www.diveintopython3.net/index.html) -* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown new file mode 100644 index 00000000..bf80fed2 --- /dev/null +++ b/ru-ru/python-ru.html.markdown @@ -0,0 +1,651 @@ +--- +language: python3 +lang: ru-ru +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Steven Basart", "http://github.com/xksteven"] +translators: + - ["Andre Polykanine", "https://github.com/Oire"] +filename: learnpython3-ru.py +--- + +Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из +самых популярных языков. Я влюбился в Python за понятный и доходчивый синтаксис — это +почти что исполняемый псевдокод. + +С благодарностью жду ваших отзывов: [@louiedinh](http://twitter.com/louiedinh) +или louiedinh [at] [почтовый сервис Google] + +Замечание: Эта статья относится только к Python 3. +Если вы хотите изучить Python 2.7, обратитесь к другой статье. + +```python +# Однострочные комментарии начинаются с символа решётки. +""" Многострочный текст может быть + записан, используя 3 знака " и обычно используется + в качестве встроенной документации +""" + +#################################################### +## 1. Примитивные типы данных и операторы +#################################################### + +# У вас есть числа +3 #=> 3 + +# Математика работает вполне ожидаемо +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 + +# Кроме деления, которое по умолчанию возвращает число с плавающей запятой +35 / 5 # => 7.0 + +# Результат целочисленного деления округляется в меньшую сторону +# как для положительных, так и для отрицательных чисел. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # работает и для чисел с плавающей запятой +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Когда вы используете числа с плавающей запятой, +# результатом будет также число с плавающей запятой +3 * 2.0 # => 6.0 + +# Остаток от деления +7 % 3 # => 1 + +# Возведение в степень +2**4 # => 16 + +# Приоритет операций указывается скобками +(1 + 3) * 2 #=> 8 + +# Для логических (булевых) значений существует отдельный примитивный тип +True +False + +# Для отрицания используется ключевое слово not +not True #=> False +not False #=> True + +# Логические операторы +# Обратите внимание: ключевые слова «and» и «or» чувствительны к регистру букв +True and False #=> False +False or True #=> True + +# Обратите внимание, что логические операторы используются и с целыми числами +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# Равенство — это == +1 == 1 #=> True +2 == 1 #=> False + +# Неравенство — это != +1 != 1 #=> False +2 != 1 #=> True + +# Ещё немного сравнений +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# Сравнения могут быть записаны цепочкой: +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Строки определяются символом " или ' +"Это строка." +'Это тоже строка.' + +# И строки тоже могут складываться! Хотя лучше не злоупотребляйте этим. +"Привет " + "мир!" #=> "Привет мир!" + +# Строки можно умножать. +"aa" * 4 #=> "aaaaaaaa" + +# Со строкой можно работать, как со списком символов +"Это строка"[0] #=> 'Э' + +# Метод format используется для форматирования строк: +"{0} могут быть {1}".format("строки", "форматированы") + +# Вы можете повторять аргументы форматирования, чтобы меньше печатать. +"Ехал {0} через реку, видит {0} - в реке {1}! Сунул {0} руку в реку, {1} за руку греку цап!".format("грека", "рак") +#=> "Ехал грека через реку, видит грека - в реке рак! Сунул грека руку в реку, рак за руку греку цап!" +# Если вы не хотите считать, можете использовать ключевые слова. +"{name} хочет есть {food}".format(name="Боб", food="лазанью") + +# Если ваш код на Python 3 нужно запускать также и под Python 2.5 и ниже, +# вы также можете использовать старый способ форматирования: +"%s можно %s %s способом" % ("строки", "интерполировать", "старым") + +# None является объектом +None #=> None + +# Не используйте оператор равенства '==' для сравнения +# объектов с None. Используйте для этого 'is' +"etc" is None #=> False +None is None #=> True + +# Оператор «is» проверяет идентичность объектов. Он не +# очень полезен при работе с примитивными типами, но +# зато просто незаменим при работе с объектами. + +# None, 0 и пустые строки/списки/словари приводятся к False. +# Все остальные значения равны True +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False + + +#################################################### +## 2. Переменные и коллекции +#################################################### + +# В Python есть функция Print +print("Я Python. Приятно познакомиться!") + +# Объявлять переменные перед инициализацией не нужно. +# По соглашению используется нижний_регистр_с_подчёркиваниями +some_var = 5 +some_var #=> 5 + +# При попытке доступа к неинициализированной переменной +# выбрасывается исключение. +# Об исключениях см. раздел «Поток управления и итерируемые объекты». +some_unknown_var # Выбрасывает ошибку именования + +# Списки хранят последовательности +li = [] +# Можно сразу начать с заполненного списка +other_li = [4, 5, 6] + +# Объекты добавляются в конец списка методом append +li.append(1) # [1] +li.append(2) # [1, 2] +li.append(4) # [1, 2, 4] +li.append(3) # [1, 2, 4, 3] +# И удаляются с конца методом pop +li.pop() #=> возвращает 3 и li становится равен [1, 2, 4] +# Положим элемент обратно +li.append(3) # [1, 2, 4, 3]. + +# Обращайтесь со списком, как с обычным массивом +li[0] #=> 1 +# Обратимся к последнему элементу +li[-1] #=> 3 + +# Попытка выйти за границы массива приведёт к ошибке индекса +li[4] # Выдаёт IndexError + +# Можно обращаться к диапазону, используя так называемые срезы +# (Для тех, кто любит математику, это называется замкнуто-открытый интервал). +li[1:3] #=> [2, 4] +# Опускаем начало +li[2:] #=> [4, 3] +# Опускаем конец +li[:3] #=> [1, 2, 4] +# Выбираем каждый второй элемент +li[::2] # =>[1, 4] +# Переворачиваем список +li[::-1] # => [3, 4, 2, 1] +# Используйте сочетания всего вышеназванного для выделения более сложных срезов +# li[начало:конец:шаг] + +# Удаляем произвольные элементы из списка оператором del +del li[2] # [1, 2, 3] + +# Вы можете складывать, или, как ещё говорят, конкатенировать списки +# Обратите внимание: значения li и other_li при этом не изменились. +li + other_li #=> [1, 2, 3, 4, 5, 6] — Замечание: li и other_li не изменяются + +# Объединять списки можно методом extend +li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6] + +# Проверить элемент на вхождение в список можно оператором in +1 in li #=> True + +# Длина списка вычисляется функцией len +len(li) #=> 6 + + +# Кортежи — это такие списки, только неизменяемые +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # Выдаёт TypeError + +# Всё то же самое можно делать и с кортежами +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Вы можете распаковывать кортежи (или списки) в переменные +a, b, c = (1, 2, 3) # a == 1, b == 2 и c == 3 +# Кортежи создаются по умолчанию, если опущены скобки +d, e, f = 4, 5, 6 +# Обратите внимание, как легко поменять местами значения двух переменных +e, d = d, e # теперь d == 5, а e == 4 + + +# Словари содержат ассоциативные массивы +empty_dict = {} +# Вот так описывается предзаполненный словарь +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Значения извлекаются так же, как из списка, с той лишь разницей, +# что индекс — у словарей он называется ключом — не обязан быть числом +filled_dict["one"] #=> 1 + +# Все ключи в виде списка получаются с помощью метода keys(). +# Его вызов нужно обернуть в list(), так как обратно мы получаем +# итерируемый объект, о которых поговорим позднее. +list(filled_dict.keys()) # => ["three", "two", "one"] +# Замечание: сохранение порядка ключей в словаре не гарантируется +# Ваши результаты могут не совпадать с этими. + +# Все значения в виде списка можно получить с помощью values(). +# И снова нам нужно обернуть вызов в list(), чтобы превратить +# итерируемый объект в список. +list(filled_dict.values()) # => [3, 2, 1] +# То же самое замечание насчёт порядка ключей справедливо и здесь + +# При помощи оператора in можно проверять ключи на вхождение в словарь +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# Попытка получить значение по несуществующему ключу выбросит ошибку ключа +filled_dict["four"] # KeyError + +# Чтобы избежать этого, используйте метод get() +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# Метод get также принимает аргумент по умолчанию, значение которого будет +# возвращено при отсутствии указанного ключа +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# Метод setdefault вставляет пару ключ-значение, только если такого ключа нет +filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5 +filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5 + +# Добавление элементов в словарь +filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} +#filled_dict["four"] = 4 # Другой способ добавления элементов + +# Удаляйте ключи из словаря с помощью оператора del +del filled_dict["one"] # Удаляет ключ «one» из словаря + + +# Множества содержат... ну, в общем, множества +empty_set = set() +# Инициализация множества набором значений. +# Да, оно выглядит примерно как словарь… ну извините, так уж вышло. +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Множеству можно назначать новую переменную +filled_set = some_set + +# Добавление новых элементов в множество +filled_set.add(5) # filled_set равно {1, 2, 3, 4, 5} + +# Пересечение множеств: & +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# Объединение множеств: | +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# Разность множеств: - +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Проверка на вхождение во множество: in +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. Поток управления и итерируемые объекты +#################################################### + +# Для начала заведём переменную +some_var = 5 + +# Так выглядит выражение if. Отступы в python очень важны! +# результат: «some_var меньше, чем 10» +if some_var > 10: + print("some_var намного больше, чем 10.") +elif some_var < 10: # Выражение elif необязательно. + print("some_var меньше, чем 10.") +else: # Это тоже необязательно. + print("some_var равно 10.") + + +# Циклы For проходят по спискам. Результат: + # собака — это млекопитающее + # кошка — это млекопитающее + # мышь — это млекопитающее +for animal in ["собака", "кошка", "мышь"]: + # Можете использовать format() для интерполяции форматированных строк + print("{} — это млекопитающее".format(animal)) + +""" +«range(число)» возвращает список чисел +от нуля до заданного числа +Результат: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +Циклы while продолжаются до тех пор, пока указанное условие не станет ложным. +Результат: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Краткая запись для x = x + 1 + +# Обрабатывайте исключения блоками try/except +try: + # Чтобы выбросить ошибку, используется raise + raise IndexError("Это ошибка индекса") +except IndexError as e: + # pass — это просто отсутствие оператора. Обычно здесь происходит + # восстановление после ошибки. + pass +except (TypeError, NameError): + pass # Несколько исключений можно обработать вместе, если нужно. +else: # Необязательное выражение. Должно следовать за последним блоком except + print("Всё хорошо!") # Выполнится, только если не было никаких исключений + +# Python предоставляет фундаментальную абстракцию, +# которая называется итерируемым объектом (an iterable). +# Итерируемый объект — это объект, который воспринимается как последовательность. +# Объект, который возвратила функция range(), итерируемый. +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) #=> range(1,10). Это объект, реализующий интерфейс iterable + +# Мы можем проходить по нему циклом. +for i in our_iterable: + print(i) # Выводит one, two, three + +# Но мы не можем обращаться к элементу по индексу. +our_iterable[1] # Выбрасывает ошибку типа + +# Итерируемый объект знает, как создавать итератор. +our_iterator = iter(our_iterable) + +# Итератор может запоминать состояние при проходе по объекту. +# Мы получаем следующий объект, вызывая функцию __next__. +our_iterator.__next__() #=> "one" + +# Он сохраняет состояние при вызове __next__. +our_iterator.__next__() #=> "two" +our_iterator.__next__() #=> "three" + +# Возвратив все данные, итератор выбрасывает исключение StopIterator +our_iterator.__next__() # Выбрасывает исключение остановки итератора + +# Вы можете получить сразу все элементы итератора, вызвав на нём функцию list(). +list(filled_dict.keys()) #=> Возвращает ["one", "two", "three"] + + +#################################################### +## 4. Функции +#################################################### + +# Используйте def для создания новых функций +def add(x, y): + print("x равен %s, а y равен %s" % (x, y)) + return x + y # Возвращайте результат с помощью ключевого слова return + +# Вызов функции с аргументами +add(5, 6) #=> выводит «x равен 5, а y равен 6» и возвращает 11 + +# Другой способ вызова функции — вызов с именованными аргументами +add(y=6, x=5) # Именованные аргументы можно указывать в любом порядке. + +# Вы можете определить функцию, принимающую переменное число аргументов +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# А также можете определить функцию, принимающую переменное число +# именованных аргументов +def keyword_args(**kwargs): + return kwargs + +# Вызовем эту функцию и посмотрим, что из этого получится +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# Если хотите, можете использовать оба способа одновременно +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) выводит: + (1, 2) + {"a": 3, "b": 4} +""" + +# Вызывая функции, можете сделать наоборот! +# Используйте символ * для распаковки кортежей и ** для распаковки словарей +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # эквивалентно foo(1, 2, 3, 4) +all_the_args(**kwargs) # эквивалентно foo(a=3, b=4) +all_the_args(*args, **kwargs) # эквивалентно foo(1, 2, 3, 4, a=3, b=4) + +# Область определения функций +x = 5 + +def setX(num): + # Локальная переменная x — это не то же самое, что глобальная переменная x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # Глобальная переменная x теперь равна 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + +# В Python функции — «объекты первого класса» +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Также есть и анонимные функции +(lambda x: x > 2)(3) #=> True + +# Есть встроенные функции высшего порядка +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Для удобного отображения и фильтрации можно использовать списочные включения +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] + +#################################################### +## 5. Классы +#################################################### + +# Чтобы получить класс, мы наследуемся от object. +class Human(object): + + # Атрибут класса. Он разделяется всеми экземплярами этого класса + species = "H. sapiens" + + # Обычный конструктор, вызывается при инициализации экземпляра класса + # Обратите внимание, что двойное подчёркивание в начале и в конце имени + # означает объекты и атрибуты, которые используются Python, но находятся + # в пространствах имён, управляемых пользователем. + # Не придумывайте им имена самостоятельно. + def __init__(self, name): + # Присваивание значения аргумента атрибуту класса name + self.name = name + + # Метод экземпляра. Все методы принимают self в качестве первого аргумента + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # Метод класса разделяется между всеми экземплярами + # Они вызываются с указыванием вызывающего класса в качестве первого аргумента + @classmethod + def get_species(cls): + return cls.species + + # Статический метод вызывается без ссылки на класс или экземпляр + @staticmethod + def grunt(): + return "*grunt*" + + +# Инициализация экземпляра класса +i = Human(name="Иван") +print(i.say("привет")) # Выводит: «Иван: привет» + +j = Human("Пётр") +print(j.say("Привет")) # Выводит: «Пётр: привет» + +# Вызов метода класса +i.get_species() #=> "H. sapiens" + +# Изменение разделяемого атрибута +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Вызов статического метода +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. Модули +#################################################### + +# Вы можете импортировать модули +import math +print(math.sqrt(16)) #=> 4.0 + +# Вы можете импортировать отдельные функции модуля +from math import ceil, floor +print(ceil(3.7)) #=> 4.0 +print(floor(3.7)) #=> 3.0 + +# Можете импортировать все функции модуля. +# (Хотя это и не рекомендуется) +from math import * + +# Можете сокращать имена модулей +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Модули в Python — это обычные Python-файлы. Вы +# можете писать свои модули и импортировать их. Название +# модуля совпадает с названием файла. + +# Вы можете узнать, какие функции и атрибуты определены +# в модуле +import math +dir(math) + +#################################################### +## 7. Дополнительно +#################################################### + +# Генераторы помогут выполнить ленивые вычисления +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Генератор создаёт значения на лету. +# Он не возвращает все значения разом, а создаёт каждое из них при каждой +# итерации. Это значит, что значения больше 15 в double_numbers +# обработаны не будут. +# Обратите внимание: range — это тоже генератор. +# Создание списка чисел от 1 до 900000000 требует много места и времени. +# Если нам нужно имя переменной, совпадающее с ключевым словом Python, +# мы используем подчёркивание в конце +range_ = range(1, 900000000) + +# Будет удваивать все числа, пока результат не превысит 30 +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Декораторы +# В этом примере beg оборачивает say +# Метод beg вызовет say. Если say_please равно True, +# он изменит возвращаемое сообщение +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, " Пожалуйста! У меня нет денег :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Вы не купите мне пива?" + return msg, say_please + + +print(say()) # Вы не купите мне пива? +print(say(say_please=True)) # Вы не купите мне пива? Пожалуйста! У меня нет денег :( + +``` + +## Хотите ещё? + +### Бесплатные онлайн-материалы + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [Официальная документация](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/3/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +### Платные + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + diff --git a/ru-ru/python3-ru.html.markdown b/ru-ru/python3-ru.html.markdown deleted file mode 100644 index bf80fed2..00000000 --- a/ru-ru/python3-ru.html.markdown +++ /dev/null @@ -1,651 +0,0 @@ ---- -language: python3 -lang: ru-ru -contributors: - - ["Louie Dinh", "http://ldinh.ca"] - - ["Steven Basart", "http://github.com/xksteven"] -translators: - - ["Andre Polykanine", "https://github.com/Oire"] -filename: learnpython3-ru.py ---- - -Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из -самых популярных языков. Я влюбился в Python за понятный и доходчивый синтаксис — это -почти что исполняемый псевдокод. - -С благодарностью жду ваших отзывов: [@louiedinh](http://twitter.com/louiedinh) -или louiedinh [at] [почтовый сервис Google] - -Замечание: Эта статья относится только к Python 3. -Если вы хотите изучить Python 2.7, обратитесь к другой статье. - -```python -# Однострочные комментарии начинаются с символа решётки. -""" Многострочный текст может быть - записан, используя 3 знака " и обычно используется - в качестве встроенной документации -""" - -#################################################### -## 1. Примитивные типы данных и операторы -#################################################### - -# У вас есть числа -3 #=> 3 - -# Математика работает вполне ожидаемо -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 - -# Кроме деления, которое по умолчанию возвращает число с плавающей запятой -35 / 5 # => 7.0 - -# Результат целочисленного деления округляется в меньшую сторону -# как для положительных, так и для отрицательных чисел. -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # работает и для чисел с плавающей запятой --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Когда вы используете числа с плавающей запятой, -# результатом будет также число с плавающей запятой -3 * 2.0 # => 6.0 - -# Остаток от деления -7 % 3 # => 1 - -# Возведение в степень -2**4 # => 16 - -# Приоритет операций указывается скобками -(1 + 3) * 2 #=> 8 - -# Для логических (булевых) значений существует отдельный примитивный тип -True -False - -# Для отрицания используется ключевое слово not -not True #=> False -not False #=> True - -# Логические операторы -# Обратите внимание: ключевые слова «and» и «or» чувствительны к регистру букв -True and False #=> False -False or True #=> True - -# Обратите внимание, что логические операторы используются и с целыми числами -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -1 == True #=> True - -# Равенство — это == -1 == 1 #=> True -2 == 1 #=> False - -# Неравенство — это != -1 != 1 #=> False -2 != 1 #=> True - -# Ещё немного сравнений -1 < 10 #=> True -1 > 10 #=> False -2 <= 2 #=> True -2 >= 2 #=> True - -# Сравнения могут быть записаны цепочкой: -1 < 2 < 3 #=> True -2 < 3 < 2 #=> False - -# Строки определяются символом " или ' -"Это строка." -'Это тоже строка.' - -# И строки тоже могут складываться! Хотя лучше не злоупотребляйте этим. -"Привет " + "мир!" #=> "Привет мир!" - -# Строки можно умножать. -"aa" * 4 #=> "aaaaaaaa" - -# Со строкой можно работать, как со списком символов -"Это строка"[0] #=> 'Э' - -# Метод format используется для форматирования строк: -"{0} могут быть {1}".format("строки", "форматированы") - -# Вы можете повторять аргументы форматирования, чтобы меньше печатать. -"Ехал {0} через реку, видит {0} - в реке {1}! Сунул {0} руку в реку, {1} за руку греку цап!".format("грека", "рак") -#=> "Ехал грека через реку, видит грека - в реке рак! Сунул грека руку в реку, рак за руку греку цап!" -# Если вы не хотите считать, можете использовать ключевые слова. -"{name} хочет есть {food}".format(name="Боб", food="лазанью") - -# Если ваш код на Python 3 нужно запускать также и под Python 2.5 и ниже, -# вы также можете использовать старый способ форматирования: -"%s можно %s %s способом" % ("строки", "интерполировать", "старым") - -# None является объектом -None #=> None - -# Не используйте оператор равенства '==' для сравнения -# объектов с None. Используйте для этого 'is' -"etc" is None #=> False -None is None #=> True - -# Оператор «is» проверяет идентичность объектов. Он не -# очень полезен при работе с примитивными типами, но -# зато просто незаменим при работе с объектами. - -# None, 0 и пустые строки/списки/словари приводятся к False. -# Все остальные значения равны True -bool(0) # => False -bool("") # => False -bool([]) #=> False -bool({}) #=> False - - -#################################################### -## 2. Переменные и коллекции -#################################################### - -# В Python есть функция Print -print("Я Python. Приятно познакомиться!") - -# Объявлять переменные перед инициализацией не нужно. -# По соглашению используется нижний_регистр_с_подчёркиваниями -some_var = 5 -some_var #=> 5 - -# При попытке доступа к неинициализированной переменной -# выбрасывается исключение. -# Об исключениях см. раздел «Поток управления и итерируемые объекты». -some_unknown_var # Выбрасывает ошибку именования - -# Списки хранят последовательности -li = [] -# Можно сразу начать с заполненного списка -other_li = [4, 5, 6] - -# Объекты добавляются в конец списка методом append -li.append(1) # [1] -li.append(2) # [1, 2] -li.append(4) # [1, 2, 4] -li.append(3) # [1, 2, 4, 3] -# И удаляются с конца методом pop -li.pop() #=> возвращает 3 и li становится равен [1, 2, 4] -# Положим элемент обратно -li.append(3) # [1, 2, 4, 3]. - -# Обращайтесь со списком, как с обычным массивом -li[0] #=> 1 -# Обратимся к последнему элементу -li[-1] #=> 3 - -# Попытка выйти за границы массива приведёт к ошибке индекса -li[4] # Выдаёт IndexError - -# Можно обращаться к диапазону, используя так называемые срезы -# (Для тех, кто любит математику, это называется замкнуто-открытый интервал). -li[1:3] #=> [2, 4] -# Опускаем начало -li[2:] #=> [4, 3] -# Опускаем конец -li[:3] #=> [1, 2, 4] -# Выбираем каждый второй элемент -li[::2] # =>[1, 4] -# Переворачиваем список -li[::-1] # => [3, 4, 2, 1] -# Используйте сочетания всего вышеназванного для выделения более сложных срезов -# li[начало:конец:шаг] - -# Удаляем произвольные элементы из списка оператором del -del li[2] # [1, 2, 3] - -# Вы можете складывать, или, как ещё говорят, конкатенировать списки -# Обратите внимание: значения li и other_li при этом не изменились. -li + other_li #=> [1, 2, 3, 4, 5, 6] — Замечание: li и other_li не изменяются - -# Объединять списки можно методом extend -li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6] - -# Проверить элемент на вхождение в список можно оператором in -1 in li #=> True - -# Длина списка вычисляется функцией len -len(li) #=> 6 - - -# Кортежи — это такие списки, только неизменяемые -tup = (1, 2, 3) -tup[0] #=> 1 -tup[0] = 3 # Выдаёт TypeError - -# Всё то же самое можно делать и с кортежами -len(tup) #=> 3 -tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tup[:2] #=> (1, 2) -2 in tup #=> True - -# Вы можете распаковывать кортежи (или списки) в переменные -a, b, c = (1, 2, 3) # a == 1, b == 2 и c == 3 -# Кортежи создаются по умолчанию, если опущены скобки -d, e, f = 4, 5, 6 -# Обратите внимание, как легко поменять местами значения двух переменных -e, d = d, e # теперь d == 5, а e == 4 - - -# Словари содержат ассоциативные массивы -empty_dict = {} -# Вот так описывается предзаполненный словарь -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Значения извлекаются так же, как из списка, с той лишь разницей, -# что индекс — у словарей он называется ключом — не обязан быть числом -filled_dict["one"] #=> 1 - -# Все ключи в виде списка получаются с помощью метода keys(). -# Его вызов нужно обернуть в list(), так как обратно мы получаем -# итерируемый объект, о которых поговорим позднее. -list(filled_dict.keys()) # => ["three", "two", "one"] -# Замечание: сохранение порядка ключей в словаре не гарантируется -# Ваши результаты могут не совпадать с этими. - -# Все значения в виде списка можно получить с помощью values(). -# И снова нам нужно обернуть вызов в list(), чтобы превратить -# итерируемый объект в список. -list(filled_dict.values()) # => [3, 2, 1] -# То же самое замечание насчёт порядка ключей справедливо и здесь - -# При помощи оператора in можно проверять ключи на вхождение в словарь -"one" in filled_dict #=> True -1 in filled_dict #=> False - -# Попытка получить значение по несуществующему ключу выбросит ошибку ключа -filled_dict["four"] # KeyError - -# Чтобы избежать этого, используйте метод get() -filled_dict.get("one") #=> 1 -filled_dict.get("four") #=> None -# Метод get также принимает аргумент по умолчанию, значение которого будет -# возвращено при отсутствии указанного ключа -filled_dict.get("one", 4) #=> 1 -filled_dict.get("four", 4) #=> 4 - -# Метод setdefault вставляет пару ключ-значение, только если такого ключа нет -filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5 -filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5 - -# Добавление элементов в словарь -filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} -#filled_dict["four"] = 4 # Другой способ добавления элементов - -# Удаляйте ключи из словаря с помощью оператора del -del filled_dict["one"] # Удаляет ключ «one» из словаря - - -# Множества содержат... ну, в общем, множества -empty_set = set() -# Инициализация множества набором значений. -# Да, оно выглядит примерно как словарь… ну извините, так уж вышло. -filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} - -# Множеству можно назначать новую переменную -filled_set = some_set - -# Добавление новых элементов в множество -filled_set.add(5) # filled_set равно {1, 2, 3, 4, 5} - -# Пересечение множеств: & -other_set = {3, 4, 5, 6} -filled_set & other_set #=> {3, 4, 5} - -# Объединение множеств: | -filled_set | other_set #=> {1, 2, 3, 4, 5, 6} - -# Разность множеств: - -{1,2,3,4} - {2,3,5} #=> {1, 4} - -# Проверка на вхождение во множество: in -2 in filled_set #=> True -10 in filled_set #=> False - - -#################################################### -## 3. Поток управления и итерируемые объекты -#################################################### - -# Для начала заведём переменную -some_var = 5 - -# Так выглядит выражение if. Отступы в python очень важны! -# результат: «some_var меньше, чем 10» -if some_var > 10: - print("some_var намного больше, чем 10.") -elif some_var < 10: # Выражение elif необязательно. - print("some_var меньше, чем 10.") -else: # Это тоже необязательно. - print("some_var равно 10.") - - -# Циклы For проходят по спискам. Результат: - # собака — это млекопитающее - # кошка — это млекопитающее - # мышь — это млекопитающее -for animal in ["собака", "кошка", "мышь"]: - # Можете использовать format() для интерполяции форматированных строк - print("{} — это млекопитающее".format(animal)) - -""" -«range(число)» возвращает список чисел -от нуля до заданного числа -Результат: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -Циклы while продолжаются до тех пор, пока указанное условие не станет ложным. -Результат: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Краткая запись для x = x + 1 - -# Обрабатывайте исключения блоками try/except -try: - # Чтобы выбросить ошибку, используется raise - raise IndexError("Это ошибка индекса") -except IndexError as e: - # pass — это просто отсутствие оператора. Обычно здесь происходит - # восстановление после ошибки. - pass -except (TypeError, NameError): - pass # Несколько исключений можно обработать вместе, если нужно. -else: # Необязательное выражение. Должно следовать за последним блоком except - print("Всё хорошо!") # Выполнится, только если не было никаких исключений - -# Python предоставляет фундаментальную абстракцию, -# которая называется итерируемым объектом (an iterable). -# Итерируемый объект — это объект, который воспринимается как последовательность. -# Объект, который возвратила функция range(), итерируемый. -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) #=> range(1,10). Это объект, реализующий интерфейс iterable - -# Мы можем проходить по нему циклом. -for i in our_iterable: - print(i) # Выводит one, two, three - -# Но мы не можем обращаться к элементу по индексу. -our_iterable[1] # Выбрасывает ошибку типа - -# Итерируемый объект знает, как создавать итератор. -our_iterator = iter(our_iterable) - -# Итератор может запоминать состояние при проходе по объекту. -# Мы получаем следующий объект, вызывая функцию __next__. -our_iterator.__next__() #=> "one" - -# Он сохраняет состояние при вызове __next__. -our_iterator.__next__() #=> "two" -our_iterator.__next__() #=> "three" - -# Возвратив все данные, итератор выбрасывает исключение StopIterator -our_iterator.__next__() # Выбрасывает исключение остановки итератора - -# Вы можете получить сразу все элементы итератора, вызвав на нём функцию list(). -list(filled_dict.keys()) #=> Возвращает ["one", "two", "three"] - - -#################################################### -## 4. Функции -#################################################### - -# Используйте def для создания новых функций -def add(x, y): - print("x равен %s, а y равен %s" % (x, y)) - return x + y # Возвращайте результат с помощью ключевого слова return - -# Вызов функции с аргументами -add(5, 6) #=> выводит «x равен 5, а y равен 6» и возвращает 11 - -# Другой способ вызова функции — вызов с именованными аргументами -add(y=6, x=5) # Именованные аргументы можно указывать в любом порядке. - -# Вы можете определить функцию, принимающую переменное число аргументов -def varargs(*args): - return args - -varargs(1, 2, 3) #=> (1,2,3) - - -# А также можете определить функцию, принимающую переменное число -# именованных аргументов -def keyword_args(**kwargs): - return kwargs - -# Вызовем эту функцию и посмотрим, что из этого получится -keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} - -# Если хотите, можете использовать оба способа одновременно -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) выводит: - (1, 2) - {"a": 3, "b": 4} -""" - -# Вызывая функции, можете сделать наоборот! -# Используйте символ * для распаковки кортежей и ** для распаковки словарей -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # эквивалентно foo(1, 2, 3, 4) -all_the_args(**kwargs) # эквивалентно foo(a=3, b=4) -all_the_args(*args, **kwargs) # эквивалентно foo(1, 2, 3, 4, a=3, b=4) - -# Область определения функций -x = 5 - -def setX(num): - # Локальная переменная x — это не то же самое, что глобальная переменная x - x = num # => 43 - print (x) # => 43 - -def setGlobalX(num): - global x - print (x) # => 5 - x = num # Глобальная переменная x теперь равна 6 - print (x) # => 6 - -setX(43) -setGlobalX(6) - -# В Python функции — «объекты первого класса» -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) #=> 13 - -# Также есть и анонимные функции -(lambda x: x > 2)(3) #=> True - -# Есть встроенные функции высшего порядка -map(add_10, [1,2,3]) #=> [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] - -# Для удобного отображения и фильтрации можно использовать списочные включения -[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] - -#################################################### -## 5. Классы -#################################################### - -# Чтобы получить класс, мы наследуемся от object. -class Human(object): - - # Атрибут класса. Он разделяется всеми экземплярами этого класса - species = "H. sapiens" - - # Обычный конструктор, вызывается при инициализации экземпляра класса - # Обратите внимание, что двойное подчёркивание в начале и в конце имени - # означает объекты и атрибуты, которые используются Python, но находятся - # в пространствах имён, управляемых пользователем. - # Не придумывайте им имена самостоятельно. - def __init__(self, name): - # Присваивание значения аргумента атрибуту класса name - self.name = name - - # Метод экземпляра. Все методы принимают self в качестве первого аргумента - def say(self, msg): - return "{name}: {message}".format(name=self.name, message=msg) - - # Метод класса разделяется между всеми экземплярами - # Они вызываются с указыванием вызывающего класса в качестве первого аргумента - @classmethod - def get_species(cls): - return cls.species - - # Статический метод вызывается без ссылки на класс или экземпляр - @staticmethod - def grunt(): - return "*grunt*" - - -# Инициализация экземпляра класса -i = Human(name="Иван") -print(i.say("привет")) # Выводит: «Иван: привет» - -j = Human("Пётр") -print(j.say("Привет")) # Выводит: «Пётр: привет» - -# Вызов метода класса -i.get_species() #=> "H. sapiens" - -# Изменение разделяемого атрибута -Human.species = "H. neanderthalensis" -i.get_species() #=> "H. neanderthalensis" -j.get_species() #=> "H. neanderthalensis" - -# Вызов статического метода -Human.grunt() #=> "*grunt*" - - -#################################################### -## 6. Модули -#################################################### - -# Вы можете импортировать модули -import math -print(math.sqrt(16)) #=> 4.0 - -# Вы можете импортировать отдельные функции модуля -from math import ceil, floor -print(ceil(3.7)) #=> 4.0 -print(floor(3.7)) #=> 3.0 - -# Можете импортировать все функции модуля. -# (Хотя это и не рекомендуется) -from math import * - -# Можете сокращать имена модулей -import math as m -math.sqrt(16) == m.sqrt(16) #=> True - -# Модули в Python — это обычные Python-файлы. Вы -# можете писать свои модули и импортировать их. Название -# модуля совпадает с названием файла. - -# Вы можете узнать, какие функции и атрибуты определены -# в модуле -import math -dir(math) - -#################################################### -## 7. Дополнительно -#################################################### - -# Генераторы помогут выполнить ленивые вычисления -def double_numbers(iterable): - for i in iterable: - yield i + i - -# Генератор создаёт значения на лету. -# Он не возвращает все значения разом, а создаёт каждое из них при каждой -# итерации. Это значит, что значения больше 15 в double_numbers -# обработаны не будут. -# Обратите внимание: range — это тоже генератор. -# Создание списка чисел от 1 до 900000000 требует много места и времени. -# Если нам нужно имя переменной, совпадающее с ключевым словом Python, -# мы используем подчёркивание в конце -range_ = range(1, 900000000) - -# Будет удваивать все числа, пока результат не превысит 30 -for i in double_numbers(range_): - print(i) - if i >= 30: - break - - -# Декораторы -# В этом примере beg оборачивает say -# Метод beg вызовет say. Если say_please равно True, -# он изменит возвращаемое сообщение -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, " Пожалуйста! У меня нет денег :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Вы не купите мне пива?" - return msg, say_please - - -print(say()) # Вы не купите мне пива? -print(say(say_please=True)) # Вы не купите мне пива? Пожалуйста! У меня нет денег :( - -``` - -## Хотите ещё? - -### Бесплатные онлайн-материалы - -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [Официальная документация](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/3/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) - -### Платные - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) - diff --git a/tr-tr/python-tr.html.markdown b/tr-tr/python-tr.html.markdown new file mode 100644 index 00000000..b78d517f --- /dev/null +++ b/tr-tr/python-tr.html.markdown @@ -0,0 +1,640 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Batuhan Osman T.", "https://github.com/BTaskaya"] +translators: + - ["Eray AYDIN", "http://erayaydin.me/"] +lang: tr-tr +filename: learnpython3-tr.py +--- + +Python,90ların başlarında Guido Van Rossum tarafından oluşturulmuştur. En popüler olan dillerden biridir. Beni Python'a aşık eden sebep onun syntax beraklığı. Çok basit bir çalıştırılabilir söz koddur. + +Not: Bu makale Python 3 içindir. Eğer Python 2.7 öğrenmek istiyorsanız [burayı](http://learnxinyminutes.com/docs/python/) kontrol edebilirsiniz. + +```python + +# Tek satırlık yorum satırı kare(#) işareti ile başlamaktadır. + +""" Çok satırlı olmasını istediğiniz yorumlar + üç adet tırnak(") işareti ile + yapılmaktadır +""" + +#################################################### +## 1. Temel Veri Türleri ve Operatörler +#################################################### + +# Sayılar +3 # => 3 + +# Tahmin edebileceğiniz gibi matematik +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Bölme işlemi varsayılan olarak onluk döndürür +35 / 5 # => 7.0 + +# Tam sayı bölmeleri, pozitif ve negatif sayılar için aşağıya yuvarlar +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # onluklar için de bu böyledir +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Onluk kullanırsanız, sonuç da onluk olur +3 * 2.0 # => 6.0 + +# Kalan operatörü +7 % 3 # => 1 + +# Üs (2 üzeri 4) +2**4 # => 16 + +# Parantez ile önceliği değiştirebilirsiniz +(1 + 3) * 2 # => 8 + +# Boolean(Doğru-Yanlış) değerleri standart +True +False + +# 'değil' ile terse çevirme +not True # => False +not False # => True + +# Boolean Operatörleri +# "and" ve "or" büyük küçük harf duyarlıdır +True and False #=> False +False or True #=> True + +# Bool operatörleri ile sayı kullanımı +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# Eşitlik kontrolü == +1 == 1 # => True +2 == 1 # => False + +# Eşitsizlik Kontrolü != +1 != 1 # => False +2 != 1 # => True + +# Diğer karşılaştırmalar +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Zincirleme şeklinde karşılaştırma da yapabilirsiniz! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Yazı(Strings) " veya ' işaretleri ile oluşturulabilir +"Bu bir yazı." +'Bu da bir yazı.' + +# Yazılar da eklenebilir! Fakat bunu yapmanızı önermem. +"Merhaba " + "dünya!" # => "Merhaba dünya!" + +# Bir yazı(string) karakter listesi gibi işlenebilir +"Bu bir yazı"[0] # => 'B' + +# .format ile yazıyı biçimlendirebilirsiniz, şu şekilde: +"{} da ayrıca {}".format("yazılar", "işlenebilir") + +# Biçimlendirme işleminde aynı argümanı da birden fazla kullanabilirsiniz. +"{0} çeviktir, {0} hızlıdır, {0} , {1} üzerinden atlayabilir".format("Ahmet", "şeker çubuğu") +#=> "Ahmet çeviktir, Ahmet hızlıdır, Ahmet , şeker çubuğu üzerinden atlayabilir" + +# Argümanın sırasını saymak istemiyorsanız, anahtar kelime kullanabilirsiniz. +"{isim} yemek olarak {yemek} istiyor".format(isim="Ahmet", yemek="patates") #=> "Ahmet yemek olarak patates istiyor" + +# Eğer Python 3 kodunuz ayrıca Python 2.5 ve üstünde çalışmasını istiyorsanız, +# eski stil formatlamayı kullanabilirsiniz: +"%s bu %s yolla da %s" % ("yazılar", "eski", "biçimlendirilebilir") + + +# Hiçbir şey(none) da bir objedir +None # => None + +# Bir değerin none ile eşitlik kontrolü için "==" sembolünü kullanmayın +# Bunun yerine "is" kullanın. Obje türünün eşitliğini kontrol edecektir. +"vb" is None # => False +None is None # => True + +# None, 0, ve boş yazılar/listeler/sözlükler hepsi False değeri döndürü. +# Diğer veriler ise True değeri döndürür +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False + + +#################################################### +## 2. Değişkenler ve Koleksiyonlar +#################################################### + +# Python bir yazdırma fonksiyonuna sahip +print("Ben Python. Tanıştığıma memnun oldum!") + +# Değişkenlere veri atamak için önce değişkeni oluşturmanıza gerek yok. +# Düzenli bir değişken için hepsi_kucuk_ve_alt_cizgi_ile_ayirin +bir_degisken = 5 +bir_degisken # => 5 + +# Önceden tanımlanmamış değişkene erişmek hata oluşturacaktır. +# Kontrol akışları başlığından hata kontrolünü öğrenebilirsiniz. +bir_bilinmeyen_degisken # NameError hatası oluşturur + +# Listeler ile sıralamaları tutabilirsiniz +li = [] +# Önceden doldurulmuş listeler ile başlayabilirsiniz +diger_li = [4, 5, 6] + +# 'append' ile listenin sonuna ekleme yapabilirsiniz +li.append(1) # li artık [1] oldu +li.append(2) # li artık [1, 2] oldu +li.append(4) # li artık [1, 2, 4] oldu +li.append(3) # li artık [1, 2, 4, 3] oldu +# 'pop' ile listenin son elementini kaldırabilirsiniz +li.pop() # => 3 ve li artık [1, 2, 4] +# Çıkarttığımız tekrardan ekleyelim +li.append(3) # li yeniden [1, 2, 4, 3] oldu. + +# Dizi gibi listeye erişim sağlayın +li[0] # => 1 +# Son elemente bakın +li[-1] # => 3 + +# Listede olmayan bir elemente erişim sağlamaya çalışmak IndexError hatası oluşturur +li[4] # IndexError hatası oluşturur + +# Bir kısmını almak isterseniz. +li[1:3] # => [2, 4] +# Başlangıç belirtmezseniz +li[2:] # => [4, 3] +# Sonu belirtmesseniz +li[:3] # => [1, 2, 4] +# Her ikişer objeyi seçme +li[::2] # =>[1, 4] +# Listeyi tersten almak +li[::-1] # => [3, 4, 2, 1] +# Kombinasyonları kullanarak gelişmiş bir şekilde listenin bir kısmını alabilirsiniz +# li[baslangic:son:adim] + +# "del" ile isteğe bağlı, elementleri listeden kaldırabilirsiniz +del li[2] # li artık [1, 2, 3] oldu + +# Listelerde de ekleme yapabilirsiniz +# Not: değerler üzerinde değişiklik yapılmaz. +li + diger_li # => [1, 2, 3, 4, 5, 6] + +# Listeleri birbirine bağlamak için "extend()" kullanılabilir +li.extend(diger_li) # li artık [1, 2, 3, 4, 5, 6] oldu + +# Listedeki bir elementin olup olmadığı kontrolü "in" ile yapılabilir +1 in li # => True + +# Uzunluğu öğrenmek için "len()" kullanılabilir +len(li) # => 6 + + +# Tüpler listeler gibidir fakat değiştirilemez. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # TypeError hatası oluşturur + +# Diğer liste işlemlerini tüplerde de uygulayabilirsiniz +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Tüpleri(veya listeleri) değişkenlere açabilirsiniz +a, b, c = (1, 2, 3) # 'a' artık 1, 'b' artık 2 ve 'c' artık 3 +# Eğer parantez kullanmazsanız varsayılan oalrak tüpler oluşturulur +d, e, f = 4, 5, 6 +# 2 değeri birbirine değiştirmek bu kadar kolay +e, d = d, e # 'd' artık 5 ve 'e' artık 4 + + +# Sözlükler anahtar kodlarla verileri tutar +bos_sozl = {} +# Önceden doldurulmuş sözlük oluşturma +dolu_sozl = {"bir": 1, "iki": 2, "uc": 3} + +# Değere bakmak için [] kullanalım +dolu_sozl["bir"] # => 1 + +# Bütün anahtarları almak için "keys()" kullanılabilir. +# Listelemek için list() kullanacağınız çünkü dönen değerin işlenmesi gerekiyor. Bu konuya daha sonra değineceğiz. +# Not - Sözlük anahtarlarının sıralaması kesin değildir. +# Beklediğiniz çıktı sizinkiyle tam uyuşmuyor olabilir. +list(dolu_sozl.keys()) # => ["uc", "iki", "bir"] + + +# Tüm değerleri almak için "values()" kullanacağız. Dönen değeri biçimlendirmek için de list() kullanmamız gerekiyor +# Not - Sıralama değişebilir. +list(dolu_sozl.values()) # => [3, 2, 1] + + +# Bir anahtarın sözlükte olup olmadığını "in" ile kontrol edebilirsiniz +"bir" in dolu_sozl # => True +1 in dolu_sozl # => False + +# Olmayan bir anahtardan değer elde etmek isterseniz KeyError sorunu oluşacaktır. +dolu_sozl["dort"] # KeyError hatası oluşturur + +# "get()" metodu ile değeri almaya çalışırsanız KeyError sorunundan kurtulursunuz +dolu_sozl.get("bir") # => 1 +dolu_sozl.get("dort") # => None +# "get" metoduna parametre belirterek değerin olmaması durumunda varsayılan bir değer döndürebilirsiniz. +dolu_sozl.get("bir", 4) # => 1 +dolu_sozl.get("dort", 4) # => 4 + +# "setdefault()" metodu sözlükte, belirttiğiniz anahtarın [olmaması] durumunda varsayılan bir değer atayacaktır +dolu_sozl.setdefault("bes", 5) # dolu_sozl["bes"] artık 5 değerine sahip +dolu_sozl.setdefault("bes", 6) # dolu_sozl["bes"] değişmedi, hala 5 değerine sahip + +# Sözlüğe ekleme +dolu_sozl.update({"dort":4}) #=> {"bir": 1, "iki": 2, "uc": 3, "dort": 4} +#dolu_sozl["dort"] = 4 #sözlüğe eklemenin bir diğer yolu + +# Sözlükten anahtar silmek için 'del' kullanılabilir +del dolu_sozl["bir"] # "bir" anahtarını dolu sözlükten silecektir + + +# Setler ... set işte :D +bos_set = set() +# Seti bir veri listesi ile de oluşturabilirsiniz. Evet, biraz sözlük gibi duruyor. Üzgünüm. +bir_set = {1, 1, 2, 2, 3, 4} # bir_set artık {1, 2, 3, 4} + +# Sete yeni setler ekleyebilirsiniz +dolu_set = bir_set + +# Sete bir diğer öğe ekleme +dolu_set.add(5) # dolu_set artık {1, 2, 3, 4, 5} oldu + +# Setlerin çakışan kısımlarını almak için '&' kullanabilirsiniz +diger_set = {3, 4, 5, 6} +dolu_set & diger_set # => {3, 4, 5} + +# '|' ile aynı olan elementleri almayacak şekilde setleri birleştirebilirsiniz +dolu_set | diger_set # => {1, 2, 3, 4, 5, 6} + +# Farklılıkları almak için "-" kullanabilirsiniz +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Bir değerin olup olmadığının kontrolü için "in" kullanılabilir +2 in dolu_set # => True +10 in dolu_set # => False + + +#################################################### +## 3. Kontrol Akışları ve Temel Soyutlandırma +#################################################### + +# Bir değişken oluşturalım +bir_degisken = 5 + +# Burada bir "if" ifadesi var. Girinti(boşluk,tab) python için önemlidir! +# çıktı olarak "bir_degisken 10 dan küçük" yazar +if bir_degisken > 10: + print("bir_degisken 10 dan büyük") +elif bir_degisken < 10: # Bu 'elif' ifadesi zorunlu değildir. + print("bir_degisken 10 dan küçük") +else: # Bu ifade de zorunlu değil. + print("bir_degisken değeri 10") + + +""" +Döngülerle lsiteleri döngüye alabilirsiniz +çıktı: + köpek bir memeli hayvandır + kedi bir memeli hayvandır + fare bir memeli hayvandır +""" +for hayvan in ["köpek", "kedi, "fare"]: + # format ile kolayca yazıyı biçimlendirelim + print("{} bir memeli hayvandır".format(hayvan)) + +""" +"range(sayi)" bir sayı listesi döndür +0'dan belirttiğiniz sayıyıa kadar +çıktı: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +'While' döngüleri koşul çalıştıkça işlemleri gerçekleştirir. +çıktı: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Uzun hali x = x + 1 + +# Hataları kontrol altına almak için try/except bloklarını kullanabilirsiniz +try: + # Bir hata oluşturmak için "raise" kullanabilirsiniz + raise IndexError("Bu bir index hatası") +except IndexError as e: + pass # Önemsiz, devam et. +except (TypeError, NameError): + pass # Çoklu bir şekilde hataları kontrol edebilirsiniz, tabi gerekirse. +else: # İsteğe bağlı bir kısım. Eğer hiçbir hata kontrol mekanizması desteklemiyorsa bu blok çalışacaktır + print("Her şey iyi!") # IndexError, TypeError ve NameError harici bir hatada bu blok çalıştı + +# Temel Soyutlandırma, bir objenin işlenmiş halidir. +# Aşağıdaki örnekte; Obje, range fonksiyonuna temel soyutlandırma gönderdi. + +dolu_sozl = {"bir": 1, "iki": 2, "uc": 3} +temel_soyut = dolu_sozl.keys() +print(temel_soyut) #=> range(1,10). Bu obje temel soyutlandırma arayüzü ile oluşturuldu + +# Temel Soyutlandırılmış objeyi döngüye sokabiliriz. +for i in temel_soyut: + print(i) # Çıktısı: bir, iki, uc + +# Fakat, elementin anahtarına değerine. +temel_soyut[1] # TypeError hatası! + +# 'iterable' bir objenin nasıl temel soyutlandırıldığıdır. +iterator = iter(temel_soyut) + +# 'iterator' o obje üzerinde yaptığımız değişiklikleri hatırlayacaktır +# Bir sonraki objeyi almak için __next__ fonksiyonunu kullanabilirsiniz. +iterator.__next__() #=> "bir" + +# Bir önceki __next__ fonksiyonumuzu hatırlayıp bir sonraki kullanımda bu sefer ondan bir sonraki objeyi döndürecektir +iterator.__next__() #=> "iki" +iterator.__next__() #=> "uc" + +# Bütün nesneleri aldıktan sonra bir daha __next__ kullanımınızda, StopIterator hatası oluşturacaktır. +iterator.__next__() # StopIteration hatası + +# iterator'deki tüm nesneleri almak için list() kullanabilirsiniz. +list(dolu_sozl.keys()) #=> Returns ["bir", "iki", "uc"] + + +#################################################### +## 4. Fonksiyonlar +#################################################### + +# "def" ile yeni fonksiyonlar oluşturabilirsiniz +def topla(x, y): + print("x = {} ve y = {}".format(x, y)) + return x + y # Değer döndürmek için 'return' kullanmalısınız + +# Fonksiyonu parametleri ile çağırıyoruz +topla(5, 6) # => çıktı "x = 5 ve y = 6" ve değer olarak 11 döndürür + +# Bir diğer fonksiyon çağırma yöntemi de anahtar değerleri ile belirtmek +topla(y=6, x=5) # Anahtar değeri belirttiğiniz için parametre sıralaması önemsiz. + +# Sınırsız sayıda argüman da alabilirsiniz +def argumanlar(*argumanlar): + return argumanlar + +argumanlar(1, 2, 3) # => (1, 2, 3) + +# Parametrelerin anahtar değerlerini almak isterseniz +def anahtar_par(**anahtarlar): + return anahtar + +# Çalıştırdığımızda +anahtar_par(anah1="deg1", anah2="deg2") # => {"anah1": "deg1", "anah2": "deg2"} + + +# İsterseniz, bu ikisini birden kullanabilirsiniz +def tum_argumanlar(*argumanlar, **anahtarla): + print(argumanlar) + print(anahtarla) +""" +tum_argumanlar(1, 2, a=3, b=4) çıktı: + (1, 2) + {"a": 3, "b": 4} +""" + +# Fonksiyonu çağırırken de aynısını kullanabilirsiniz +argumanlar = (1, 2, 3, 4) +anahtarla = {"a": 3, "b": 4} +tum_argumanlar(*argumanlar) # = foo(1, 2, 3, 4) +tum_argumanlar(**anahtarla) # = foo(a=3, b=4) +tum_argumanlar(*argumanlar, **anahtarla) # = foo(1, 2, 3, 4, a=3, b=4) + + +# Fonksiyonlarda kullanacağımız bir değişken oluşturalım +x = 5 + +def belirleX(sayi): + # Fonksiyon içerisindeki x ile global tanımladığımız x aynı değil + x = sayi # => 43 + print (x) # => 43 + +def globalBelirleX(sayi): + global x + print (x) # => 5 + x = sayi # global olan x değişkeni artık 6 + print (x) # => 6 + +belirleX(43) +globalBelirleX(6) + + +# Sınıf fonksiyonları oluşturma +def toplama_olustur(x): + def topla(y): + return x + y + return topla + +ekle_10 = toplama_olustur(10) +ekle_10(3) # => 13 + +# Bilinmeyen fonksiyon +(lambda x: x > 2)(3) # => True + +# TODO - Fix for iterables +# Belirli sayıdan yükseğini alma fonksiyonu +map(ekle_10, [1, 2, 3]) # => [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Filtreleme işlemi için liste comprehensions da kullanabiliriz +[ekle_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. Sınıflar +#################################################### + + +# Sınıf oluşturmak için objeden alt sınıf oluşturacağız. +class Insan(object): + + # Sınıf değeri. Sınıfın tüm nesneleri tarafından kullanılabilir + tur = "H. sapiens" + + # Basit başlatıcı, Sınıf çağrıldığında tetiklenecektir. + # Dikkat edin, iki adet alt çizgi(_) bulunmakta. Bunlar + # python tarafından tanımlanan isimlerdir. + # Kendinize ait bir fonksiyon oluştururken __fonksiyon__ kullanmayınız! + def __init__(self, isim): + # Parametreyi sınıfın değerine atayalım + self.isim = isim + + # Bir metot. Bütün metotlar ilk parametre olarak "self "alır. + def soyle(self, mesaj): + return "{isim}: {mesaj}".format(isim=self.isim, mesaj=mesaj) + + # Bir sınıf metotu bütün nesnelere paylaştırılır + # İlk parametre olarak sınıf alırlar + @classmethod + def getir_tur(snf): + return snf.tur + + # Bir statik metot, sınıf ve nesnesiz çağrılır + @staticmethod + def grunt(): + return "*grunt*" + + +# Sınıfı çağıralım +i = Insan(isim="Ahmet") +print(i.soyle("merhaba")) # çıktı "Ahmet: merhaba" + +j = Insan("Ali") +print(j.soyle("selam")) # çıktı "Ali: selam" + +# Sınıf metodumuzu çağıraim +i.getir_tur() # => "H. sapiens" + +# Paylaşılan değeri değiştirelim +Insan.tur = "H. neanderthalensis" +i.getir_tur() # => "H. neanderthalensis" +j.getir_tur() # => "H. neanderthalensis" + +# Statik metodumuzu çağıralım +Insan.grunt() # => "*grunt*" + + +#################################################### +## 6. Moduller +#################################################### + +# Modülleri içe aktarabilirsiniz +import math +print(math.sqrt(16)) # => 4.0 + +# Modülden belirli bir fonksiyonları alabilirsiniz +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Modüldeki tüm fonksiyonları içe aktarabilirsiniz +# Dikkat: bunu yapmanızı önermem. +from math import * + +# Modül isimlerini değiştirebilirsiniz. +# Not: Modül ismini kısaltmanız çok daha iyi olacaktır +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Python modulleri aslında birer python dosyalarıdır. +# İsterseniz siz de yazabilir ve içe aktarabilirsiniz Modulün +# ismi ile dosyanın ismi aynı olacaktır. + +# Moduldeki fonksiyon ve değerleri öğrenebilirsiniz. +import math +dir(math) + + +#################################################### +## 7. Gelişmiş +#################################################### + +# Oluşturucular uzun uzun kod yazmamanızı sağlayacak ve yardımcı olacaktır +def kare_sayilar(nesne): + for i in nesne: + yield i + i + +# Bir oluşturucu(generator) değerleri anında oluşturur. +# Bir seferde tüm değerleri oluşturup göndermek yerine teker teker her oluşumdan +# sonra geri döndürür. Bu demektir ki, kare_sayilar fonksiyonumuzda 15'ten büyük +# değerler işlenmeyecektir. +# Not: range() da bir oluşturucu(generator)dur. 1-900000000 arası bir liste yapmaya çalıştığınızda +# çok fazla vakit alacaktır. +# Python tarafından belirlenen anahtar kelimelerden kaçınmak için basitçe alt çizgi(_) kullanılabilir. +range_ = range(1, 900000000) +# kare_sayilar'dan dönen değer 30'a ulaştığında durduralım +for i in kare_sayilar(range_): + print(i) + if i >= 30: + break + + +# Dekoratörler +# Bu örnekte, +# Eğer lutfen_soyle True ise dönen değer değişecektir. +from functools import wraps + + +def yalvar(hedef_fonksiyon): + @wraps(hedef_fonksiyon) + def metot(*args, **kwargs): + msj, lutfen_soyle = hedef_fonksiyon(*args, **kwargs) + if lutfen_soyle: + return "{} {}".format(msj, "Lütfen! Artık dayanamıyorum :(") + return msj + + return metot + + +@yalvar +def soyle(lutfen_soyle=False): + msj = "Bana soda alır mısın?" + return msj, lutfen_soyle + + +print(soyle()) # Bana soda alır mısın? +print(soyle(lutfen_soyle=True)) # Ban soda alır mısın? Lutfen! Artık dayanamıyorum :( +``` + +## Daha Fazlasına Hazır Mısınız? + +### Ücretsiz Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) + +### Kitaplar + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown deleted file mode 100644 index b78d517f..00000000 --- a/tr-tr/python3-tr.html.markdown +++ /dev/null @@ -1,640 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Batuhan Osman T.", "https://github.com/BTaskaya"] -translators: - - ["Eray AYDIN", "http://erayaydin.me/"] -lang: tr-tr -filename: learnpython3-tr.py ---- - -Python,90ların başlarında Guido Van Rossum tarafından oluşturulmuştur. En popüler olan dillerden biridir. Beni Python'a aşık eden sebep onun syntax beraklığı. Çok basit bir çalıştırılabilir söz koddur. - -Not: Bu makale Python 3 içindir. Eğer Python 2.7 öğrenmek istiyorsanız [burayı](http://learnxinyminutes.com/docs/python/) kontrol edebilirsiniz. - -```python - -# Tek satırlık yorum satırı kare(#) işareti ile başlamaktadır. - -""" Çok satırlı olmasını istediğiniz yorumlar - üç adet tırnak(") işareti ile - yapılmaktadır -""" - -#################################################### -## 1. Temel Veri Türleri ve Operatörler -#################################################### - -# Sayılar -3 # => 3 - -# Tahmin edebileceğiniz gibi matematik -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 - -# Bölme işlemi varsayılan olarak onluk döndürür -35 / 5 # => 7.0 - -# Tam sayı bölmeleri, pozitif ve negatif sayılar için aşağıya yuvarlar -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # onluklar için de bu böyledir --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Onluk kullanırsanız, sonuç da onluk olur -3 * 2.0 # => 6.0 - -# Kalan operatörü -7 % 3 # => 1 - -# Üs (2 üzeri 4) -2**4 # => 16 - -# Parantez ile önceliği değiştirebilirsiniz -(1 + 3) * 2 # => 8 - -# Boolean(Doğru-Yanlış) değerleri standart -True -False - -# 'değil' ile terse çevirme -not True # => False -not False # => True - -# Boolean Operatörleri -# "and" ve "or" büyük küçük harf duyarlıdır -True and False #=> False -False or True #=> True - -# Bool operatörleri ile sayı kullanımı -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -1 == True #=> True - -# Eşitlik kontrolü == -1 == 1 # => True -2 == 1 # => False - -# Eşitsizlik Kontrolü != -1 != 1 # => False -2 != 1 # => True - -# Diğer karşılaştırmalar -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# Zincirleme şeklinde karşılaştırma da yapabilirsiniz! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# Yazı(Strings) " veya ' işaretleri ile oluşturulabilir -"Bu bir yazı." -'Bu da bir yazı.' - -# Yazılar da eklenebilir! Fakat bunu yapmanızı önermem. -"Merhaba " + "dünya!" # => "Merhaba dünya!" - -# Bir yazı(string) karakter listesi gibi işlenebilir -"Bu bir yazı"[0] # => 'B' - -# .format ile yazıyı biçimlendirebilirsiniz, şu şekilde: -"{} da ayrıca {}".format("yazılar", "işlenebilir") - -# Biçimlendirme işleminde aynı argümanı da birden fazla kullanabilirsiniz. -"{0} çeviktir, {0} hızlıdır, {0} , {1} üzerinden atlayabilir".format("Ahmet", "şeker çubuğu") -#=> "Ahmet çeviktir, Ahmet hızlıdır, Ahmet , şeker çubuğu üzerinden atlayabilir" - -# Argümanın sırasını saymak istemiyorsanız, anahtar kelime kullanabilirsiniz. -"{isim} yemek olarak {yemek} istiyor".format(isim="Ahmet", yemek="patates") #=> "Ahmet yemek olarak patates istiyor" - -# Eğer Python 3 kodunuz ayrıca Python 2.5 ve üstünde çalışmasını istiyorsanız, -# eski stil formatlamayı kullanabilirsiniz: -"%s bu %s yolla da %s" % ("yazılar", "eski", "biçimlendirilebilir") - - -# Hiçbir şey(none) da bir objedir -None # => None - -# Bir değerin none ile eşitlik kontrolü için "==" sembolünü kullanmayın -# Bunun yerine "is" kullanın. Obje türünün eşitliğini kontrol edecektir. -"vb" is None # => False -None is None # => True - -# None, 0, ve boş yazılar/listeler/sözlükler hepsi False değeri döndürü. -# Diğer veriler ise True değeri döndürür -bool(0) # => False -bool("") # => False -bool([]) #=> False -bool({}) #=> False - - -#################################################### -## 2. Değişkenler ve Koleksiyonlar -#################################################### - -# Python bir yazdırma fonksiyonuna sahip -print("Ben Python. Tanıştığıma memnun oldum!") - -# Değişkenlere veri atamak için önce değişkeni oluşturmanıza gerek yok. -# Düzenli bir değişken için hepsi_kucuk_ve_alt_cizgi_ile_ayirin -bir_degisken = 5 -bir_degisken # => 5 - -# Önceden tanımlanmamış değişkene erişmek hata oluşturacaktır. -# Kontrol akışları başlığından hata kontrolünü öğrenebilirsiniz. -bir_bilinmeyen_degisken # NameError hatası oluşturur - -# Listeler ile sıralamaları tutabilirsiniz -li = [] -# Önceden doldurulmuş listeler ile başlayabilirsiniz -diger_li = [4, 5, 6] - -# 'append' ile listenin sonuna ekleme yapabilirsiniz -li.append(1) # li artık [1] oldu -li.append(2) # li artık [1, 2] oldu -li.append(4) # li artık [1, 2, 4] oldu -li.append(3) # li artık [1, 2, 4, 3] oldu -# 'pop' ile listenin son elementini kaldırabilirsiniz -li.pop() # => 3 ve li artık [1, 2, 4] -# Çıkarttığımız tekrardan ekleyelim -li.append(3) # li yeniden [1, 2, 4, 3] oldu. - -# Dizi gibi listeye erişim sağlayın -li[0] # => 1 -# Son elemente bakın -li[-1] # => 3 - -# Listede olmayan bir elemente erişim sağlamaya çalışmak IndexError hatası oluşturur -li[4] # IndexError hatası oluşturur - -# Bir kısmını almak isterseniz. -li[1:3] # => [2, 4] -# Başlangıç belirtmezseniz -li[2:] # => [4, 3] -# Sonu belirtmesseniz -li[:3] # => [1, 2, 4] -# Her ikişer objeyi seçme -li[::2] # =>[1, 4] -# Listeyi tersten almak -li[::-1] # => [3, 4, 2, 1] -# Kombinasyonları kullanarak gelişmiş bir şekilde listenin bir kısmını alabilirsiniz -# li[baslangic:son:adim] - -# "del" ile isteğe bağlı, elementleri listeden kaldırabilirsiniz -del li[2] # li artık [1, 2, 3] oldu - -# Listelerde de ekleme yapabilirsiniz -# Not: değerler üzerinde değişiklik yapılmaz. -li + diger_li # => [1, 2, 3, 4, 5, 6] - -# Listeleri birbirine bağlamak için "extend()" kullanılabilir -li.extend(diger_li) # li artık [1, 2, 3, 4, 5, 6] oldu - -# Listedeki bir elementin olup olmadığı kontrolü "in" ile yapılabilir -1 in li # => True - -# Uzunluğu öğrenmek için "len()" kullanılabilir -len(li) # => 6 - - -# Tüpler listeler gibidir fakat değiştirilemez. -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # TypeError hatası oluşturur - -# Diğer liste işlemlerini tüplerde de uygulayabilirsiniz -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# Tüpleri(veya listeleri) değişkenlere açabilirsiniz -a, b, c = (1, 2, 3) # 'a' artık 1, 'b' artık 2 ve 'c' artık 3 -# Eğer parantez kullanmazsanız varsayılan oalrak tüpler oluşturulur -d, e, f = 4, 5, 6 -# 2 değeri birbirine değiştirmek bu kadar kolay -e, d = d, e # 'd' artık 5 ve 'e' artık 4 - - -# Sözlükler anahtar kodlarla verileri tutar -bos_sozl = {} -# Önceden doldurulmuş sözlük oluşturma -dolu_sozl = {"bir": 1, "iki": 2, "uc": 3} - -# Değere bakmak için [] kullanalım -dolu_sozl["bir"] # => 1 - -# Bütün anahtarları almak için "keys()" kullanılabilir. -# Listelemek için list() kullanacağınız çünkü dönen değerin işlenmesi gerekiyor. Bu konuya daha sonra değineceğiz. -# Not - Sözlük anahtarlarının sıralaması kesin değildir. -# Beklediğiniz çıktı sizinkiyle tam uyuşmuyor olabilir. -list(dolu_sozl.keys()) # => ["uc", "iki", "bir"] - - -# Tüm değerleri almak için "values()" kullanacağız. Dönen değeri biçimlendirmek için de list() kullanmamız gerekiyor -# Not - Sıralama değişebilir. -list(dolu_sozl.values()) # => [3, 2, 1] - - -# Bir anahtarın sözlükte olup olmadığını "in" ile kontrol edebilirsiniz -"bir" in dolu_sozl # => True -1 in dolu_sozl # => False - -# Olmayan bir anahtardan değer elde etmek isterseniz KeyError sorunu oluşacaktır. -dolu_sozl["dort"] # KeyError hatası oluşturur - -# "get()" metodu ile değeri almaya çalışırsanız KeyError sorunundan kurtulursunuz -dolu_sozl.get("bir") # => 1 -dolu_sozl.get("dort") # => None -# "get" metoduna parametre belirterek değerin olmaması durumunda varsayılan bir değer döndürebilirsiniz. -dolu_sozl.get("bir", 4) # => 1 -dolu_sozl.get("dort", 4) # => 4 - -# "setdefault()" metodu sözlükte, belirttiğiniz anahtarın [olmaması] durumunda varsayılan bir değer atayacaktır -dolu_sozl.setdefault("bes", 5) # dolu_sozl["bes"] artık 5 değerine sahip -dolu_sozl.setdefault("bes", 6) # dolu_sozl["bes"] değişmedi, hala 5 değerine sahip - -# Sözlüğe ekleme -dolu_sozl.update({"dort":4}) #=> {"bir": 1, "iki": 2, "uc": 3, "dort": 4} -#dolu_sozl["dort"] = 4 #sözlüğe eklemenin bir diğer yolu - -# Sözlükten anahtar silmek için 'del' kullanılabilir -del dolu_sozl["bir"] # "bir" anahtarını dolu sözlükten silecektir - - -# Setler ... set işte :D -bos_set = set() -# Seti bir veri listesi ile de oluşturabilirsiniz. Evet, biraz sözlük gibi duruyor. Üzgünüm. -bir_set = {1, 1, 2, 2, 3, 4} # bir_set artık {1, 2, 3, 4} - -# Sete yeni setler ekleyebilirsiniz -dolu_set = bir_set - -# Sete bir diğer öğe ekleme -dolu_set.add(5) # dolu_set artık {1, 2, 3, 4, 5} oldu - -# Setlerin çakışan kısımlarını almak için '&' kullanabilirsiniz -diger_set = {3, 4, 5, 6} -dolu_set & diger_set # => {3, 4, 5} - -# '|' ile aynı olan elementleri almayacak şekilde setleri birleştirebilirsiniz -dolu_set | diger_set # => {1, 2, 3, 4, 5, 6} - -# Farklılıkları almak için "-" kullanabilirsiniz -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Bir değerin olup olmadığının kontrolü için "in" kullanılabilir -2 in dolu_set # => True -10 in dolu_set # => False - - -#################################################### -## 3. Kontrol Akışları ve Temel Soyutlandırma -#################################################### - -# Bir değişken oluşturalım -bir_degisken = 5 - -# Burada bir "if" ifadesi var. Girinti(boşluk,tab) python için önemlidir! -# çıktı olarak "bir_degisken 10 dan küçük" yazar -if bir_degisken > 10: - print("bir_degisken 10 dan büyük") -elif bir_degisken < 10: # Bu 'elif' ifadesi zorunlu değildir. - print("bir_degisken 10 dan küçük") -else: # Bu ifade de zorunlu değil. - print("bir_degisken değeri 10") - - -""" -Döngülerle lsiteleri döngüye alabilirsiniz -çıktı: - köpek bir memeli hayvandır - kedi bir memeli hayvandır - fare bir memeli hayvandır -""" -for hayvan in ["köpek", "kedi, "fare"]: - # format ile kolayca yazıyı biçimlendirelim - print("{} bir memeli hayvandır".format(hayvan)) - -""" -"range(sayi)" bir sayı listesi döndür -0'dan belirttiğiniz sayıyıa kadar -çıktı: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -'While' döngüleri koşul çalıştıkça işlemleri gerçekleştirir. -çıktı: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Uzun hali x = x + 1 - -# Hataları kontrol altına almak için try/except bloklarını kullanabilirsiniz -try: - # Bir hata oluşturmak için "raise" kullanabilirsiniz - raise IndexError("Bu bir index hatası") -except IndexError as e: - pass # Önemsiz, devam et. -except (TypeError, NameError): - pass # Çoklu bir şekilde hataları kontrol edebilirsiniz, tabi gerekirse. -else: # İsteğe bağlı bir kısım. Eğer hiçbir hata kontrol mekanizması desteklemiyorsa bu blok çalışacaktır - print("Her şey iyi!") # IndexError, TypeError ve NameError harici bir hatada bu blok çalıştı - -# Temel Soyutlandırma, bir objenin işlenmiş halidir. -# Aşağıdaki örnekte; Obje, range fonksiyonuna temel soyutlandırma gönderdi. - -dolu_sozl = {"bir": 1, "iki": 2, "uc": 3} -temel_soyut = dolu_sozl.keys() -print(temel_soyut) #=> range(1,10). Bu obje temel soyutlandırma arayüzü ile oluşturuldu - -# Temel Soyutlandırılmış objeyi döngüye sokabiliriz. -for i in temel_soyut: - print(i) # Çıktısı: bir, iki, uc - -# Fakat, elementin anahtarına değerine. -temel_soyut[1] # TypeError hatası! - -# 'iterable' bir objenin nasıl temel soyutlandırıldığıdır. -iterator = iter(temel_soyut) - -# 'iterator' o obje üzerinde yaptığımız değişiklikleri hatırlayacaktır -# Bir sonraki objeyi almak için __next__ fonksiyonunu kullanabilirsiniz. -iterator.__next__() #=> "bir" - -# Bir önceki __next__ fonksiyonumuzu hatırlayıp bir sonraki kullanımda bu sefer ondan bir sonraki objeyi döndürecektir -iterator.__next__() #=> "iki" -iterator.__next__() #=> "uc" - -# Bütün nesneleri aldıktan sonra bir daha __next__ kullanımınızda, StopIterator hatası oluşturacaktır. -iterator.__next__() # StopIteration hatası - -# iterator'deki tüm nesneleri almak için list() kullanabilirsiniz. -list(dolu_sozl.keys()) #=> Returns ["bir", "iki", "uc"] - - -#################################################### -## 4. Fonksiyonlar -#################################################### - -# "def" ile yeni fonksiyonlar oluşturabilirsiniz -def topla(x, y): - print("x = {} ve y = {}".format(x, y)) - return x + y # Değer döndürmek için 'return' kullanmalısınız - -# Fonksiyonu parametleri ile çağırıyoruz -topla(5, 6) # => çıktı "x = 5 ve y = 6" ve değer olarak 11 döndürür - -# Bir diğer fonksiyon çağırma yöntemi de anahtar değerleri ile belirtmek -topla(y=6, x=5) # Anahtar değeri belirttiğiniz için parametre sıralaması önemsiz. - -# Sınırsız sayıda argüman da alabilirsiniz -def argumanlar(*argumanlar): - return argumanlar - -argumanlar(1, 2, 3) # => (1, 2, 3) - -# Parametrelerin anahtar değerlerini almak isterseniz -def anahtar_par(**anahtarlar): - return anahtar - -# Çalıştırdığımızda -anahtar_par(anah1="deg1", anah2="deg2") # => {"anah1": "deg1", "anah2": "deg2"} - - -# İsterseniz, bu ikisini birden kullanabilirsiniz -def tum_argumanlar(*argumanlar, **anahtarla): - print(argumanlar) - print(anahtarla) -""" -tum_argumanlar(1, 2, a=3, b=4) çıktı: - (1, 2) - {"a": 3, "b": 4} -""" - -# Fonksiyonu çağırırken de aynısını kullanabilirsiniz -argumanlar = (1, 2, 3, 4) -anahtarla = {"a": 3, "b": 4} -tum_argumanlar(*argumanlar) # = foo(1, 2, 3, 4) -tum_argumanlar(**anahtarla) # = foo(a=3, b=4) -tum_argumanlar(*argumanlar, **anahtarla) # = foo(1, 2, 3, 4, a=3, b=4) - - -# Fonksiyonlarda kullanacağımız bir değişken oluşturalım -x = 5 - -def belirleX(sayi): - # Fonksiyon içerisindeki x ile global tanımladığımız x aynı değil - x = sayi # => 43 - print (x) # => 43 - -def globalBelirleX(sayi): - global x - print (x) # => 5 - x = sayi # global olan x değişkeni artık 6 - print (x) # => 6 - -belirleX(43) -globalBelirleX(6) - - -# Sınıf fonksiyonları oluşturma -def toplama_olustur(x): - def topla(y): - return x + y - return topla - -ekle_10 = toplama_olustur(10) -ekle_10(3) # => 13 - -# Bilinmeyen fonksiyon -(lambda x: x > 2)(3) # => True - -# TODO - Fix for iterables -# Belirli sayıdan yükseğini alma fonksiyonu -map(ekle_10, [1, 2, 3]) # => [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] - -# Filtreleme işlemi için liste comprehensions da kullanabiliriz -[ekle_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -#################################################### -## 5. Sınıflar -#################################################### - - -# Sınıf oluşturmak için objeden alt sınıf oluşturacağız. -class Insan(object): - - # Sınıf değeri. Sınıfın tüm nesneleri tarafından kullanılabilir - tur = "H. sapiens" - - # Basit başlatıcı, Sınıf çağrıldığında tetiklenecektir. - # Dikkat edin, iki adet alt çizgi(_) bulunmakta. Bunlar - # python tarafından tanımlanan isimlerdir. - # Kendinize ait bir fonksiyon oluştururken __fonksiyon__ kullanmayınız! - def __init__(self, isim): - # Parametreyi sınıfın değerine atayalım - self.isim = isim - - # Bir metot. Bütün metotlar ilk parametre olarak "self "alır. - def soyle(self, mesaj): - return "{isim}: {mesaj}".format(isim=self.isim, mesaj=mesaj) - - # Bir sınıf metotu bütün nesnelere paylaştırılır - # İlk parametre olarak sınıf alırlar - @classmethod - def getir_tur(snf): - return snf.tur - - # Bir statik metot, sınıf ve nesnesiz çağrılır - @staticmethod - def grunt(): - return "*grunt*" - - -# Sınıfı çağıralım -i = Insan(isim="Ahmet") -print(i.soyle("merhaba")) # çıktı "Ahmet: merhaba" - -j = Insan("Ali") -print(j.soyle("selam")) # çıktı "Ali: selam" - -# Sınıf metodumuzu çağıraim -i.getir_tur() # => "H. sapiens" - -# Paylaşılan değeri değiştirelim -Insan.tur = "H. neanderthalensis" -i.getir_tur() # => "H. neanderthalensis" -j.getir_tur() # => "H. neanderthalensis" - -# Statik metodumuzu çağıralım -Insan.grunt() # => "*grunt*" - - -#################################################### -## 6. Moduller -#################################################### - -# Modülleri içe aktarabilirsiniz -import math -print(math.sqrt(16)) # => 4.0 - -# Modülden belirli bir fonksiyonları alabilirsiniz -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# Modüldeki tüm fonksiyonları içe aktarabilirsiniz -# Dikkat: bunu yapmanızı önermem. -from math import * - -# Modül isimlerini değiştirebilirsiniz. -# Not: Modül ismini kısaltmanız çok daha iyi olacaktır -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Python modulleri aslında birer python dosyalarıdır. -# İsterseniz siz de yazabilir ve içe aktarabilirsiniz Modulün -# ismi ile dosyanın ismi aynı olacaktır. - -# Moduldeki fonksiyon ve değerleri öğrenebilirsiniz. -import math -dir(math) - - -#################################################### -## 7. Gelişmiş -#################################################### - -# Oluşturucular uzun uzun kod yazmamanızı sağlayacak ve yardımcı olacaktır -def kare_sayilar(nesne): - for i in nesne: - yield i + i - -# Bir oluşturucu(generator) değerleri anında oluşturur. -# Bir seferde tüm değerleri oluşturup göndermek yerine teker teker her oluşumdan -# sonra geri döndürür. Bu demektir ki, kare_sayilar fonksiyonumuzda 15'ten büyük -# değerler işlenmeyecektir. -# Not: range() da bir oluşturucu(generator)dur. 1-900000000 arası bir liste yapmaya çalıştığınızda -# çok fazla vakit alacaktır. -# Python tarafından belirlenen anahtar kelimelerden kaçınmak için basitçe alt çizgi(_) kullanılabilir. -range_ = range(1, 900000000) -# kare_sayilar'dan dönen değer 30'a ulaştığında durduralım -for i in kare_sayilar(range_): - print(i) - if i >= 30: - break - - -# Dekoratörler -# Bu örnekte, -# Eğer lutfen_soyle True ise dönen değer değişecektir. -from functools import wraps - - -def yalvar(hedef_fonksiyon): - @wraps(hedef_fonksiyon) - def metot(*args, **kwargs): - msj, lutfen_soyle = hedef_fonksiyon(*args, **kwargs) - if lutfen_soyle: - return "{} {}".format(msj, "Lütfen! Artık dayanamıyorum :(") - return msj - - return metot - - -@yalvar -def soyle(lutfen_soyle=False): - msj = "Bana soda alır mısın?" - return msj, lutfen_soyle - - -print(soyle()) # Bana soda alır mısın? -print(soyle(lutfen_soyle=True)) # Ban soda alır mısın? Lutfen! Artık dayanamıyorum :( -``` - -## Daha Fazlasına Hazır Mısınız? - -### Ücretsiz Online - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) -* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) -* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) -* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) -* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) - -### Kitaplar - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) - diff --git a/vi-vn/python-vi.html.markdown b/vi-vn/python-vi.html.markdown new file mode 100644 index 00000000..f6cce1a3 --- /dev/null +++ b/vi-vn/python-vi.html.markdown @@ -0,0 +1,914 @@ +--- +language: python3 +filename: learnpython3-vi.py +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["evuez", "http://github.com/evuez"] +translators: + - ["Xuan (Sean) Luong, https://github.com/xuanluong"] +lang: vi-vn + +--- + +Python được tạo ra bởi Guido van Rossum vào đầu những năm 90s. Ngày nay nó là một trong những ngôn ngữ phổ biến +nhất còn tồn tại. Tôi thích Python vì sự rõ ràng, trong sáng về mặt cú pháp. Về cơ bản, Python có thể coi +như một loại mã giả (pseudocode) có thể thực thi được. + +Mọi phản hồi đều sẽ được tích cực ghi nhận! Bạn có thể liên lạc với tôi qua Twitter [@louiedinh](http://twitter.com/louiedinh) hoặc louiedinh [at] [google's email service] + +Lưu ý: Bài viết này áp dụng riêng cho Python 3. Truy cập [vào đây](http://learnxinyminutes.com/docs/python/) nếu bạn muốn học phiên bản cũ Python 2.7 + +```python + +# Dòng bình luận (comment) bắt đầu bằng dấu thăng (#) + +""" Những chuỗi ký tự (string) nằm trên nhiều dòng + có thể được viết bằng cách dùng 3 dấu nháy " và thường + được dùng trong quá trình viết tài liệu (documentation). +""" + +#################################################### +## 1. Các kiểu dữ liệu cơ bản và Các phép toán +#################################################### + +# Bạn có những con số +3 # => 3 + +# Tính toán với những con số là những điều có thể bạn sẽ làm +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 + +# Kết quả của phép chia số nguyên sẽ được làm tròn xuống cho cả số dương và số âm +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # phép chia số nguyên cũng áp dụng được cho kiểu dữ liệu float biểu diễn số thực +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Kết quả của phép chia luôn là số thực +10.0 / 3 # => 3.3333333333333335 + +# Phép toán lấy phần dư (modulo) +7 % 3 # => 1 + +# Phép lũy thừa (x**y, x lũy thừa y) +2**3 # => 8 + +# Áp đặt thứ tự tính toán bằng dấu ngoặc +(1 + 3) * 2 # => 8 + +# Kiểu Boolean cũng là một kiểu dữ liệu cơ bản (Lưu ý: ký tự đầu tiên viết hoa) +True +False + +# Phủ định bằng từ khóa 'not' +not True # => False +not False # => True + +# Các phép toán với kiểu Boolean +# Lưu ý từ khóa "and" và "or" là case-sensitive +True and False # => False +False or True # => True + +# Lưu ý khi sử dụng các phép toán của kiểu Boolean với số nguyên 'int' +# False là 0 và True là 1 +# Đừng nhầm lẫn các phép toán Boolean cho số nguyên và các phép toán and/or trên bit (& và |) +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True +-5 != False != True #=> True + +# So sánh bằng với == +1 == 1 # => True +2 == 1 # => False + +# So sánh không bằng với != +1 != 1 # => False +2 != 1 # => True + +# Các phép so sánh khác +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Các phép so sánh có thể xâu chuỗi với nhau! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (is vs. ==) từ khóa is kiểm tra xem 2 biến có cùng tham chiếu một đối tượng, còn == kiếm tra +# xem hai đối tượng có cùng giá trị hay không. +a = [1, 2, 3, 4] # a trỏ tới một danh sách (list) mới, [1, 2, 3, 4] +b = a # b trỏ tới nơi mà a cũng đang trỏ tới +b is a # => True, a và b cùng trỏ tới một đối tượng +b == a # => True, đối tượng mà a và b trỏ tới có cùng giá trị +b = [1, 2, 3, 4] # b trỏ tới một danh sách mới, [1, 2, 3, 4] +b is a # => False, a và b không cùng trỏ tới một đối tượng +b == a # => True, đối tượng mà a và b trỏ tới không có cùng giá trị + +# Chuỗi ký tự được tạo ra bằng dấu nháy kép " hoặc nháy đơn ' +"Đây là một chuỗi ký tự." +'Đây cũng là một chuỗi ký tự.' + +# Chuỗi ký tự có thể được cộng với nhau can be added too! Tuy nhiên nên tránh làm như vậy +"Xin " + "chào!" # => "Xin chào!" +# Các chuỗi ký tự không phải là biến (literals) có thể được nối với nhau mà không cần dùng phép cộng '+' +"Xin " "chào!" # => "Xin chào!" + +# Một chuỗi ký tự có thể xem như một danh sách (list) các ký tự +"Đây là một chuỗi ký tự"[0] # => 'Đ' + +# Bạn có thể tìm chiều dài một chuỗi +len("Đây là một chuỗi") # => 16 + +# .format có thể được dùng để định dạng chuỗi, ví dụ như: +"{} có thể được {}".format("Chuỗi ký tự", "định dạng") # => "Chuỗi ký tự có thể được định dạng" + +# Bạn có thể lặp lại đối số (arguments) khi định dạnh để không phải gõ nhiều lần +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# Bạn có thể dùng từ khóa nếu bạn không muốn đếm +"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" + +# Nếu code Python 3 của bạn cần phải chạy với Python 2.5 hoặc các bản cũ hơn, bạn cũng có thể +# dùng cách định dạng cũ: +"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" + + +# None là một đối tượng +None # => None + +# Đừng dùng so sánh bằng "==" để so sánh đối tượng với None +# Thay vào đó dùng is. Nó sẽ kiểm tra xem một đối tượng có đồng nhất với None hay không. +"etc" is None # => False +None is None # => True + +# None, 0, và chuỗi/danh sách (list)/từ điển (dict)/tuple rỗng khi chuyển về kiểu Boolean đều có giá trị là False. +# Tất cả những giá trị khác đều là True +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False +bool(()) # => False + +#################################################### +## 2. Biến và Các kiểu dữ liệu gộp (Collections) +#################################################### + +# Hàm print trong Python +print("Tôi là Python. Rất hân hạnh được làm quen!") # => Tôi là Python. Rất hân hạnh được làm quen! + +# Hàm print mặc định in thêm ký tự xuống dòng +# Dùng đối số tùy chọn (optional argument) để thay đổi cách kết thúc chuỗi. +print("Hello, World", end="!") # => Hello, World! + +# Một cách đơn giản để lấy dữ liệu vào từ bàn phím +input_string_var = input("Nhập dữ liệu: ") # Trả về dữ liệu vào là một chuỗi +# Lưu ý: Trong những phiên bản cũ của Python input() có tên là raw_input() + +# Không cần phải khai báo biến mà chỉ có gán giá trị cho biến. +# Quy ước là sử dụng chữ_viết_thường_có_dấu_gạch_dưới +some_var = 5 +some_var # => 5 + +# Truy cập một biến chưa được gán trước đó sẽ tạo ra biệt lệ (exception). +# Đọc mục Luồng điều khiển để hiểu thêm về việc giải quyết các biệt lệ (exception handling) +some_unknown_var # Sinh ra một biệt lệ kiểu NameError + +# if có thể dùng như một biểu thức +# Tương đương với phép toán ba ngôi trong C: '?:' +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Kiểu danh sách (list) lưu trữ chuỗi đối tượng tuần tự +li = [] +# Bạn có thể bắt đầu với một danh sách đã có sãn các phần tử +other_li = [4, 5, 6] + +# Thêm phần tử vào cuối danh sách bằng phương thức append +li.append(1) # li bây giờ là [1] +li.append(2) # li bây giờ là [1, 2] +li.append(4) # li bây giờ là [1, 2, 4] +li.append(3) # li bây giờ là [1, 2, 4, 3] +# Xóa phần tử cuối cùng bằng phương thức pop +li.pop() # => 3 and li is now [1, 2, 4] +# Sau đó ta có thể đưa đối tượng trở lại danh sách +li.append(3) # li trở lại là [1, 2, 4, 3]. + +# Truy cập một danh sách như bạn làm với một mảng (array) +li[0] # => 1 +# Truy cập phần tử cuối cùng +li[-1] # => 3 + +# Truy cập ngoài giới hạn sẽ tạo ra biệt lệ IndexError +li[4] # Sinh ra một biệt lệ kiểu IndexError + +# Bạn có thể truy cập một đoạn bằng phép cắt (slice). +# Chỉ mục bắt đầu được tính làm điểm bắt đầu còn chỉ mục kết thúc thì không, mà là chỉ mục của phần tử tiếp theo phần tử kết thúc +# (Về mặt toán học thì đây là một đoạn đóng/mở, hay nửa đoạn) +li[1:3] # => [2, 4] +# Lấy từ vị trí thứ 3 đến hết +li[2:] # => [4, 3] +# Lấy từ đầu đến vị trí thứ 3 +li[:3] # => [1, 2, 4] +# Lấy những phần tử có chỉ mục chẵn +li[::2] # =>[1, 4] +# Trả về bản sao của danh sách bị đảo ngược +li[::-1] # => [3, 4, 2, 1] +# Kết hợp 3 tham số để làm những phép cắt phức tạp hơn +# li[start:end:step] + +# Tạo ra một bản sao sâu (deep copy) bằng phép cắt +li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. + +# Xóa phần tử nào đó của danh sách bằng "del" +del li[2] # li is now [1, 2, 3] + +# Xóa đi phần tử đầu tiên mang một giá trị nhất định +li.remove(2) # li bây giờ là [1, 3] +li.remove(2) # Sinh ra biệt lệ kiểu ValueError vì 2 không tồn tại trong danh sách + +# Chèn một phần tử vào một vị trí cụ thể +li.insert(1, 2) # li bây giờ lại là [1, 2, 3] + +# Tìm chỉ mục của của phần tử đầu tiên mang một giá trị nhất định +li.index(2) # => 1 +li.index(4) # Sinh ra biệt lệ a ValueError as 4 is not in the list + +# Bạn có thể cộng dồn các danh sách +# Lưu ý: giá trị của li và other_li không đổi +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Nối danh sách bằng "extend()" +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] + +# Kiểm tra sự tồn tại của một phần tử trong danh sách bằng "in" +1 in li # => True + +# Xác định độ dài bằng "len()" +len(li) # => 6 + + +# Tuple cũng giống như danh sách nhưng không thể thay đổi giá trị được (immutable) +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Sinh ra biệt lệ kiểu TypeError + +# Lưu ý rằng tuple có độ dài là 1 phải có dấu phẩy theo sau phần tử cuối +# nhưng tuples có độ dài khác, ngay cả tuple rỗng, thì không cần như vậy +type((1)) # => +type((1,)) # => +type(()) # => + +# Hầu hết các phép toán của danh sách đều áp dụng được cho tuples +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Bạn có thể gán giá trị cho nhiều biến một lúc bằng tuple (tuple unpacking) +a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +# Sau đây là unpacking kiểu mở rộng +a, *b, c = (1, 2, 3, 4) # a bây giờ là 1, b là [2, 3] và c là 4 +# Tuple được tự động tạo ra nếu bạn không để dấu ngoặc đơn +d, e, f = 4, 5, 6 +# Hoán đổi hai biến trở nên dễ dàng +e, d = d, e # d bây giờ là 5 và e là 4 + + +# Kiểu dữ liệu từ điển (dictionaries) lưu trữ ánh xạ từ các khóa (keys) đến các giá trị (values) +empty_dict = {} +# Sau đây là một từ điển có sẵn phần tử +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Lưu ý rằng khóa của từ điển phải có kiểu dữ liệu thuộc loại immutable. Điều này để bảo đảm rằng +# khóa đó luôn được chuyển hóa thành một giá trị băm (hash value) duy nhất khi tìm kiếm trong từ điển +# Những kiểu immutable bao gồm số nguyên (int), số thực (float), chuỗi ký tự (string), hay tuple +invalid_dict = {[1,2,3]: "123"} # => Sinh ra biệt lệ kiểu TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Tuy nhiên, giá trị có thể thuộc bất kỳ kiểu gì + +# Truy cập giá trị của một từ khóa bằng dấu [] +filled_dict["one"] # => 1 + +# Tất cả khóa trong một từ điển có thể được chuyển thành một đối tượng khả lặp (iterable). +# Chúng ta cần phải gọi hàm list() để chuyển một iterable thành một danh sách. +# Chúng ta sẽ bàn về vấn đề này sau. Lưu ý - Thứ tự của khóa trong từ điển sẽ không được đảm bảo. +# Những gì bạn thấy khi chạy dòng code dưới đây có thể sẽ không hoàn toàn giống như vậy. +list(filled_dict.keys()) # => ["three", "two", "one"] + + +# Tất cả các giá trị có thể chuyển thành một đối tượng khả lặp bằng cách gọi hàm "values()". +# Chúng ta cũng vẫn phải gọi hàm list() nếu muốn chuyển nó thành một danh sách. Lưu ý - thứ +# tự của giá trị cũng không được đảm bảo +list(filled_dict.values()) # => [3, 2, 1] + + +# Sự tồn tại của khóa trong từ điển có thể kiểm tra được thông qua từ khóa "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# Truy xuất giá trị của một khóa không tồn tại trong từ điển sẽ tạo ra biệt lệ KeyError +filled_dict["four"] # KeyError + +# Dừng phương thức "get()" để tránh tạo ra biệt lệ KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# Phương thức get hỗ trợ một đối số mặt định khi không thể tìm thấy giá trị ứng với từ khóa +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# "setdefault()" chèn một giá trị ứng với khóa nếu khóa đó không có sẵn trong từ điển +filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 + +# Thêm khóa và giá trị vào từ điển +filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} +filled_dict["four"] = 4 # another way to add to dict + +# Xóa một khóa ra khỏi từ điển bằng từ khóa del +del filled_dict["one"] # Removes the key "one" from filled dict + +# Bắt đầu từ Python 3.5 bạn có thể unpack từ điển trong một từ điển khác +{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} +{'a': 1, **{'a': 2}} # => {'a': 2} + + + +# Kiểu tập hợp (set) lưu trữ ... tập hợp +empty_set = set() +# Khởi tạo giá trị một tập hợp với nhiều giá tri. Vâng, nhìn nó khá giống từ điển. +some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} + +# Tương tự như khóa của từ điển, phần tử của một tập hợp cũng phải là immutable +invalid_set = {[1], 1} # => Sinh ra biệt lệ TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# Thêm một phần tử vào tập hợp +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# Thực hiện phép giao hai tập hợp bằng phép toán & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Thực hiện phép hợp bằng phép toán | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Lấy hiệu của hai tập hơp bằng phép toán - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Lấy hiệu đối xứng bằng phép toán ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Kiểm tra tập hợp bên trái là tập cha của bên phải +{1, 2} >= {1, 2, 3} # => False + +# Kiểm tra xem tập hợp bên trái có phải là tập con của tập hợp bên phải +{1, 2} <= {1, 2, 3} # => True + +# Kiểm tra sự tồn tại của một phần tử trong tập hợp bằng từ khóa in +2 in filled_set # => True +10 in filled_set # => False + + + +#################################################### +## 3. Luồng điều khiển và kiểu khả lặp +#################################################### + +# Đầu tiên hãy tạo ra một biến +some_var = 5 + +# Sau đây là một câu lệnh if. Khoảng cách lề rất quan trọng trong Python +# Quy ước chung là dùng khoảng trắng chứ không phải ký tự tab +# Chuỗi sau sẽ được in ra "some_var is smaller than 10" +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # Phần elif là tùy chọn. + print("some_var is smaller than 10.") +else: # else cũng là tùy chọn. + print("some_var is indeed 10.") + + +""" +Lặp qua một danh sách bằng for +in ra: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # Bạn có thể dùng format() để gán một giá trị vào giữa chuỗi (string interpolation) + print("{} is a mammal".format(animal)) + +""" +"range(number)" trả về một đối tượng khả lặp kiểu số +từ 0 đến giá trị của number +in ra: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(lower, upper)" trả về một đối tượng khả lặp kiểu số +từ giá trị lower đến giá trị upper +in ra: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(lower, upper, step)" trả về một đối tượng khả lặp kiểu số +từ giá trị lower đến giá trị upper, tăng dần theo giá trị +của step. Nếu không có giá trị của step thì mặc định là 1. +in ra: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) +""" + +Vòng lặp while tiếp tục lặp khi điều kiện còn được thỏa mãn +in ra: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # cách viết ngán cho x = x + 1 + +# Handle exceptions with a try/except block +# Đối phó với biệt lệ bằng khối lệnh try/except +try: + # Dùng "raise" để ném ra một biệt lệ + raise IndexError("This is an index error") +except IndexError as e: + pass # pass có nghĩa là không làm gì cả. Thông thường đây là nơi để khắc phụ vấn đề làm xảy ra biệt lệ +except (TypeError, NameError): + pass # Nhiều biệt lệ có thể được đối phó cùng một lúc nếu cần +else: # Không bắt buộc phải sử dụng else nhưng nếu dùng thì nó phải sau tất cả các khối except + print("All good!") # Chỉ thực thi nếu không có biệt lệ phát sinh +finally: # Luôn thực thi trong mọi hoàn cảnh + print("We can clean up resources here") + +# Thay vì dùng try/finally để thu hồi tài nguyên (resources) ta có thể dùng with +with open("myfile.txt") as f: + for line in f: + print(line) + +# Python hỗ trợ kiểu dữ liệu khả lặp (iterable). +# Một đối tượng khả lặp có thể được xem như là một chuỗi các đối tượng tuần tự (sequence) +# Đối tượng trả về bởi hàm range là một khả lặp. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => dict_keys(['one', 'two', 'three']). Đây là một đối tượng khả lặp + +# Ta có thể lặp qua đối tượng +for i in our_iterable: + print(i) # In ra một, hai, ba + +# Tuy nhiên chúng ta không thể truy cập phần tử bằng chỉ mục +our_iterable[1] # Sinh ra biệt lệ TypeError + +# Một đối tượng khả lặp là đối tượng có thể tạo ra một iterator +our_iterator = iter(our_iterable) + +# iterator là một đối tượng ghi nhớ được trạng thái trong quá trình nó được duyệt qua +# đối tượng kế tiếp có thể truy cập được bằng hàm next +next(our_iterator) # => "one" + +# Nó ghi nhớ trạng thái trong quá trình lặp +next(our_iterator) # => "two" +next(our_iterator) # => "three" + +# Sau khi iterator đã trả về tất cả dữ liệu, nó sẽ sinh ra biệt lệ kiểu StopIteration +next(our_iterator) # Sinh ra biệt lệ StopIteration + +# Ta có thể lấy tất cả phần tử của một iterator bằng cách gọi hàm list với nó +list(filled_dict.keys()) # => Returns ["one", "two", "three"] + + +#################################################### +## 4. Hàm +#################################################### + +# Dùng từ khóa def để định nghĩa hàm +def add(x, y): + print("x is {} and y is {}".format(x, y)) + return x + y # từ khóa return để trả về một giá trị + +# Gọi một hàm với đối số +add(5, 6) # => In ra "x is 5 and y is 6" và trả về 11 + +# Một cách khác để gọi hàm là dùng đối số có từ khóa (keyword arguments) +add(y=6, x=5) # Đối số có từ khóa có thể xuất hiện với thứ tự bất kỳ + +# Bạn có thể định nghĩa hàm có số lượng đối số vị trí (positional arguments) không biết trước +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# Số lượng tham số từ khóa cũng có thể không cần biết trước +def keyword_args(**kwargs): + return kwargs + +# Thử gọi hàm để xem điều gì xảy ra +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# Có thể định nghĩa hàm dùng cả hai loại đối số +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) in ra: + (1, 2) + {"a": 3, "b": 4} +""" + +# Khi gọi hàm, bạn có thể làm ngược với khi định nghĩa +# Dùng dấu * để lấy giá trị từ args và ** với giá trị từ kwargs +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # tương đương với foo(1, 2, 3, 4) +all_the_args(**kwargs) # tương đương với foo(a=3, b=4) +all_the_args(*args, **kwargs) # tương đương với foo(1, 2, 3, 4, a=3, b=4) + +# Trả về nhiều giá trị (gán vào một tuple) +def swap(x, y): + return y, x # Trả về nhiều giá trị dưới dạng một tuple mà không cần dấu ngoặc. + # (Lưu ý là dấu ngoặc đơn đã được bỏ đi những vẫn có thể được thêm vào) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # dấu ngoặc đơn đã được bỏ đi những vẫn có thể được thêm vào + +# Tầm vực của hàm +x = 5 + +def set_x(num): + # Biến cục bộ x không đồng nhất với biến toàn cục x + x = num # => 43 + print(x) # => 43 + +def set_global_x(num): + global x + print(x) # => 5 + x = num # biến toàn cục x được gán giá trị là 6 + print(x) # => 6 + +set_x(43) +set_global_x(6) + + +# Hàm trong Python cũng là đối tượng +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Có những hàm không tên +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# Có những hàm cấp cao được hỗ trọ sẵn +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] + +list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] + +# list comprehension có thể dùng để hay thế map và filter +# list comprehension lưu giá trị xuất vào một danh sách mà bản thân nó có thể lồng trong danh sách khác +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# Tập hơp và từ điển cũng có thể được tao ra thông qua set comprehension và dict comprehension +{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +## 5. Mô đun +#################################################### + +# Bạn có thể import một mô đun +import math +print(math.sqrt(16)) # => 4.0 + +# Bạn có thể lấy một hàm cụ thể từ một mô đun +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Hoặc import tất cả hàm từ một mô đun +# Cảnh báo: đây không phải là một cách hay +from math import * + +# Có thể làm tên của module ngắn lại +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Mô đun trong Python chỉ là những tập tin Python bình thường. Bạn +# có thể viết mô đun của mình và import chúng. Tên của mô đun +# cũng là tên của tập tin. + +# You can find out which functions and attributes +# are defined in a module. +# Bạn có thể liệt kê những hàm và thuộc tính +# được định nghĩa trong một mô đun +import math +dir(math) + +# Nếu bạn có một tập tin code Python gọi là math.py ở cùng +# thư mục với tập tin hiện tai, tập tin math.py sẽ +# được nạp vào thay vì mô đun được cung cấp sẵn (built-in) trong Python. +# Điều này xảy ra vì thư mục hiện tại có ưu tiên +# hơn những thư viện cung cấp sẵn. + + +#################################################### +## 6. Lớp (classes) +#################################################### + +# Ta dùng từ khóa "class" đề định nghĩa một lớp +class Human: + + # Một thuộc tính của lớp được chia sẽ bởi tất cả đối tượng của lớp này + species = "H. sapiens" + + # Hàm khởi tạo cơ bản sẽ được goi khi một đối tượng được tạo ra. + # Lưu ý 2 dấu gạch dưới ở đầu và cuối ám chỉ đối tượng + # hoặc thuộc tính dùng bở Python những tồn tại trong không gian tên + # do người dùng kiểm soát. Phương thức (hoặc thuộc tính) như: __init__, __str__, + # __repr__ v.v.. là những phương thức đặc biệt. + # Bạn không nên tự đặt những tên như vậy. + def __init__(self, name): + # Gán đối số vào thuộc tính name của đối tượng + self.name = name + + # Khởi tạo thuộc tính + self._age = 0 + + # Một phương thức trên đối tượng. Tất cả đều có đối số đầu tiên là "self" + def say(self, msg): + print ("{name}: {message}".format(name=self.name, message=msg)) + + # Một phương thức trên đối tượng khác + def sing(self): + return 'yo... yo... microphone check... one two... one two...' + + # Một phương thức trên lớp được chia sẻ với mọi đối tượng + # Lớp đó cũng là đối số thứ nhất của phương thức đó + @classmethod + def get_species(cls): + return cls.species + + # Một phương thức tĩnh được gọi mà không có lớp hay đối tượng đi kèm + @staticmethod + def grunt(): + return "*grunt*" + + # Một thuộc tính chỉ giống như một hàm truy xuất. + # Nó biến phương thức age() thành một thuộc tính chỉ đọc cùng tên. + # Tuy nhiên trong Python không nhất thiết phải viết những hàm đọc và ghi quá đơn giản + @property + def age(self): + return self._age + + # Đây là hàm để ghi giá trị cho thuộc tính + @age.setter + def age(self, age): + self._age = age + + # Đây là hàm để xóa thuộc tính + @age.deleter + def age(self): + del self._age + + +# Khi trình thông dịch Python đọc một tập tin mã nguồn, nó thực thi tất cả code trong đó. +# Kiểm tra giá trị của __name__ bảo đảm rằng đoạn mã bên dưới chỉ thực thi khi +# mô đun này là chương trình chính +if __name__ == '__main__': + # Khởi tạo một đối tượng + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # i và j là thực thể của kiểu Human, nói cách khác: chúng là những đối tượng Human + + # Gọi những phương thức trên lớp + i.say(i.get_species()) # "Ian: H. sapiens" + # Thay đổi thuộc tính chung + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # Gọi phương thức tĩnh + print(Human.grunt()) # => "*grunt*" + + # Không thể gọi phương thức tĩnh với một thực thể/đối tượng + # bởi vì i.grunt() sẽ tự động đặt "self" (tức là đối tượng i) làm đối số thứ nhất + print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given + + # Thay đổi thuộc tính của đối tượng + i.age = 42 + # Truy cập thuộc tính + i.say(i.age) # => "Ian: 42" + j.say(j.age) # => "Joel: 0" + # Xóa thuộc tính + del i.age + # i.age # => dòng nãy sẽ tạo ra biệt lệ AttributeError + + +#################################################### +## 6.1 Đa thừa kế +#################################################### + +# Một định nghĩa lớp khác +class Bat: + + species = 'Baty' + + def __init__(self, can_fly=True): + self.fly = can_fly + + # Lớp này có phương thức say + def say(self, msg): + msg = '... ... ...' + return msg + + # Và một phương thức khác + def sonar(self): + return '))) ... (((' + +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) + +# Để tận dụng việc mô đun hóa thành từng tập tin, bạn có thể đặt những lớp định nghĩa ở trên vào các tập tin riêng, +# ví dụ như human.py và bat.py + +# Để import hàm từ tập tin khác dừng cấu trúc sau +# from "filename-without-extension" import "function-or-class" + +# superhero.py +from human import Human +from bat import Bat + +# Batman thừa kế từ lớp Human và Bat +class Batman(Human, Bat): + + # Batman có giá trị riêng cho thuộc tính trên lớp species + species = 'Superhero' + + def __init__(self, *args, **kwargs): + # Cách điển hình để thừa kế thuộc tính là gọi super + # super(Batman, self).__init__(*args, **kwargs) + # Tuy nhiên với đa thừa kế, super() sẽ chỉ gọi lớp cơ sở tiếp theo trong danh sách MRO. + # Vì thế, ta sẽ gọi cụ thể hàm __init__ của các lớp chả. + # Sử dụng *args và **kwargs cho phép việc truyền đối số gọn gàng hơn, + # trong đó mỗi lớp cha sẽ chịu trách nhiệm cho những phần thuộc về nó + Human.__init__(self, 'anonymous', *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # ghi đè giá trị của thuộc tính name + self.name = 'Sad Affleck' + + def sing(self): + return 'nan nan nan nan nan batman!' + + +if __name__ == '__main__': + sup = Batman() + + # Kiểm tra kiểu đối tượng + if isinstance(sup, Human): + print('I am human') + if isinstance(sup, Bat): + print('I am bat') + if type(sup) is Batman: + print('I am Batman') + + # Truy xuất thứ tự phương thức của các lớp cha (Method Resolution search Order), vốn được dùng bởi cả getattr() và super9) + # Thuộc tính này động và có thể được cập nhật + print(Batman.__mro__) # => (, , , ) + + # Gọi phương thức của lớp cha nhưng dùng thuộc tính trên chính lớp hiện tại + print(sup.get_species()) # => Superhero + + # Gọi phương thức được nạp chồng + print(sup.sing()) # => nan nan nan nan nan batman! + + # Gọi phương thức của Human, bởi vì thứ tự thừa kế ảnh hưởng đến phương thức được gọi + sup.say('I agree') # => Sad Affleck: I agree + + # Gọi phương thức chỉ tồn tại ở lớp cha thứ 2 + print(sup.sonar()) # => ))) ... ((( + + # Thuộc tính cấp lớp được thừa kế + sup.age = 100 + print(sup.age) + + # Thuộc tính thừa kế từ lớp cha thứ 2 có giá trị mặc định đã bị ghi đè + print('Can I fly? ' + str(sup.fly)) + + + +#################################################### +## 7. Phần nâng cao +#################################################### + +# Generator giúp ta viết những đoạn code lười biếng (áp dụng nguyên tắc lazy evaluation) +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Generators tiết kiệm bộ nhớ vì nó chỉ tải dữ liệu khi cần +# xử lý giá trị kế tiếp của một đối tượng khả lặp. Điều này cho phép generator thực hiện +# những thao tác mà bình thường không làm được trên những khoảng giá trị lớn +# Lưu ý: `range` thay thế `xrange` trong Python3. + +for i in double_numbers(range(1, 900000000)): # `range` là một generator. + print(i) + if i >= 30: + break + +# Cũng như danh sách có list comprehension, generator cũng có generator +# comprehension +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # in -1 -2 -3 -4 -5 ra màn hình dòng lệnh + +# Một generator cũng có thể bị ép kiểu thành danh sách +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + + +# Decorators +# Trong ví dụ này hàm `beg` 'phủ lên' hàm `say`. Nếu say_please là True thì nó +# sẽ thay đội giá trị trả về +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Làm ơn! Tui rất nghèo :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Mua bia cho tui nhé?" + return msg, say_please + + +print(say()) # Mua bia cho tui nhé? +print(say(say_please=True)) # Mua bia cho tui nhé? Làm ơn! Tui rất nghèo :( +``` + +## Sẵn sàng để học nhiều hơn? + +### Miễn phí trên mạng + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) +* [Dive Into Python 3](http://www.diveintopython3.net/index.html) +* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/vi-vn/python3-vi.html.markdown b/vi-vn/python3-vi.html.markdown deleted file mode 100644 index f6cce1a3..00000000 --- a/vi-vn/python3-vi.html.markdown +++ /dev/null @@ -1,914 +0,0 @@ ---- -language: python3 -filename: learnpython3-vi.py -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] - - ["evuez", "http://github.com/evuez"] -translators: - - ["Xuan (Sean) Luong, https://github.com/xuanluong"] -lang: vi-vn - ---- - -Python được tạo ra bởi Guido van Rossum vào đầu những năm 90s. Ngày nay nó là một trong những ngôn ngữ phổ biến -nhất còn tồn tại. Tôi thích Python vì sự rõ ràng, trong sáng về mặt cú pháp. Về cơ bản, Python có thể coi -như một loại mã giả (pseudocode) có thể thực thi được. - -Mọi phản hồi đều sẽ được tích cực ghi nhận! Bạn có thể liên lạc với tôi qua Twitter [@louiedinh](http://twitter.com/louiedinh) hoặc louiedinh [at] [google's email service] - -Lưu ý: Bài viết này áp dụng riêng cho Python 3. Truy cập [vào đây](http://learnxinyminutes.com/docs/python/) nếu bạn muốn học phiên bản cũ Python 2.7 - -```python - -# Dòng bình luận (comment) bắt đầu bằng dấu thăng (#) - -""" Những chuỗi ký tự (string) nằm trên nhiều dòng - có thể được viết bằng cách dùng 3 dấu nháy " và thường - được dùng trong quá trình viết tài liệu (documentation). -""" - -#################################################### -## 1. Các kiểu dữ liệu cơ bản và Các phép toán -#################################################### - -# Bạn có những con số -3 # => 3 - -# Tính toán với những con số là những điều có thể bạn sẽ làm -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7.0 - -# Kết quả của phép chia số nguyên sẽ được làm tròn xuống cho cả số dương và số âm -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # phép chia số nguyên cũng áp dụng được cho kiểu dữ liệu float biểu diễn số thực --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Kết quả của phép chia luôn là số thực -10.0 / 3 # => 3.3333333333333335 - -# Phép toán lấy phần dư (modulo) -7 % 3 # => 1 - -# Phép lũy thừa (x**y, x lũy thừa y) -2**3 # => 8 - -# Áp đặt thứ tự tính toán bằng dấu ngoặc -(1 + 3) * 2 # => 8 - -# Kiểu Boolean cũng là một kiểu dữ liệu cơ bản (Lưu ý: ký tự đầu tiên viết hoa) -True -False - -# Phủ định bằng từ khóa 'not' -not True # => False -not False # => True - -# Các phép toán với kiểu Boolean -# Lưu ý từ khóa "and" và "or" là case-sensitive -True and False # => False -False or True # => True - -# Lưu ý khi sử dụng các phép toán của kiểu Boolean với số nguyên 'int' -# False là 0 và True là 1 -# Đừng nhầm lẫn các phép toán Boolean cho số nguyên và các phép toán and/or trên bit (& và |) -0 and 2 # => 0 --5 or 0 # => -5 -0 == False # => True -2 == True # => False -1 == True # => True --5 != False != True #=> True - -# So sánh bằng với == -1 == 1 # => True -2 == 1 # => False - -# So sánh không bằng với != -1 != 1 # => False -2 != 1 # => True - -# Các phép so sánh khác -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# Các phép so sánh có thể xâu chuỗi với nhau! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# (is vs. ==) từ khóa is kiểm tra xem 2 biến có cùng tham chiếu một đối tượng, còn == kiếm tra -# xem hai đối tượng có cùng giá trị hay không. -a = [1, 2, 3, 4] # a trỏ tới một danh sách (list) mới, [1, 2, 3, 4] -b = a # b trỏ tới nơi mà a cũng đang trỏ tới -b is a # => True, a và b cùng trỏ tới một đối tượng -b == a # => True, đối tượng mà a và b trỏ tới có cùng giá trị -b = [1, 2, 3, 4] # b trỏ tới một danh sách mới, [1, 2, 3, 4] -b is a # => False, a và b không cùng trỏ tới một đối tượng -b == a # => True, đối tượng mà a và b trỏ tới không có cùng giá trị - -# Chuỗi ký tự được tạo ra bằng dấu nháy kép " hoặc nháy đơn ' -"Đây là một chuỗi ký tự." -'Đây cũng là một chuỗi ký tự.' - -# Chuỗi ký tự có thể được cộng với nhau can be added too! Tuy nhiên nên tránh làm như vậy -"Xin " + "chào!" # => "Xin chào!" -# Các chuỗi ký tự không phải là biến (literals) có thể được nối với nhau mà không cần dùng phép cộng '+' -"Xin " "chào!" # => "Xin chào!" - -# Một chuỗi ký tự có thể xem như một danh sách (list) các ký tự -"Đây là một chuỗi ký tự"[0] # => 'Đ' - -# Bạn có thể tìm chiều dài một chuỗi -len("Đây là một chuỗi") # => 16 - -# .format có thể được dùng để định dạng chuỗi, ví dụ như: -"{} có thể được {}".format("Chuỗi ký tự", "định dạng") # => "Chuỗi ký tự có thể được định dạng" - -# Bạn có thể lặp lại đối số (arguments) khi định dạnh để không phải gõ nhiều lần -"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" - -# Bạn có thể dùng từ khóa nếu bạn không muốn đếm -"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" - -# Nếu code Python 3 của bạn cần phải chạy với Python 2.5 hoặc các bản cũ hơn, bạn cũng có thể -# dùng cách định dạng cũ: -"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" - - -# None là một đối tượng -None # => None - -# Đừng dùng so sánh bằng "==" để so sánh đối tượng với None -# Thay vào đó dùng is. Nó sẽ kiểm tra xem một đối tượng có đồng nhất với None hay không. -"etc" is None # => False -None is None # => True - -# None, 0, và chuỗi/danh sách (list)/từ điển (dict)/tuple rỗng khi chuyển về kiểu Boolean đều có giá trị là False. -# Tất cả những giá trị khác đều là True -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False -bool(()) # => False - -#################################################### -## 2. Biến và Các kiểu dữ liệu gộp (Collections) -#################################################### - -# Hàm print trong Python -print("Tôi là Python. Rất hân hạnh được làm quen!") # => Tôi là Python. Rất hân hạnh được làm quen! - -# Hàm print mặc định in thêm ký tự xuống dòng -# Dùng đối số tùy chọn (optional argument) để thay đổi cách kết thúc chuỗi. -print("Hello, World", end="!") # => Hello, World! - -# Một cách đơn giản để lấy dữ liệu vào từ bàn phím -input_string_var = input("Nhập dữ liệu: ") # Trả về dữ liệu vào là một chuỗi -# Lưu ý: Trong những phiên bản cũ của Python input() có tên là raw_input() - -# Không cần phải khai báo biến mà chỉ có gán giá trị cho biến. -# Quy ước là sử dụng chữ_viết_thường_có_dấu_gạch_dưới -some_var = 5 -some_var # => 5 - -# Truy cập một biến chưa được gán trước đó sẽ tạo ra biệt lệ (exception). -# Đọc mục Luồng điều khiển để hiểu thêm về việc giải quyết các biệt lệ (exception handling) -some_unknown_var # Sinh ra một biệt lệ kiểu NameError - -# if có thể dùng như một biểu thức -# Tương đương với phép toán ba ngôi trong C: '?:' -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# Kiểu danh sách (list) lưu trữ chuỗi đối tượng tuần tự -li = [] -# Bạn có thể bắt đầu với một danh sách đã có sãn các phần tử -other_li = [4, 5, 6] - -# Thêm phần tử vào cuối danh sách bằng phương thức append -li.append(1) # li bây giờ là [1] -li.append(2) # li bây giờ là [1, 2] -li.append(4) # li bây giờ là [1, 2, 4] -li.append(3) # li bây giờ là [1, 2, 4, 3] -# Xóa phần tử cuối cùng bằng phương thức pop -li.pop() # => 3 and li is now [1, 2, 4] -# Sau đó ta có thể đưa đối tượng trở lại danh sách -li.append(3) # li trở lại là [1, 2, 4, 3]. - -# Truy cập một danh sách như bạn làm với một mảng (array) -li[0] # => 1 -# Truy cập phần tử cuối cùng -li[-1] # => 3 - -# Truy cập ngoài giới hạn sẽ tạo ra biệt lệ IndexError -li[4] # Sinh ra một biệt lệ kiểu IndexError - -# Bạn có thể truy cập một đoạn bằng phép cắt (slice). -# Chỉ mục bắt đầu được tính làm điểm bắt đầu còn chỉ mục kết thúc thì không, mà là chỉ mục của phần tử tiếp theo phần tử kết thúc -# (Về mặt toán học thì đây là một đoạn đóng/mở, hay nửa đoạn) -li[1:3] # => [2, 4] -# Lấy từ vị trí thứ 3 đến hết -li[2:] # => [4, 3] -# Lấy từ đầu đến vị trí thứ 3 -li[:3] # => [1, 2, 4] -# Lấy những phần tử có chỉ mục chẵn -li[::2] # =>[1, 4] -# Trả về bản sao của danh sách bị đảo ngược -li[::-1] # => [3, 4, 2, 1] -# Kết hợp 3 tham số để làm những phép cắt phức tạp hơn -# li[start:end:step] - -# Tạo ra một bản sao sâu (deep copy) bằng phép cắt -li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. - -# Xóa phần tử nào đó của danh sách bằng "del" -del li[2] # li is now [1, 2, 3] - -# Xóa đi phần tử đầu tiên mang một giá trị nhất định -li.remove(2) # li bây giờ là [1, 3] -li.remove(2) # Sinh ra biệt lệ kiểu ValueError vì 2 không tồn tại trong danh sách - -# Chèn một phần tử vào một vị trí cụ thể -li.insert(1, 2) # li bây giờ lại là [1, 2, 3] - -# Tìm chỉ mục của của phần tử đầu tiên mang một giá trị nhất định -li.index(2) # => 1 -li.index(4) # Sinh ra biệt lệ a ValueError as 4 is not in the list - -# Bạn có thể cộng dồn các danh sách -# Lưu ý: giá trị của li và other_li không đổi -li + other_li # => [1, 2, 3, 4, 5, 6] - -# Nối danh sách bằng "extend()" -li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] - -# Kiểm tra sự tồn tại của một phần tử trong danh sách bằng "in" -1 in li # => True - -# Xác định độ dài bằng "len()" -len(li) # => 6 - - -# Tuple cũng giống như danh sách nhưng không thể thay đổi giá trị được (immutable) -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # Sinh ra biệt lệ kiểu TypeError - -# Lưu ý rằng tuple có độ dài là 1 phải có dấu phẩy theo sau phần tử cuối -# nhưng tuples có độ dài khác, ngay cả tuple rỗng, thì không cần như vậy -type((1)) # => -type((1,)) # => -type(()) # => - -# Hầu hết các phép toán của danh sách đều áp dụng được cho tuples -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# Bạn có thể gán giá trị cho nhiều biến một lúc bằng tuple (tuple unpacking) -a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 -# Sau đây là unpacking kiểu mở rộng -a, *b, c = (1, 2, 3, 4) # a bây giờ là 1, b là [2, 3] và c là 4 -# Tuple được tự động tạo ra nếu bạn không để dấu ngoặc đơn -d, e, f = 4, 5, 6 -# Hoán đổi hai biến trở nên dễ dàng -e, d = d, e # d bây giờ là 5 và e là 4 - - -# Kiểu dữ liệu từ điển (dictionaries) lưu trữ ánh xạ từ các khóa (keys) đến các giá trị (values) -empty_dict = {} -# Sau đây là một từ điển có sẵn phần tử -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Lưu ý rằng khóa của từ điển phải có kiểu dữ liệu thuộc loại immutable. Điều này để bảo đảm rằng -# khóa đó luôn được chuyển hóa thành một giá trị băm (hash value) duy nhất khi tìm kiếm trong từ điển -# Những kiểu immutable bao gồm số nguyên (int), số thực (float), chuỗi ký tự (string), hay tuple -invalid_dict = {[1,2,3]: "123"} # => Sinh ra biệt lệ kiểu TypeError: unhashable type: 'list' -valid_dict = {(1,2,3):[1,2,3]} # Tuy nhiên, giá trị có thể thuộc bất kỳ kiểu gì - -# Truy cập giá trị của một từ khóa bằng dấu [] -filled_dict["one"] # => 1 - -# Tất cả khóa trong một từ điển có thể được chuyển thành một đối tượng khả lặp (iterable). -# Chúng ta cần phải gọi hàm list() để chuyển một iterable thành một danh sách. -# Chúng ta sẽ bàn về vấn đề này sau. Lưu ý - Thứ tự của khóa trong từ điển sẽ không được đảm bảo. -# Những gì bạn thấy khi chạy dòng code dưới đây có thể sẽ không hoàn toàn giống như vậy. -list(filled_dict.keys()) # => ["three", "two", "one"] - - -# Tất cả các giá trị có thể chuyển thành một đối tượng khả lặp bằng cách gọi hàm "values()". -# Chúng ta cũng vẫn phải gọi hàm list() nếu muốn chuyển nó thành một danh sách. Lưu ý - thứ -# tự của giá trị cũng không được đảm bảo -list(filled_dict.values()) # => [3, 2, 1] - - -# Sự tồn tại của khóa trong từ điển có thể kiểm tra được thông qua từ khóa "in" -"one" in filled_dict # => True -1 in filled_dict # => False - -# Truy xuất giá trị của một khóa không tồn tại trong từ điển sẽ tạo ra biệt lệ KeyError -filled_dict["four"] # KeyError - -# Dừng phương thức "get()" để tránh tạo ra biệt lệ KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# Phương thức get hỗ trợ một đối số mặt định khi không thể tìm thấy giá trị ứng với từ khóa -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 - -# "setdefault()" chèn một giá trị ứng với khóa nếu khóa đó không có sẵn trong từ điển -filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 - -# Thêm khóa và giá trị vào từ điển -filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} -filled_dict["four"] = 4 # another way to add to dict - -# Xóa một khóa ra khỏi từ điển bằng từ khóa del -del filled_dict["one"] # Removes the key "one" from filled dict - -# Bắt đầu từ Python 3.5 bạn có thể unpack từ điển trong một từ điển khác -{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} -{'a': 1, **{'a': 2}} # => {'a': 2} - - - -# Kiểu tập hợp (set) lưu trữ ... tập hợp -empty_set = set() -# Khởi tạo giá trị một tập hợp với nhiều giá tri. Vâng, nhìn nó khá giống từ điển. -some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} - -# Tương tự như khóa của từ điển, phần tử của một tập hợp cũng phải là immutable -invalid_set = {[1], 1} # => Sinh ra biệt lệ TypeError: unhashable type: 'list' -valid_set = {(1,), 1} - -# Thêm một phần tử vào tập hợp -filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} - -# Thực hiện phép giao hai tập hợp bằng phép toán & -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# Thực hiện phép hợp bằng phép toán | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# Lấy hiệu của hai tập hơp bằng phép toán - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Lấy hiệu đối xứng bằng phép toán ^ -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# Kiểm tra tập hợp bên trái là tập cha của bên phải -{1, 2} >= {1, 2, 3} # => False - -# Kiểm tra xem tập hợp bên trái có phải là tập con của tập hợp bên phải -{1, 2} <= {1, 2, 3} # => True - -# Kiểm tra sự tồn tại của một phần tử trong tập hợp bằng từ khóa in -2 in filled_set # => True -10 in filled_set # => False - - - -#################################################### -## 3. Luồng điều khiển và kiểu khả lặp -#################################################### - -# Đầu tiên hãy tạo ra một biến -some_var = 5 - -# Sau đây là một câu lệnh if. Khoảng cách lề rất quan trọng trong Python -# Quy ước chung là dùng khoảng trắng chứ không phải ký tự tab -# Chuỗi sau sẽ được in ra "some_var is smaller than 10" -if some_var > 10: - print("some_var is totally bigger than 10.") -elif some_var < 10: # Phần elif là tùy chọn. - print("some_var is smaller than 10.") -else: # else cũng là tùy chọn. - print("some_var is indeed 10.") - - -""" -Lặp qua một danh sách bằng for -in ra: - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - # Bạn có thể dùng format() để gán một giá trị vào giữa chuỗi (string interpolation) - print("{} is a mammal".format(animal)) - -""" -"range(number)" trả về một đối tượng khả lặp kiểu số -từ 0 đến giá trị của number -in ra: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -"range(lower, upper)" trả về một đối tượng khả lặp kiểu số -từ giá trị lower đến giá trị upper -in ra: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -"range(lower, upper, step)" trả về một đối tượng khả lặp kiểu số -từ giá trị lower đến giá trị upper, tăng dần theo giá trị -của step. Nếu không có giá trị của step thì mặc định là 1. -in ra: - 4 - 6 -""" -for i in range(4, 8, 2): - print(i) -""" - -Vòng lặp while tiếp tục lặp khi điều kiện còn được thỏa mãn -in ra: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # cách viết ngán cho x = x + 1 - -# Handle exceptions with a try/except block -# Đối phó với biệt lệ bằng khối lệnh try/except -try: - # Dùng "raise" để ném ra một biệt lệ - raise IndexError("This is an index error") -except IndexError as e: - pass # pass có nghĩa là không làm gì cả. Thông thường đây là nơi để khắc phụ vấn đề làm xảy ra biệt lệ -except (TypeError, NameError): - pass # Nhiều biệt lệ có thể được đối phó cùng một lúc nếu cần -else: # Không bắt buộc phải sử dụng else nhưng nếu dùng thì nó phải sau tất cả các khối except - print("All good!") # Chỉ thực thi nếu không có biệt lệ phát sinh -finally: # Luôn thực thi trong mọi hoàn cảnh - print("We can clean up resources here") - -# Thay vì dùng try/finally để thu hồi tài nguyên (resources) ta có thể dùng with -with open("myfile.txt") as f: - for line in f: - print(line) - -# Python hỗ trợ kiểu dữ liệu khả lặp (iterable). -# Một đối tượng khả lặp có thể được xem như là một chuỗi các đối tượng tuần tự (sequence) -# Đối tượng trả về bởi hàm range là một khả lặp. - -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) # => dict_keys(['one', 'two', 'three']). Đây là một đối tượng khả lặp - -# Ta có thể lặp qua đối tượng -for i in our_iterable: - print(i) # In ra một, hai, ba - -# Tuy nhiên chúng ta không thể truy cập phần tử bằng chỉ mục -our_iterable[1] # Sinh ra biệt lệ TypeError - -# Một đối tượng khả lặp là đối tượng có thể tạo ra một iterator -our_iterator = iter(our_iterable) - -# iterator là một đối tượng ghi nhớ được trạng thái trong quá trình nó được duyệt qua -# đối tượng kế tiếp có thể truy cập được bằng hàm next -next(our_iterator) # => "one" - -# Nó ghi nhớ trạng thái trong quá trình lặp -next(our_iterator) # => "two" -next(our_iterator) # => "three" - -# Sau khi iterator đã trả về tất cả dữ liệu, nó sẽ sinh ra biệt lệ kiểu StopIteration -next(our_iterator) # Sinh ra biệt lệ StopIteration - -# Ta có thể lấy tất cả phần tử của một iterator bằng cách gọi hàm list với nó -list(filled_dict.keys()) # => Returns ["one", "two", "three"] - - -#################################################### -## 4. Hàm -#################################################### - -# Dùng từ khóa def để định nghĩa hàm -def add(x, y): - print("x is {} and y is {}".format(x, y)) - return x + y # từ khóa return để trả về một giá trị - -# Gọi một hàm với đối số -add(5, 6) # => In ra "x is 5 and y is 6" và trả về 11 - -# Một cách khác để gọi hàm là dùng đối số có từ khóa (keyword arguments) -add(y=6, x=5) # Đối số có từ khóa có thể xuất hiện với thứ tự bất kỳ - -# Bạn có thể định nghĩa hàm có số lượng đối số vị trí (positional arguments) không biết trước -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - -# Số lượng tham số từ khóa cũng có thể không cần biết trước -def keyword_args(**kwargs): - return kwargs - -# Thử gọi hàm để xem điều gì xảy ra -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# Có thể định nghĩa hàm dùng cả hai loại đối số -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) in ra: - (1, 2) - {"a": 3, "b": 4} -""" - -# Khi gọi hàm, bạn có thể làm ngược với khi định nghĩa -# Dùng dấu * để lấy giá trị từ args và ** với giá trị từ kwargs -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # tương đương với foo(1, 2, 3, 4) -all_the_args(**kwargs) # tương đương với foo(a=3, b=4) -all_the_args(*args, **kwargs) # tương đương với foo(1, 2, 3, 4, a=3, b=4) - -# Trả về nhiều giá trị (gán vào một tuple) -def swap(x, y): - return y, x # Trả về nhiều giá trị dưới dạng một tuple mà không cần dấu ngoặc. - # (Lưu ý là dấu ngoặc đơn đã được bỏ đi những vẫn có thể được thêm vào) - -x = 1 -y = 2 -x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # dấu ngoặc đơn đã được bỏ đi những vẫn có thể được thêm vào - -# Tầm vực của hàm -x = 5 - -def set_x(num): - # Biến cục bộ x không đồng nhất với biến toàn cục x - x = num # => 43 - print(x) # => 43 - -def set_global_x(num): - global x - print(x) # => 5 - x = num # biến toàn cục x được gán giá trị là 6 - print(x) # => 6 - -set_x(43) -set_global_x(6) - - -# Hàm trong Python cũng là đối tượng -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# Có những hàm không tên -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# Có những hàm cấp cao được hỗ trọ sẵn -list(map(add_10, [1, 2, 3])) # => [11, 12, 13] -list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] - -list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] - -# list comprehension có thể dùng để hay thế map và filter -# list comprehension lưu giá trị xuất vào một danh sách mà bản thân nó có thể lồng trong danh sách khác -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -# Tập hơp và từ điển cũng có thể được tao ra thông qua set comprehension và dict comprehension -{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} -{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} - - -#################################################### -## 5. Mô đun -#################################################### - -# Bạn có thể import một mô đun -import math -print(math.sqrt(16)) # => 4.0 - -# Bạn có thể lấy một hàm cụ thể từ một mô đun -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# Hoặc import tất cả hàm từ một mô đun -# Cảnh báo: đây không phải là một cách hay -from math import * - -# Có thể làm tên của module ngắn lại -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Mô đun trong Python chỉ là những tập tin Python bình thường. Bạn -# có thể viết mô đun của mình và import chúng. Tên của mô đun -# cũng là tên của tập tin. - -# You can find out which functions and attributes -# are defined in a module. -# Bạn có thể liệt kê những hàm và thuộc tính -# được định nghĩa trong một mô đun -import math -dir(math) - -# Nếu bạn có một tập tin code Python gọi là math.py ở cùng -# thư mục với tập tin hiện tai, tập tin math.py sẽ -# được nạp vào thay vì mô đun được cung cấp sẵn (built-in) trong Python. -# Điều này xảy ra vì thư mục hiện tại có ưu tiên -# hơn những thư viện cung cấp sẵn. - - -#################################################### -## 6. Lớp (classes) -#################################################### - -# Ta dùng từ khóa "class" đề định nghĩa một lớp -class Human: - - # Một thuộc tính của lớp được chia sẽ bởi tất cả đối tượng của lớp này - species = "H. sapiens" - - # Hàm khởi tạo cơ bản sẽ được goi khi một đối tượng được tạo ra. - # Lưu ý 2 dấu gạch dưới ở đầu và cuối ám chỉ đối tượng - # hoặc thuộc tính dùng bở Python những tồn tại trong không gian tên - # do người dùng kiểm soát. Phương thức (hoặc thuộc tính) như: __init__, __str__, - # __repr__ v.v.. là những phương thức đặc biệt. - # Bạn không nên tự đặt những tên như vậy. - def __init__(self, name): - # Gán đối số vào thuộc tính name của đối tượng - self.name = name - - # Khởi tạo thuộc tính - self._age = 0 - - # Một phương thức trên đối tượng. Tất cả đều có đối số đầu tiên là "self" - def say(self, msg): - print ("{name}: {message}".format(name=self.name, message=msg)) - - # Một phương thức trên đối tượng khác - def sing(self): - return 'yo... yo... microphone check... one two... one two...' - - # Một phương thức trên lớp được chia sẻ với mọi đối tượng - # Lớp đó cũng là đối số thứ nhất của phương thức đó - @classmethod - def get_species(cls): - return cls.species - - # Một phương thức tĩnh được gọi mà không có lớp hay đối tượng đi kèm - @staticmethod - def grunt(): - return "*grunt*" - - # Một thuộc tính chỉ giống như một hàm truy xuất. - # Nó biến phương thức age() thành một thuộc tính chỉ đọc cùng tên. - # Tuy nhiên trong Python không nhất thiết phải viết những hàm đọc và ghi quá đơn giản - @property - def age(self): - return self._age - - # Đây là hàm để ghi giá trị cho thuộc tính - @age.setter - def age(self, age): - self._age = age - - # Đây là hàm để xóa thuộc tính - @age.deleter - def age(self): - del self._age - - -# Khi trình thông dịch Python đọc một tập tin mã nguồn, nó thực thi tất cả code trong đó. -# Kiểm tra giá trị của __name__ bảo đảm rằng đoạn mã bên dưới chỉ thực thi khi -# mô đun này là chương trình chính -if __name__ == '__main__': - # Khởi tạo một đối tượng - i = Human(name="Ian") - i.say("hi") # "Ian: hi" - j = Human("Joel") - j.say("hello") # "Joel: hello" - # i và j là thực thể của kiểu Human, nói cách khác: chúng là những đối tượng Human - - # Gọi những phương thức trên lớp - i.say(i.get_species()) # "Ian: H. sapiens" - # Thay đổi thuộc tính chung - Human.species = "H. neanderthalensis" - i.say(i.get_species()) # => "Ian: H. neanderthalensis" - j.say(j.get_species()) # => "Joel: H. neanderthalensis" - - # Gọi phương thức tĩnh - print(Human.grunt()) # => "*grunt*" - - # Không thể gọi phương thức tĩnh với một thực thể/đối tượng - # bởi vì i.grunt() sẽ tự động đặt "self" (tức là đối tượng i) làm đối số thứ nhất - print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given - - # Thay đổi thuộc tính của đối tượng - i.age = 42 - # Truy cập thuộc tính - i.say(i.age) # => "Ian: 42" - j.say(j.age) # => "Joel: 0" - # Xóa thuộc tính - del i.age - # i.age # => dòng nãy sẽ tạo ra biệt lệ AttributeError - - -#################################################### -## 6.1 Đa thừa kế -#################################################### - -# Một định nghĩa lớp khác -class Bat: - - species = 'Baty' - - def __init__(self, can_fly=True): - self.fly = can_fly - - # Lớp này có phương thức say - def say(self, msg): - msg = '... ... ...' - return msg - - # Và một phương thức khác - def sonar(self): - return '))) ... (((' - -if __name__ == '__main__': - b = Bat() - print(b.say('hello')) - print(b.fly) - -# Để tận dụng việc mô đun hóa thành từng tập tin, bạn có thể đặt những lớp định nghĩa ở trên vào các tập tin riêng, -# ví dụ như human.py và bat.py - -# Để import hàm từ tập tin khác dừng cấu trúc sau -# from "filename-without-extension" import "function-or-class" - -# superhero.py -from human import Human -from bat import Bat - -# Batman thừa kế từ lớp Human và Bat -class Batman(Human, Bat): - - # Batman có giá trị riêng cho thuộc tính trên lớp species - species = 'Superhero' - - def __init__(self, *args, **kwargs): - # Cách điển hình để thừa kế thuộc tính là gọi super - # super(Batman, self).__init__(*args, **kwargs) - # Tuy nhiên với đa thừa kế, super() sẽ chỉ gọi lớp cơ sở tiếp theo trong danh sách MRO. - # Vì thế, ta sẽ gọi cụ thể hàm __init__ của các lớp chả. - # Sử dụng *args và **kwargs cho phép việc truyền đối số gọn gàng hơn, - # trong đó mỗi lớp cha sẽ chịu trách nhiệm cho những phần thuộc về nó - Human.__init__(self, 'anonymous', *args, **kwargs) - Bat.__init__(self, *args, can_fly=False, **kwargs) - # ghi đè giá trị của thuộc tính name - self.name = 'Sad Affleck' - - def sing(self): - return 'nan nan nan nan nan batman!' - - -if __name__ == '__main__': - sup = Batman() - - # Kiểm tra kiểu đối tượng - if isinstance(sup, Human): - print('I am human') - if isinstance(sup, Bat): - print('I am bat') - if type(sup) is Batman: - print('I am Batman') - - # Truy xuất thứ tự phương thức của các lớp cha (Method Resolution search Order), vốn được dùng bởi cả getattr() và super9) - # Thuộc tính này động và có thể được cập nhật - print(Batman.__mro__) # => (, , , ) - - # Gọi phương thức của lớp cha nhưng dùng thuộc tính trên chính lớp hiện tại - print(sup.get_species()) # => Superhero - - # Gọi phương thức được nạp chồng - print(sup.sing()) # => nan nan nan nan nan batman! - - # Gọi phương thức của Human, bởi vì thứ tự thừa kế ảnh hưởng đến phương thức được gọi - sup.say('I agree') # => Sad Affleck: I agree - - # Gọi phương thức chỉ tồn tại ở lớp cha thứ 2 - print(sup.sonar()) # => ))) ... ((( - - # Thuộc tính cấp lớp được thừa kế - sup.age = 100 - print(sup.age) - - # Thuộc tính thừa kế từ lớp cha thứ 2 có giá trị mặc định đã bị ghi đè - print('Can I fly? ' + str(sup.fly)) - - - -#################################################### -## 7. Phần nâng cao -#################################################### - -# Generator giúp ta viết những đoạn code lười biếng (áp dụng nguyên tắc lazy evaluation) -def double_numbers(iterable): - for i in iterable: - yield i + i - -# Generators tiết kiệm bộ nhớ vì nó chỉ tải dữ liệu khi cần -# xử lý giá trị kế tiếp của một đối tượng khả lặp. Điều này cho phép generator thực hiện -# những thao tác mà bình thường không làm được trên những khoảng giá trị lớn -# Lưu ý: `range` thay thế `xrange` trong Python3. - -for i in double_numbers(range(1, 900000000)): # `range` là một generator. - print(i) - if i >= 30: - break - -# Cũng như danh sách có list comprehension, generator cũng có generator -# comprehension -values = (-x for x in [1,2,3,4,5]) -for x in values: - print(x) # in -1 -2 -3 -4 -5 ra màn hình dòng lệnh - -# Một generator cũng có thể bị ép kiểu thành danh sách -values = (-x for x in [1,2,3,4,5]) -gen_to_list = list(values) -print(gen_to_list) # => [-1, -2, -3, -4, -5] - - -# Decorators -# Trong ví dụ này hàm `beg` 'phủ lên' hàm `say`. Nếu say_please là True thì nó -# sẽ thay đội giá trị trả về -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Làm ơn! Tui rất nghèo :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Mua bia cho tui nhé?" - return msg, say_please - - -print(say()) # Mua bia cho tui nhé? -print(say(say_please=True)) # Mua bia cho tui nhé? Làm ơn! Tui rất nghèo :( -``` - -## Sẵn sàng để học nhiều hơn? - -### Miễn phí trên mạng - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) -* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) -* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) -* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) -* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) -* [Dive Into Python 3](http://www.diveintopython3.net/index.html) -* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown new file mode 100644 index 00000000..fd962305 --- /dev/null +++ b/zh-cn/python-cn.html.markdown @@ -0,0 +1,632 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] +translators: + - ["Geoff Liu", "http://geoffliu.me"] +filename: learnpython3-cn.py +lang: zh-cn +--- + +Python 是由吉多·范罗苏姆(Guido Van Rossum)在 90 年代早期设计。 +它是如今最常用的编程语言之一。它的语法简洁且优美,几乎就是可执行的伪代码。 + +欢迎大家斧正。英文版原作 Louie Dinh [@louiedinh](http://twitter.com/louiedinh) +邮箱 louiedinh [at] [谷歌的信箱服务]。中文翻译 Geoff Liu。 + +注意:这篇教程是基于 Python 3 写的。如果你想学旧版 Python 2,我们特别有[另一篇教程](http://learnxinyminutes.com/docs/python/)。 + +```python + +# 用井字符开头的是单行注释 + +""" 多行字符串用三个引号 + 包裹,也常被用来做多 + 行注释 +""" + +#################################################### +## 1. 原始数据类型和运算符 +#################################################### + +# 整数 +3 # => 3 + +# 算术没有什么出乎意料的 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# 但是除法例外,会自动转换成浮点数 +35 / 5 # => 7.0 +5 / 3 # => 1.6666666666666667 + +# 整数除法的结果都是向下取整 +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # 浮点数也可以 +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# 浮点数的运算结果也是浮点数 +3 * 2.0 # => 6.0 + +# 模除 +7 % 3 # => 1 + +# x的y次方 +2**4 # => 16 + +# 用括号决定优先级 +(1 + 3) * 2 # => 8 + +# 布尔值 +True +False + +# 用not取非 +not True # => False +not False # => True + +# 逻辑运算符,注意and和or都是小写 +True and False # => False +False or True # => True + +# 整数也可以当作布尔值 +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True + +# 用==判断相等 +1 == 1 # => True +2 == 1 # => False + +# 用!=判断不等 +1 != 1 # => False +2 != 1 # => True + +# 比较大小 +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# 大小比较可以连起来! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# 字符串用单引双引都可以 +"这是个字符串" +'这也是个字符串' + +# 用加号连接字符串 +"Hello " + "world!" # => "Hello world!" + +# 字符串可以被当作字符列表 +"This is a string"[0] # => 'T' + +# 用.format来格式化字符串 +"{} can be {}".format("strings", "interpolated") + +# 可以重复参数以节省时间 +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# 如果不想数参数,可以用关键字 +"{name} wants to eat {food}".format(name="Bob", food="lasagna") +# => "Bob wants to eat lasagna" + +# 如果你的Python3程序也要在Python2.5以下环境运行,也可以用老式的格式化语法 +"%s can be %s the %s way" % ("strings", "interpolated", "old") + +# None是一个对象 +None # => None + +# 当与None进行比较时不要用 ==,要用is。is是用来比较两个变量是否指向同一个对象。 +"etc" is None # => False +None is None # => True + +# None,0,空字符串,空列表,空字典都算是False +# 所有其他值都是True +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False + + +#################################################### +## 2. 变量和集合 +#################################################### + +# print是内置的打印函数 +print("I'm Python. Nice to meet you!") + +# 在给变量赋值前不用提前声明 +# 传统的变量命名是小写,用下划线分隔单词 +some_var = 5 +some_var # => 5 + +# 访问未赋值的变量会抛出异常 +# 参考流程控制一段来学习异常处理 +some_unknown_var # 抛出NameError + +# 用列表(list)储存序列 +li = [] +# 创建列表时也可以同时赋给元素 +other_li = [4, 5, 6] + +# 用append在列表最后追加元素 +li.append(1) # li现在是[1] +li.append(2) # li现在是[1, 2] +li.append(4) # li现在是[1, 2, 4] +li.append(3) # li现在是[1, 2, 4, 3] +# 用pop从列表尾部删除 +li.pop() # => 3 且li现在是[1, 2, 4] +# 把3再放回去 +li.append(3) # li变回[1, 2, 4, 3] + +# 列表存取跟数组一样 +li[0] # => 1 +# 取出最后一个元素 +li[-1] # => 3 + +# 越界存取会造成IndexError +li[4] # 抛出IndexError + +# 列表有切割语法 +li[1:3] # => [2, 4] +# 取尾 +li[2:] # => [4, 3] +# 取头 +li[:3] # => [1, 2, 4] +# 隔一个取一个 +li[::2] # =>[1, 4] +# 倒排列表 +li[::-1] # => [3, 4, 2, 1] +# 可以用三个参数的任何组合来构建切割 +# li[始:终:步伐] + +# 用del删除任何一个元素 +del li[2] # li is now [1, 2, 3] + +# 列表可以相加 +# 注意:li和other_li的值都不变 +li + other_li # => [1, 2, 3, 4, 5, 6] + +# 用extend拼接列表 +li.extend(other_li) # li现在是[1, 2, 3, 4, 5, 6] + +# 用in测试列表是否包含值 +1 in li # => True + +# 用len取列表长度 +len(li) # => 6 + + +# 元组是不可改变的序列 +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # 抛出TypeError + +# 列表允许的操作元组大都可以 +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# 可以把元组合列表解包,赋值给变量 +a, b, c = (1, 2, 3) # 现在a是1,b是2,c是3 +# 元组周围的括号是可以省略的 +d, e, f = 4, 5, 6 +# 交换两个变量的值就这么简单 +e, d = d, e # 现在d是5,e是4 + + +# 用字典表达映射关系 +empty_dict = {} +# 初始化的字典 +filled_dict = {"one": 1, "two": 2, "three": 3} + +# 用[]取值 +filled_dict["one"] # => 1 + + +# 用 keys 获得所有的键。 +# 因为 keys 返回一个可迭代对象,所以在这里把结果包在 list 里。我们下面会详细介绍可迭代。 +# 注意:字典键的顺序是不定的,你得到的结果可能和以下不同。 +list(filled_dict.keys()) # => ["three", "two", "one"] + + +# 用values获得所有的值。跟keys一样,要用list包起来,顺序也可能不同。 +list(filled_dict.values()) # => [3, 2, 1] + + +# 用in测试一个字典是否包含一个键 +"one" in filled_dict # => True +1 in filled_dict # => False + +# 访问不存在的键会导致KeyError +filled_dict["four"] # KeyError + +# 用get来避免KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# 当键不存在的时候get方法可以返回默认值 +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# setdefault方法只有当键不存在的时候插入新值 +filled_dict.setdefault("five", 5) # filled_dict["five"]设为5 +filled_dict.setdefault("five", 6) # filled_dict["five"]还是5 + +# 字典赋值 +filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} +filled_dict["four"] = 4 # 另一种赋值方法 + +# 用del删除 +del filled_dict["one"] # 从filled_dict中把one删除 + + +# 用set表达集合 +empty_set = set() +# 初始化一个集合,语法跟字典相似。 +some_set = {1, 1, 2, 2, 3, 4} # some_set现在是{1, 2, 3, 4} + +# 可以把集合赋值于变量 +filled_set = some_set + +# 为集合添加元素 +filled_set.add(5) # filled_set现在是{1, 2, 3, 4, 5} + +# & 取交集 +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# | 取并集 +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# - 取补集 +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# in 测试集合是否包含元素 +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +## 3. 流程控制和迭代器 +#################################################### + +# 先随便定义一个变量 +some_var = 5 + +# 这是个if语句。注意缩进在Python里是有意义的 +# 印出"some_var比10小" +if some_var > 10: + print("some_var比10大") +elif some_var < 10: # elif句是可选的 + print("some_var比10小") +else: # else也是可选的 + print("some_var就是10") + + +""" +用for循环语句遍历列表 +打印: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + print("{} is a mammal".format(animal)) + +""" +"range(number)"返回数字列表从0到给的数字 +打印: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +while循环直到条件不满足 +打印: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # x = x + 1 的简写 + +# 用try/except块处理异常状况 +try: + # 用raise抛出异常 + raise IndexError("This is an index error") +except IndexError as e: + pass # pass是无操作,但是应该在这里处理错误 +except (TypeError, NameError): + pass # 可以同时处理不同类的错误 +else: # else语句是可选的,必须在所有的except之后 + print("All good!") # 只有当try运行完没有错误的时候这句才会运行 + + +# Python提供一个叫做可迭代(iterable)的基本抽象。一个可迭代对象是可以被当作序列 +# 的对象。比如说上面range返回的对象就是可迭代的。 + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => dict_keys(['one', 'two', 'three']),是一个实现可迭代接口的对象 + +# 可迭代对象可以遍历 +for i in our_iterable: + print(i) # 打印 one, two, three + +# 但是不可以随机访问 +our_iterable[1] # 抛出TypeError + +# 可迭代对象知道怎么生成迭代器 +our_iterator = iter(our_iterable) + +# 迭代器是一个可以记住遍历的位置的对象 +# 用__next__可以取得下一个元素 +our_iterator.__next__() # => "one" + +# 再一次调取__next__时会记得位置 +our_iterator.__next__() # => "two" +our_iterator.__next__() # => "three" + +# 当迭代器所有元素都取出后,会抛出StopIteration +our_iterator.__next__() # 抛出StopIteration + +# 可以用list一次取出迭代器所有的元素 +list(filled_dict.keys()) # => Returns ["one", "two", "three"] + + + +#################################################### +## 4. 函数 +#################################################### + +# 用def定义新函数 +def add(x, y): + print("x is {} and y is {}".format(x, y)) + return x + y # 用return语句返回 + +# 调用函数 +add(5, 6) # => 印出"x is 5 and y is 6"并且返回11 + +# 也可以用关键字参数来调用函数 +add(y=6, x=5) # 关键字参数可以用任何顺序 + + +# 我们可以定义一个可变参数函数 +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + + +# 我们也可以定义一个关键字可变参数函数 +def keyword_args(**kwargs): + return kwargs + +# 我们来看看结果是什么: +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# 这两种可变参数可以混着用 +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# 调用可变参数函数时可以做跟上面相反的,用*展开序列,用**展开字典。 +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # 相当于 foo(1, 2, 3, 4) +all_the_args(**kwargs) # 相当于 foo(a=3, b=4) +all_the_args(*args, **kwargs) # 相当于 foo(1, 2, 3, 4, a=3, b=4) + + +# 函数作用域 +x = 5 + +def setX(num): + # 局部作用域的x和全局域的x是不同的 + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # 现在全局域的x被赋值 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# 函数在Python是一等公民 +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# 也有匿名函数 +(lambda x: x > 2)(3) # => True + +# 内置的高阶函数 +map(add_10, [1, 2, 3]) # => [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# 用列表推导式可以简化映射和过滤。列表推导式的返回值是另一个列表。 +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. 类 +#################################################### + + +# 定义一个继承object的类 +class Human(object): + + # 类属性,被所有此类的实例共用。 + species = "H. sapiens" + + # 构造方法,当实例被初始化时被调用。注意名字前后的双下划线,这是表明这个属 + # 性或方法对Python有特殊意义,但是允许用户自行定义。你自己取名时不应该用这 + # 种格式。 + def __init__(self, name): + # Assign the argument to the instance's name attribute + self.name = name + + # 实例方法,第一个参数总是self,就是这个实例对象 + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # 类方法,被所有此类的实例共用。第一个参数是这个类对象。 + @classmethod + def get_species(cls): + return cls.species + + # 静态方法。调用时没有实例或类的绑定。 + @staticmethod + def grunt(): + return "*grunt*" + + +# 构造一个实例 +i = Human(name="Ian") +print(i.say("hi")) # 印出 "Ian: hi" + +j = Human("Joel") +print(j.say("hello")) # 印出 "Joel: hello" + +# 调用一个类方法 +i.get_species() # => "H. sapiens" + +# 改一个共用的类属性 +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# 调用静态方法 +Human.grunt() # => "*grunt*" + + +#################################################### +## 6. 模块 +#################################################### + +# 用import导入模块 +import math +print(math.sqrt(16)) # => 4.0 + +# 也可以从模块中导入个别值 +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# 可以导入一个模块中所有值 +# 警告:不建议这么做 +from math import * + +# 如此缩写模块名字 +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Python模块其实就是普通的Python文件。你可以自己写,然后导入, +# 模块的名字就是文件的名字。 + +# 你可以这样列出一个模块里所有的值 +import math +dir(math) + + +#################################################### +## 7. 高级用法 +#################################################### + +# 用生成器(generators)方便地写惰性运算 +def double_numbers(iterable): + for i in iterable: + yield i + i + +# 生成器只有在需要时才计算下一个值。它们每一次循环只生成一个值,而不是把所有的 +# 值全部算好。 +# +# range的返回值也是一个生成器,不然一个1到900000000的列表会花很多时间和内存。 +# +# 如果你想用一个Python的关键字当作变量名,可以加一个下划线来区分。 +range_ = range(1, 900000000) +# 当找到一个 >=30 的结果就会停 +# 这意味着 `double_numbers` 不会生成大于30的数。 +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# 装饰器(decorators) +# 这个例子中,beg装饰say +# beg会先调用say。如果返回的say_please为真,beg会改变返回的字符串。 +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # Can you buy me a beer? +print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( +``` + +## 想继续学吗? + +### 线上免费材料(英文) + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) + +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/3/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +### 书籍(也是英文) + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown deleted file mode 100644 index fd962305..00000000 --- a/zh-cn/python3-cn.html.markdown +++ /dev/null @@ -1,632 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] -translators: - - ["Geoff Liu", "http://geoffliu.me"] -filename: learnpython3-cn.py -lang: zh-cn ---- - -Python 是由吉多·范罗苏姆(Guido Van Rossum)在 90 年代早期设计。 -它是如今最常用的编程语言之一。它的语法简洁且优美,几乎就是可执行的伪代码。 - -欢迎大家斧正。英文版原作 Louie Dinh [@louiedinh](http://twitter.com/louiedinh) -邮箱 louiedinh [at] [谷歌的信箱服务]。中文翻译 Geoff Liu。 - -注意:这篇教程是基于 Python 3 写的。如果你想学旧版 Python 2,我们特别有[另一篇教程](http://learnxinyminutes.com/docs/python/)。 - -```python - -# 用井字符开头的是单行注释 - -""" 多行字符串用三个引号 - 包裹,也常被用来做多 - 行注释 -""" - -#################################################### -## 1. 原始数据类型和运算符 -#################################################### - -# 整数 -3 # => 3 - -# 算术没有什么出乎意料的 -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 - -# 但是除法例外,会自动转换成浮点数 -35 / 5 # => 7.0 -5 / 3 # => 1.6666666666666667 - -# 整数除法的结果都是向下取整 -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # 浮点数也可以 --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# 浮点数的运算结果也是浮点数 -3 * 2.0 # => 6.0 - -# 模除 -7 % 3 # => 1 - -# x的y次方 -2**4 # => 16 - -# 用括号决定优先级 -(1 + 3) * 2 # => 8 - -# 布尔值 -True -False - -# 用not取非 -not True # => False -not False # => True - -# 逻辑运算符,注意and和or都是小写 -True and False # => False -False or True # => True - -# 整数也可以当作布尔值 -0 and 2 # => 0 --5 or 0 # => -5 -0 == False # => True -2 == True # => False -1 == True # => True - -# 用==判断相等 -1 == 1 # => True -2 == 1 # => False - -# 用!=判断不等 -1 != 1 # => False -2 != 1 # => True - -# 比较大小 -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# 大小比较可以连起来! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# 字符串用单引双引都可以 -"这是个字符串" -'这也是个字符串' - -# 用加号连接字符串 -"Hello " + "world!" # => "Hello world!" - -# 字符串可以被当作字符列表 -"This is a string"[0] # => 'T' - -# 用.format来格式化字符串 -"{} can be {}".format("strings", "interpolated") - -# 可以重复参数以节省时间 -"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" - -# 如果不想数参数,可以用关键字 -"{name} wants to eat {food}".format(name="Bob", food="lasagna") -# => "Bob wants to eat lasagna" - -# 如果你的Python3程序也要在Python2.5以下环境运行,也可以用老式的格式化语法 -"%s can be %s the %s way" % ("strings", "interpolated", "old") - -# None是一个对象 -None # => None - -# 当与None进行比较时不要用 ==,要用is。is是用来比较两个变量是否指向同一个对象。 -"etc" is None # => False -None is None # => True - -# None,0,空字符串,空列表,空字典都算是False -# 所有其他值都是True -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False - - -#################################################### -## 2. 变量和集合 -#################################################### - -# print是内置的打印函数 -print("I'm Python. Nice to meet you!") - -# 在给变量赋值前不用提前声明 -# 传统的变量命名是小写,用下划线分隔单词 -some_var = 5 -some_var # => 5 - -# 访问未赋值的变量会抛出异常 -# 参考流程控制一段来学习异常处理 -some_unknown_var # 抛出NameError - -# 用列表(list)储存序列 -li = [] -# 创建列表时也可以同时赋给元素 -other_li = [4, 5, 6] - -# 用append在列表最后追加元素 -li.append(1) # li现在是[1] -li.append(2) # li现在是[1, 2] -li.append(4) # li现在是[1, 2, 4] -li.append(3) # li现在是[1, 2, 4, 3] -# 用pop从列表尾部删除 -li.pop() # => 3 且li现在是[1, 2, 4] -# 把3再放回去 -li.append(3) # li变回[1, 2, 4, 3] - -# 列表存取跟数组一样 -li[0] # => 1 -# 取出最后一个元素 -li[-1] # => 3 - -# 越界存取会造成IndexError -li[4] # 抛出IndexError - -# 列表有切割语法 -li[1:3] # => [2, 4] -# 取尾 -li[2:] # => [4, 3] -# 取头 -li[:3] # => [1, 2, 4] -# 隔一个取一个 -li[::2] # =>[1, 4] -# 倒排列表 -li[::-1] # => [3, 4, 2, 1] -# 可以用三个参数的任何组合来构建切割 -# li[始:终:步伐] - -# 用del删除任何一个元素 -del li[2] # li is now [1, 2, 3] - -# 列表可以相加 -# 注意:li和other_li的值都不变 -li + other_li # => [1, 2, 3, 4, 5, 6] - -# 用extend拼接列表 -li.extend(other_li) # li现在是[1, 2, 3, 4, 5, 6] - -# 用in测试列表是否包含值 -1 in li # => True - -# 用len取列表长度 -len(li) # => 6 - - -# 元组是不可改变的序列 -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # 抛出TypeError - -# 列表允许的操作元组大都可以 -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# 可以把元组合列表解包,赋值给变量 -a, b, c = (1, 2, 3) # 现在a是1,b是2,c是3 -# 元组周围的括号是可以省略的 -d, e, f = 4, 5, 6 -# 交换两个变量的值就这么简单 -e, d = d, e # 现在d是5,e是4 - - -# 用字典表达映射关系 -empty_dict = {} -# 初始化的字典 -filled_dict = {"one": 1, "two": 2, "three": 3} - -# 用[]取值 -filled_dict["one"] # => 1 - - -# 用 keys 获得所有的键。 -# 因为 keys 返回一个可迭代对象,所以在这里把结果包在 list 里。我们下面会详细介绍可迭代。 -# 注意:字典键的顺序是不定的,你得到的结果可能和以下不同。 -list(filled_dict.keys()) # => ["three", "two", "one"] - - -# 用values获得所有的值。跟keys一样,要用list包起来,顺序也可能不同。 -list(filled_dict.values()) # => [3, 2, 1] - - -# 用in测试一个字典是否包含一个键 -"one" in filled_dict # => True -1 in filled_dict # => False - -# 访问不存在的键会导致KeyError -filled_dict["four"] # KeyError - -# 用get来避免KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# 当键不存在的时候get方法可以返回默认值 -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 - -# setdefault方法只有当键不存在的时候插入新值 -filled_dict.setdefault("five", 5) # filled_dict["five"]设为5 -filled_dict.setdefault("five", 6) # filled_dict["five"]还是5 - -# 字典赋值 -filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} -filled_dict["four"] = 4 # 另一种赋值方法 - -# 用del删除 -del filled_dict["one"] # 从filled_dict中把one删除 - - -# 用set表达集合 -empty_set = set() -# 初始化一个集合,语法跟字典相似。 -some_set = {1, 1, 2, 2, 3, 4} # some_set现在是{1, 2, 3, 4} - -# 可以把集合赋值于变量 -filled_set = some_set - -# 为集合添加元素 -filled_set.add(5) # filled_set现在是{1, 2, 3, 4, 5} - -# & 取交集 -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# | 取并集 -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# - 取补集 -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# in 测试集合是否包含元素 -2 in filled_set # => True -10 in filled_set # => False - - -#################################################### -## 3. 流程控制和迭代器 -#################################################### - -# 先随便定义一个变量 -some_var = 5 - -# 这是个if语句。注意缩进在Python里是有意义的 -# 印出"some_var比10小" -if some_var > 10: - print("some_var比10大") -elif some_var < 10: # elif句是可选的 - print("some_var比10小") -else: # else也是可选的 - print("some_var就是10") - - -""" -用for循环语句遍历列表 -打印: - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - print("{} is a mammal".format(animal)) - -""" -"range(number)"返回数字列表从0到给的数字 -打印: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -while循环直到条件不满足 -打印: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # x = x + 1 的简写 - -# 用try/except块处理异常状况 -try: - # 用raise抛出异常 - raise IndexError("This is an index error") -except IndexError as e: - pass # pass是无操作,但是应该在这里处理错误 -except (TypeError, NameError): - pass # 可以同时处理不同类的错误 -else: # else语句是可选的,必须在所有的except之后 - print("All good!") # 只有当try运行完没有错误的时候这句才会运行 - - -# Python提供一个叫做可迭代(iterable)的基本抽象。一个可迭代对象是可以被当作序列 -# 的对象。比如说上面range返回的对象就是可迭代的。 - -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) # => dict_keys(['one', 'two', 'three']),是一个实现可迭代接口的对象 - -# 可迭代对象可以遍历 -for i in our_iterable: - print(i) # 打印 one, two, three - -# 但是不可以随机访问 -our_iterable[1] # 抛出TypeError - -# 可迭代对象知道怎么生成迭代器 -our_iterator = iter(our_iterable) - -# 迭代器是一个可以记住遍历的位置的对象 -# 用__next__可以取得下一个元素 -our_iterator.__next__() # => "one" - -# 再一次调取__next__时会记得位置 -our_iterator.__next__() # => "two" -our_iterator.__next__() # => "three" - -# 当迭代器所有元素都取出后,会抛出StopIteration -our_iterator.__next__() # 抛出StopIteration - -# 可以用list一次取出迭代器所有的元素 -list(filled_dict.keys()) # => Returns ["one", "two", "three"] - - - -#################################################### -## 4. 函数 -#################################################### - -# 用def定义新函数 -def add(x, y): - print("x is {} and y is {}".format(x, y)) - return x + y # 用return语句返回 - -# 调用函数 -add(5, 6) # => 印出"x is 5 and y is 6"并且返回11 - -# 也可以用关键字参数来调用函数 -add(y=6, x=5) # 关键字参数可以用任何顺序 - - -# 我们可以定义一个可变参数函数 -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - - -# 我们也可以定义一个关键字可变参数函数 -def keyword_args(**kwargs): - return kwargs - -# 我们来看看结果是什么: -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# 这两种可变参数可以混着用 -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) prints: - (1, 2) - {"a": 3, "b": 4} -""" - -# 调用可变参数函数时可以做跟上面相反的,用*展开序列,用**展开字典。 -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # 相当于 foo(1, 2, 3, 4) -all_the_args(**kwargs) # 相当于 foo(a=3, b=4) -all_the_args(*args, **kwargs) # 相当于 foo(1, 2, 3, 4, a=3, b=4) - - -# 函数作用域 -x = 5 - -def setX(num): - # 局部作用域的x和全局域的x是不同的 - x = num # => 43 - print (x) # => 43 - -def setGlobalX(num): - global x - print (x) # => 5 - x = num # 现在全局域的x被赋值 - print (x) # => 6 - -setX(43) -setGlobalX(6) - - -# 函数在Python是一等公民 -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# 也有匿名函数 -(lambda x: x > 2)(3) # => True - -# 内置的高阶函数 -map(add_10, [1, 2, 3]) # => [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] - -# 用列表推导式可以简化映射和过滤。列表推导式的返回值是另一个列表。 -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -#################################################### -## 5. 类 -#################################################### - - -# 定义一个继承object的类 -class Human(object): - - # 类属性,被所有此类的实例共用。 - species = "H. sapiens" - - # 构造方法,当实例被初始化时被调用。注意名字前后的双下划线,这是表明这个属 - # 性或方法对Python有特殊意义,但是允许用户自行定义。你自己取名时不应该用这 - # 种格式。 - def __init__(self, name): - # Assign the argument to the instance's name attribute - self.name = name - - # 实例方法,第一个参数总是self,就是这个实例对象 - def say(self, msg): - return "{name}: {message}".format(name=self.name, message=msg) - - # 类方法,被所有此类的实例共用。第一个参数是这个类对象。 - @classmethod - def get_species(cls): - return cls.species - - # 静态方法。调用时没有实例或类的绑定。 - @staticmethod - def grunt(): - return "*grunt*" - - -# 构造一个实例 -i = Human(name="Ian") -print(i.say("hi")) # 印出 "Ian: hi" - -j = Human("Joel") -print(j.say("hello")) # 印出 "Joel: hello" - -# 调用一个类方法 -i.get_species() # => "H. sapiens" - -# 改一个共用的类属性 -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" - -# 调用静态方法 -Human.grunt() # => "*grunt*" - - -#################################################### -## 6. 模块 -#################################################### - -# 用import导入模块 -import math -print(math.sqrt(16)) # => 4.0 - -# 也可以从模块中导入个别值 -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# 可以导入一个模块中所有值 -# 警告:不建议这么做 -from math import * - -# 如此缩写模块名字 -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Python模块其实就是普通的Python文件。你可以自己写,然后导入, -# 模块的名字就是文件的名字。 - -# 你可以这样列出一个模块里所有的值 -import math -dir(math) - - -#################################################### -## 7. 高级用法 -#################################################### - -# 用生成器(generators)方便地写惰性运算 -def double_numbers(iterable): - for i in iterable: - yield i + i - -# 生成器只有在需要时才计算下一个值。它们每一次循环只生成一个值,而不是把所有的 -# 值全部算好。 -# -# range的返回值也是一个生成器,不然一个1到900000000的列表会花很多时间和内存。 -# -# 如果你想用一个Python的关键字当作变量名,可以加一个下划线来区分。 -range_ = range(1, 900000000) -# 当找到一个 >=30 的结果就会停 -# 这意味着 `double_numbers` 不会生成大于30的数。 -for i in double_numbers(range_): - print(i) - if i >= 30: - break - - -# 装饰器(decorators) -# 这个例子中,beg装饰say -# beg会先调用say。如果返回的say_please为真,beg会改变返回的字符串。 -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please - - -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( -``` - -## 想继续学吗? - -### 线上免费材料(英文) - -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) - -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/3/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) - -### 书籍(也是英文) - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) - -- cgit v1.2.3