Skip to content

3. الأساسيات

  

3.1. مثال على برنامج بيثون

فيما يلي برنامج يوضح الميزات الأساسية لـ Python.


البرنامج (bases_01)

#    -*- coding=utf-8 -*-

# ----------------------------------
def affiche(chaine):
    #    chain poster
    print "chaine=%s" % (chaine)


# ----------------------------------
def afficheType(variable):
    #    displays variable type
    print "type[%s]=%s" % (variable,type(variable))

# ----------------------------------
def f1(param):
    #    add 10 to param
    return param+10

# ----------------------------------
def f2():
    #  returns 3 values
    return ("un",0,100);


#    -------------------------------- main program ------------------------------------
#  this is a comment
#    variable used without being declared
nom="dupont"

#    a screen display
print "nom=%s" % (nom)

#  a list with elements of different types
liste=["un","deux",3,4]

#  its number of elements
n=len(liste)

#    a loop
for i in range(n):
  print "liste[%d]=%s" % (i,liste[i])

#  initialize 2 variables with a tuple
(chaine1,chaine2)=("chaine1","chaine2")

#  concatenation of the 2 strings
chaine3=chaine1+chaine2

#    result display
print "[%s,%s,%s]" % (chaine1,chaine2,chaine3)

#  use function
affiche(chaine1)

#  the type of a variable can be known
afficheType(n)
afficheType(chaine1)
afficheType(liste)

#  the type of a variable can change at runtime
n="a change"
afficheType(n)

#    a function can return a result
res1=f1(4)
print "res1=%s" % (res1)

#  a function can return a list of values
(res1,res2,res3)=f2()
print "(res1,res2,res3)=[%s,%s,%s]" % (res1,res2,res3)

#  we could have retrieved these values in a
liste=f2()
for i in range(len(liste)):
    print "liste[%s]=%s" % (i, liste[i])

#    testing
for i in range(len(liste)):
    #    displays only channels
    if (type(liste[i])=="str"):
        print "liste[%s]=%s" % (i,liste[i])

#    other tests
for i in range(len(liste)):
    #    displays only integers >10
    if (type(liste[i])=="int" and liste[i]>10):
        print "liste[%s]=%s" % (i,liste[i])

#    a while loop
liste=(8,5,0,-2,3,4)
i=0
somme=0
while(i<len(liste) and liste[i]>0):
    print "liste[%s]=%s" % (i,liste[i])
    somme+=liste[i] #   sum=sum+t[i]
    i+=1 #   i=i+1
print "somme=%s" % (somme)
#    end of program

ملاحظة:

  • السطر 1: تعليق خاص يستخدم لإعلان نوع ترميز البرنامج النصي، وهو هنا UTF-8. يعتمد هذا على محرر النصوص المستخدم. هنا مع Notepad++:
 
  • السطر 4: الكلمة الرئيسية def تُعرّف دالة؛
  • السطران 5-6: نص الدالة. يتم وضع مسافة بادئة واحدة إلى اليمين. هذه المسافة البادئة، مقترنة بالنقطتين (:) في عبارة def، تحدد نص الدالة. ينطبق هذا على جميع العبارات التي تحتوي على نص: if، else، while، for، try، except؛
  • السطر 12: تدير Python أنواع المتغيرات داخليًا. يمكنك تحديد نوع المتغير باستخدام الدالة type(variable)، التي تُرجع متغيرًا من النوع 'type'. التعبير '%s' % (type(variable)) هو سلسلة تمثل نوع المتغير؛
  • السطر 25: البرنامج الرئيسي. يأتي هذا بعد تعريف جميع دوال البرنامج النصي. محتواه غير مسنن؛
  • السطر 28: في Python، لا تقوم بإعلان المتغيرات. Python حساسة لحالة الأحرف. المتغير Nom يختلف عن المتغير nom*. يمكن وضع السلسلة بين علامتي اقتباس مزدوجتين " أو علامتي اقتباس مفردة '. لذا يمكنك كتابة 'dupont' أو "dupont*"؛
  • السطر 31: التعبير "xxxx%syyyy%szzzz" % (100, 200) هو السلسلة "xxxx100yyy200szzzz" حيث تم استبدال كل %s بعنصر من التوبول. %s هو محدد تنسيق السلسلة. هناك تنسيقات أخرى؛
  • السطر 34: هناك فرق بين التوبول (1,2,3) (لاحظ الأقواس) والقائمة [1,2,3] (لاحظ الأقواس المربعة). التوبول غير قابل للتغيير، في حين أن القائمة قابلة للتغيير. في كلتا الحالتين، يُشار إلى العنصر رقم i بـ [i]؛
  • السطر 40: range(n) هو التوبول (0,1,2,...,n-1
  • السطر 74: len(var) هو عدد العناصر في المجموعة var (توبول، قائمة، قاموس، ...)؛
  • السطر 86: العوامل المنطقية الأخرى هي or و not.

يكون إخراج الشاشة كما يلي:

nom=dupont
liste[0]=un
liste[1]=deux
liste[2]=3
liste[3]=4
[chaine1,chaine2,chaine1chaine2]
chaine=chaine1
type[4]=<type 'int'>
type[chaine1]=<type 'str'>
type[['un', 'deux', 3, 4]]=<type 'list'>
type[a change]=<type 'str'>
res1=14
(res1,res2,res3)=[un,0,100]
liste[0]=un
liste[1]=0
liste[2]=100
liste[0]=8
liste[1]=5
somme=13

3.2. تحويلات الأنواع

نركز هنا على تحويلات الأنواع التي تتضمن بيانات من نوع str (سلسلة)، و int (عدد صحيح)، و float (عدد عائم)، و bool (منطقية).


البرنامج (bases_01b)

#   -*- coding=utf-8 -*-

#   type changes
#   int --> str, float, bool
x=4
print x, type(x)
x=str(4)
print x, type(x)
x=float(4)
print x, type(x)
x=bool(4)
print x, type(x)

#   bool --> int, float, str
x=True
print x, type(x)
x=int(True)
print x, type(x)
x=float(True)
print x, type(x)
x=str(True)
print x, type(x)

#   str --> int, float, bool
x="4"
print x, type(x)
x=int("4")
print x, type(x)
x=float("4")
print x, type(x)
x=bool("4")
print x, type(x)

#   float --> str, int, bool
x=4.32
print x, type(x)
x=str(4.32)
print x, type(x)
x=int(4.32)
print x, type(x)
x=bool(4.32)
print x, type(x)

#  type change error handling
try:
    x=int("abc")
    print x, type(x)
except ValueError, erreur:
    print erreur

#   various Boolean cases
x=bool("abc")
print x, type(x)
x=bool("")
print x, type(x)
x=bool(0)
print x, type(x)
x=None
print x, type(x)
x=bool(None)
print x, type(x)

هناك العديد من عمليات تحويل الأنواع الممكنة. قد تفشل بعضها، مثل تلك الموجودة في الأسطر 45–49، التي تحاول تحويل السلسلة 'abc' إلى عدد صحيح. تعاملنا مع الخطأ باستخدام كتلة try/except. الشكل العام لهذه الكتلة هو كما يلي:


try:
    actions
except Exception, Message:
    actions
finally:
    actions

إذا ألقى أي من الإجراءات داخل كتلة try استثناءً (أشار إلى خطأ)، ينتقل التحكم فورًا إلى جملة **except. إذا لم تلقِ الإجراءات داخل كتلة try استثناءً، يتم تجاهل جملة except. تعد سمات Exception و Message في جملة except اختيارية. عند وجودها، تحدد Exception نوع الاستثناء الذي تم التقاطه بواسطة جملة except، وتحتوي Message على رسالة الخطأ المرتبطة بالاستثناء. يمكن أن يكون هناك عدة جمل except إذا كنت ترغب في معالجة أنواع مختلفة من الاستثناءات داخل نفس كتلة try.

جملة finally اختيارية. إذا كانت موجودة، يتم دائمًا تنفيذ الإجراءات الموجودة في كتلة finally، بغض النظر عما إذا حدث استثناء أم لا.

سنعود إلى الاستثناءات لاحقًا.

تُظهر الأسطر من 52 إلى 61 محاولات مختلفة لتحويل البيانات من أنواع str و int و float و NoneType إلى نوع boolean. وهذا أمر ممكن دائمًا. والقواعد هي كما يلي:

  • bool(int i) تساوي False إذا كانت i تساوي 0، وتساوي True في جميع الحالات الأخرى؛
  • bool(float f) يساوي False إذا كان f يساوي 0.0، ويساوي True في جميع الحالات الأخرى؛
  • bool(str string) يساوي False إذا كان string يحتوي على 0 حرف، ويساوي True في جميع الحالات الأخرى؛
  • bool(None) يساوي False. None هو قيمة خاصة تعني أن المتغير موجود ولكن ليس له قيمة.

يكون إخراج الشاشة كما يلي:

4 <type 'int'>
4 <type 'str'>
4.0 <type 'float'>
True <type 'bool'>
True <type 'bool'>
1 <type 'int'>
1.0 <type 'float'>
True <type 'str'>
4 <type 'str'>
4 <type 'int'>
4.0 <type 'float'>
True <type 'bool'>
4.32 <type 'float'>
4.32 <type 'str'>
4 <type 'int'>
True <type 'bool'>
invalid literal for int() with base 10: 'abc'
True <type 'bool'>
False <type 'bool'>
False <type 'bool'>
None <type 'NoneType'>
False <type 'bool'>
False <type 'bool'>

3.3. نطاق المتغيرات


البرنامج (bases_02)

#    -*- coding=utf-8 -*-

#    variable scope
def f1():
    #  we use the global variable i
    global i
    i+=1
    j=10
    print "f1[i,j]=[%s,%s]" % (i,j)

def f2():
    #  we use the global variable i
    global i
    i+=1
    j=20
    print "f2[i,j]=[%s,%s]" % (i,j)

def f3():
    #  we use a local variable i
    i=1
    j=30
    print "f3[i,j]=[%s,%s]" % (i,j)

#    tests
i=0
j=0 #  these two variables are known only to a function f
    #  only if it explicitly declares with the global instruction
    #  she wants to use them
f1()
f2()
f3()
print "test[i,j]=[%s,%s]" % (i,j)

النتائج

1
2
3
4
f1[i,j]=[1,10]
f2[i,j]=[2,20]
f3[i,j]=[1,30]
test[i,j]=[2,0]

ملاحظات:

  • يوضح البرنامج النصي استخدام المتغير i، الذي تم تعريفه كمتغير عام في الدالتين f1 وf2. في هذه الحالة، يتشارك البرنامج الرئيسي والدالتين f1 وf2 في استخدام المتغير i.

3.4. القوائم والمجموعات والقواميس

3.4.1. القوائم أحادية البعد


البرنامج (bases_03)

#   -*- coding=utf-8 -*-

#   1-dimensional lists
#   initialization
list1=[0,1,2,3,4,5]

#   routes - 1
print "list1 a %s elements" % (len(list1))
for i in range(len(list1)):
    print "list1[%s]=%s" % (i, list1[i])

list1[1]=10;
#   routes - 2
print "list1 a %s elements" % (len(list1))
for element in list1:
    print element

#   addition of two elements
list1[len(list1):]=[10,11]
print ("%s") % (list1)

#   deletion of last two items
list1[len(list1)-2:]=[]
print ("%s") % (list1)

#  addition at the beginning of a tuple list
list1[:0]=[-10, -11, -12]
print ("%s") % (list1)

#   mid-list insertion of two elements
list1[3:3]=[100,101]
print ("%s") % (list1)

#  deletion of two items in the middle of a list
list1[3:4]=[]
print ("%s") % (list1)

ملاحظات:

  • تشير الصيغة array[i:j] إلى العناصر من i إلى j-1 في المصفوفة؛
  • يشير الترميز [i:] إلى العناصر من i وما يليها في المصفوفة؛
  • يشير الترميز [:i] إلى العناصر من 0 إلى i-1 في القائمة؛
  • السطر 20: print (%s) % (list1) يعرض السلسلة: "[ list1[0], list1[2], ..., list1[n-1]]".

النتائج

list1 a 6 elements
list1[0]=0
list1[1]=1
list1[2]=2
list1[3]=3
list1[4]=4
list1[5]=5
list1 a 6 elements
0
10
2
3
4
5
[0, 10, 2, 3, 4, 5, 10, 11]
[0, 10, 2, 3, 4, 5]
[-10, -11, -12, 0, 10, 2, 3, 4, 5]
[-10, -11, -12, 100, 101, 0, 10, 2, 3, 4, 5]
[-10, -11, -12, 101, 0, 10, 2, 3, 4, 5]

يمكن كتابة الكود السابق بطريقة مختلفة (bases_03b) باستخدام طرق قائمة معينة:

#   -*- coding=utf-8 -*-

#   1-dimensional lists

#   initialization
list1=[0,1,2,3,4,5]

#   routes - 1
print "list1 a %s elements" % (len(list1))
for i in range(len(list1)):
    print "list1[%s]=%s" % (i, list1[i])

list1[1]=10
#   routes - 2
print "list1 a %s elements" % (len(list1))
for element in list1:
    print element

#   addition of two elements
list1.extend([10,11])
print ("%s") % (list1)

#   deletion of last two items
del list1[len(list1)-2:]
print ("%s") % (list1)

#  addition at the beginning of a tuple list
for i in (-12, -11, -10):
    list1.insert(0,i)
print ("%s") % (list1)

#   mid-list insertion
for i in (101,100):
    list1.insert(3,i)
print ("%s") % (list1)

#   mid-list deletion
del list1[3:4]
print ("%s") % (list1)

النتائج هي نفسها كما في الإصدار السابق.

3.4.2. القاموس


البرنامج (bases_04)

#    -*- coding=utf-8 -*-

def existe(conjoints,mari):
    #  checks whether the husband key exists in the joint dictionary
    if(conjoints.has_key(mari)):
        print "La cle [%s] existe associee a la valeur [%s]" % (mari, conjoints[mari])
    else:
        print "La cle [%s] n'existe pas" % (mari)


#    ----------------------------- Main
#    dictionaries
conjoints={"Pierre":"Gisele", "Paul":"Virginie", "Jacques":"Lucette","Jean":""}

#    routes - 1
print "Nombre d'elements du dictionnaire : %s " % (len(conjoints))
for (cle,valeur) in conjoints.items():
    print "conjoints[%s]=%s" % (cle,valeur)

#    list of dictionary keys
print "liste des cles-------------"
cles=conjoints.keys()
print ("%s") % (cles)

#  list of dictionary values
print "liste des valeurs------------"
valeurs=conjoints.values()
print ("%s") % (valeurs)

#    key search
existe(conjoints,"Jacques")
existe(conjoints,"Lucette")
existe(conjoints,"Jean")

#  deleting a key-value
del (conjoints["Jean"])
print "Nombre d'elements du dictionnaire : %s " % (len(conjoints))
print ("%s") % (conjoints)

ملاحظات:

  • السطر 17: تعيد couples.items() قائمة أزواج (المفتاح، القيمة) في قاموس couples؛
  • السطر 22: تُرجع conjoints.keys() مفاتيح قاموس conjoints؛
  • السطر 27: تُرجع conjoints.values() قيم قاموس conjoints؛
  • السطر 7: spouses.has_key(husband) تُرجع True إذا كان المفتاح husband موجودًا في قاموس spouses، وإلا تُرجع False؛
  • السطر 38: يمكن عرض القاموس في سطر واحد.

النتائج

Nombre d'elements du dictionnaire : 4
conjoints[Paul]=Virginie
conjoints[Jean]=
conjoints[Pierre]=Gisele
conjoints[Jacques]=Lucette
liste des cles-------------
['Paul', 'Jean', 'Pierre', 'Jacques']
liste des valeurs------------
['Virginie', '', 'Gisele', 'Lucette']
La cle [Jacques] existe associee a la valeur [Lucette]
La cle [Lucette] n'existe pas
La cle [Jean] existe associee a la valeur []
Nombre d'elements du dictionnaire : 3
{'Paul': 'Virginie', 'Pierre': 'Gisele', 'Jacques': 'Lucette'}

3.4.3. المجموعات


البرنامج (bases_05)

#   -*- coding=utf-8 -*-

#   tuples
#   initialization
tab1=(0,1,2,3,4,5)

#   routes - 1
print "tab1 a %s elements" % (len(tab1))
for i in range(len(tab1)):
    print "tab1[%s]=%s" % (i, tab1[i])

#   routes - 2
print "tab1 a %s elements" % (len(tab1))
for element in tab1:
    print element

#   element modification
tab1[0]=-1


النتائج

tab1 a 6 elements
tab1[0]=0
tab1[1]=1
tab1[2]=2
tab1[3]=3
tab1[4]=4
tab1[5]=5
tab1 a 6 elements
0
1
2
3
4
5
Traceback (most recent call last):
  File "exemple_05.py", line 18, in <module>
    tab1[0]=-1
TypeError: 'tuple' object does not support item assignment

ملاحظات:

  • الأسطر 15–18 من النتائج: توضح أنه لا يمكن تعديل التوبول.

3.4.4. القوائم متعددة الأبعاد


البرنامج (bases_06)

#   -*- coding=utf-8 -*-

#   multidimensional lists

#   initialization
multi=[[0,1,2], [10,11,12,13], [20,21,22,23,24]]

#   route
for i1 in range(len(multi)):
    for i2 in range(len(multi[i1])):
        print "multi[%s][%s]=%s" % (i1,i2,multi[i1][i2])

#   multidimensional dictionaries
#   initialization
multi={"zero":[0,1], "un":[10,11,12,13], "deux":[20,21,22,23,24]}

#   route
for (cle,valeur) in multi.items():
    for i2 in range(len(multi[cle])):
        print "multi[%s][%s]=%s" % (cle,i2,multi[cle][i2])

النتائج

multi[0][0]=0
multi[0][1]=1
multi[0][2]=2
multi[1][0]=10
multi[1][1]=11
multi[1][2]=12
multi[1][3]=13
multi[2][0]=20
multi[2][1]=21
multi[2][2]=22
multi[2][3]=23
multi[2][4]=24
multi[zero][0]=0
multi[zero][1]=1
multi[un][0]=10
multi[un][1]=11
multi[un][2]=12
multi[un][3]=13
multi[deux][0]=20
multi[deux][1]=21
multi[deux][2]=22
multi[deux][3]=23
multi[deux][4]=24

3.4.5. الروابط بين السلاسل والقوائم


البرنامج (bases_07)


# -*- coding=Utf-8 -*-
 
# chaîne vers liste
chaine='1:2:3:4'
tab=chaine.split(':')
print type(tab)
 
# affichage liste
print "tab a %s elements" % (len(tab))
print ("%s") % (tab)
 
# liste vers chaîne
chaine2=":".join(tab)
print "chaine2=%s" % (chaine2)
 
# ajoutons un champ vide
chaine+=":"
print "chaine=%s" % (chaine)
tab=chaine.split(":")
 
# affichage liste
print "tab a %s elements" % (len(tab))
print ("%s") % (tab)
 
# ajoutons de nouveau un champ vide
chaine+=":"
print "chaine=%s" % (chaine)
tab=chaine.split(":")
 
# affichage liste
print "tab a %s elements" % (len(tab))
print ("%s") % (tab)
 

ملاحظات:

  • السطر 5: تقوم الطريقة string.split(separator) بتقسيم السلسلة string إلى عناصر مفصولة بفاصل separator وتُرجعها كقائمة. وبالتالي، فإن التعبير '1:2:3:4'.split(":") يُرجع القائمة ('1','2','3','4')؛
  • السطر 13: تُرجع 'separator'.join(list) السلسلة 'list[0]+separator+list[1]+separator+...'.

النتائج

<type 'list'>
tab a 4 elements
['1', '2', '3', '4']
chaine2=1:2:3:4
chaine=1:2:3:4:
tab a 5 elements
['1', '2', '3', '4', '']
chaine=1:2:3:4::
tab a 6 elements
['1', '2', '3', '4', '', '']

3.5. التعبيرات العادية


برنامج (bases_09)

#    -*- coding=utf-8 -*-

import re

# --------------------------------------------------------------------------
def compare(modele,chaine):
    #  compares chain chain with model chain
    #    displaying results
    print "\nResultats(%s,%s)" % (chaine,modele)
    match=re.match(modele,chaine)
    if match:
        print match.groups()
    else:
        print "La chaine [%s] ne correspond pas au modele [%s]" % (chaine,modele)


#  regular expressions in python
#  retrieve the various fields of a string
#  the model: a sequence of numbers surrounded by any characters
#  you only want to retrieve the sequence of digits
modele=r"^.*?(\d+).*?$"

#  the chain is compared with the
compare(modele,"xyz1234abcd")
compare(modele,"12 34")
compare(modele,"abcd")

#  the model: a sequence of numbers surrounded by any characters
#  we want the sequence of digits and the fields that follow and precede them
modele=r"^(.*?)(\d+)(.*?)$"

#  the chain is compared with the
compare(modele,"xyz1234abcd")
compare(modele,"12 34")
compare(modele,"abcd")

#  the template - a date in dd/mm/yy format
modele=r"^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$"
compare(modele,"10/05/97")
compare(modele," 04/04/01 ")
compare(modele,"5/1/01")

#  the model - a decimal number
modele=r"^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$"
compare(modele,"187.8")
compare(modele,"-0.6")
compare(modele,"4")
compare(modele,".6")
compare(modele,"4.")
compare(modele," + 4")
#    end

ملاحظات:

  • لاحظ الوحدة المستوردة في السطر 3. فهي تحتوي على الدالات الخاصة بمعالجة التعبيرات العادية؛
  • السطر 10: مقارنة سلسلة نصية بتعبير عادي (نمط) تُرجع True إذا كانت السلسلة تتطابق مع النمط، و False في حالة عدم التطابق؛
  • السطر 12: match.groups() عبارة عن توبول تتكون عناصره من أجزاء السلسلة التي تتطابق مع عناصر التعبير النمطي المحاطة بأقواس. في النمط:
  • ^.*?(\d+).*؟، ستكون match.groups() مجموعة ذات عنصر واحد؛
  • ^(.*?)(\d+)(.*?)$، ستكون match.groups() مجموعة مكونة من 3 عناصر.

النتائج

Resultats(xyz1234abcd,^.*?(\d+).*?$)
('1234',)

Resultats(12 34,^.*?(\d+).*?$)
('12',)

Resultats(abcd,^.*?(\d+).*?$)
La chaine [abcd] ne correspond pas au modele [^.*?(\d+).*?$]

Resultats(xyz1234abcd,^(.*?)(\d+)(.*?)$)
('xyz', '1234', 'abcd')

Resultats(12 34,^(.*?)(\d+)(.*?)$)
('', '12', ' 34')

Resultats(abcd,^(.*?)(\d+)(.*?)$)
La chaine [abcd] ne correspond pas au modele [^(.*?)(\d+)(.*?)$]

Resultats(10/05/97,^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$)
('10', '05', '97')

Resultats( 04/04/01 ,^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$)
('04', '04', '01')

Resultats(5/1/01,^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$)
La chaine [5/1/01] ne correspond pas au modele [^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$]

Resultats(187.8,^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$)
('', '187.8')

Resultats(-0.6,^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$)
('-', '0.6')

Resultats(4,^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$)
('', '4')

Resultats(.6,^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$)
('', '.6')

Resultats(4.,^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$)
('', '4.')

Resultats( + 4,^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$)
('+', '4')

3.6. وضع تمرير معلمات الدالة


البرنامج (bases_10)

#    -*- coding=utf-8 -*-

def f1(a):
    a=2

def f2(a,b):
    a=2
    b=3
    return (a,b)

#    ------------------------ hand
x=1
f1(x)
print "x=%s" % (x)
(x,y)=(-1,-1)
(x,y)=f2(x,y)
print "x=%s, y=%s" % (x,y)

النتائج

x=1
x=2, y=3

ملاحظات:

  • كل شيء في Python هو كائن. بعض الكائنات تسمى "ثابتة": لا يمكن تعديلها. هذا هو الحال بالنسبة للأرقام والسلاسل والمجموعات. عندما يتم تمرير كائنات Python كحجج إلى الدوال، يتم تمرير مراجعها، ما لم تكن هذه الكائنات "ثابتة"، وفي هذه الحالة يتم تمرير قيمة الكائن؛
  • تهدف الدالتان f1 (السطر 3) و f2 (السطر 6) إلى توضيح تمرير معلمة الإخراج. نريد أن يتم تعديل المعلمة الفعلية للدالة بواسطة الدالة؛
  • السطران 3-4: تقوم الدالة f1 بتعديل معلمتها الشكلية a. نريد معرفة ما إذا كان المعلم الفعلي سيتم تعديله أيضًا.
  • السطران 12-13: المعلمة الفعلية هي x = 1. تظهر النتيجة من السطر 1 أن المعلمة الفعلية لم يتم تعديلها. وبالتالي، فإن المعلمة الفعلية x والمعلمة الشكلية a هما كائنان مختلفان؛
  • الأسطر 6–9: تقوم الدالة f2 بتعديل معلمتيها الشكلية a و b، وتعيدهما كنتائج؛
  • السطران 15–16: يتم تمرير المتغيرات الفعلية (x, y) إلى f2، ويتم تعيين نتيجة f2 إلى (x, y). يوضح السطر 2 من النتائج أن المتغيرات الفعلية (x, y) قد تم تعديلها.

نستنتج أنه عندما تكون الكائنات "غير القابلة للتغيير" معلمات إخراج، يجب أن تكون جزءًا من النتائج التي تعيدها الدالة.

3.7. الملفات النصية


البرنامج (bases_11)

#    -*- coding=utf-8 -*-

import sys

#    sequential operation of a text file
#  this is a set of lines of the form login:pwd:uid:gid:infos:dir:shell
#  each line is put into a dictionary in the form login => [uid,gid,infos,dir,shell]

# --------------------------------------------------------------------------
def afficheInfos(dico,cle):
    #  displays the value associated with key in the dico dictionary if it exists
    valeur=None
    if dico.has_key(cle):
        valeur=dico[cle]
    if 'list' in str(type(valeur)):
        print "[{0},{1}]".format(cle,":".join(valeur))
    else:
        #  key is not a dictionary key dico
        print "la cle [{0}] n'existe pas".format(cle)           


def cutNewLineChar(ligne):
    #  delete the end-of-line mark if it exists
    l=len(ligne);
    while(ligne[l-1]=="\n" or ligne[l-1]=="\r"):
        l-=1
    return(ligne[0:l]);

#  set the file name
INFOS="infos.txt"

#  we open it in creation
try:
    fic=open(INFOS,"w")
except:
    print "Erreur d'ouverture du fichier INFOS en écriture\n"
    sys.exit()

#    generate arbitrary content
for i in range(1,101):
    ligne="login%s:pwd%s:uid%s:gid%s:infos%s:dir%s:shell%s" % (i,i,i,i,i,i,i)
    fic.write(ligne+"\n")

#  close the file
fic.close()

#  open it for reading
try:
    fic=open(INFOS,"r")
except:
    print "Erreur d'ouverture du fichier INFOS en écriture\n"
    sys.exit()

#    empty dictionary at start
dico={}

#  line reading  
ligne=fic.readline()  
while(ligne!=''):
    #  remove the end-of-line character
    ligne=cutNewLineChar(ligne)

    #  put the line in a table
    infos=ligne.split(":")

    #    retrieve login
    login=infos[0]

    #  remove the first two elements [login,pwd]
    infos[0:2]=[]

    #    create a dictionary entry
    dico[login]=infos

    #  line reading  
    ligne=fic.readline()  

#  close the file
fic.close()

#  using the dictionary
afficheInfos(dico,"login10")
afficheInfos(dico,"X")

ملاحظات:

  • السطر 37: لإنهاء البرنامج النصي في منتصف الكود.

النتائج

ملف infos.txt:

login0:pwd0:uid0:gid0:infos0:dir0:shell0
login1:pwd1:uid1:gid1:infos1:dir1:shell1
login2:pwd2:uid2:gid2:infos2:dir2:shell2
...
login98:pwd98:uid98:gid98:infos98:dir98:shell98
login99:pwd99:uid99:gid99:infos99:dir99:shell99

إخراج الشاشة:

[login10,uid10:gid10:infos10:dir10:shell10]
la cle [X] n'existe pas