# une réponse aux différents premiers exercices des slides # slide 8/15 : # swap solution classique : a = 12 b = 5 if a > b: c = a a = b b = c # swap solution plus pythonique : a = 'b' b = 'A' if a > b: a, b = b, a # slide 9/15 : # vérifier si un nombre est premier import math v = 154 if v < 2: is_prime = False else: is_prime = True #max_div = v max_div = math.ceil(math.sqrt(v)) for i in range(2,max_div): if v%i == 0: is_prime = False break msg = f"number {v} is prime: {is_prime}" print( msg ) # slides 10: # Test passage par copie/référence def test1(a): """ return 3.14""" print(f"in test1: input value is '{a}'") a = 3.14 return a def test2(a): """ append 3.14 to the input list""" a.append(3.14) v = 12 print(f"v has value '{v}' before call to test1") v2 = test1(v) print(f"v has value '{v}' after call to test1") print(f"return value of test1 call is '{v2}'") l = [1,'toto', 1.4] print(f"l has value '{l}' before call to test2") test2(l) print(f"l has value '{l}' after call to test2") res = test2(l) print(f"the return value of call to test2 is '{res}'") # Test portée des variables # global variable definition: A = 'glob' def local_var(): # local variable definition: A = 'loc' B = 3*A print(f"A in local var is '{A}'") return B print(f"A outside call is '{A}'") res = local_var() print(f"A after local_var call is '{A}'") def global_var_read(): B = 3*A print(f"in global_var_read, A is '{A}'") return B res = global_var_read() print(f"A after global_var_read call is '{A}'") def global_var_write(): global A A = 'no longer glob ' print(f"in global_var_write, A is '{A}'") return 3*A res = global_var_write() print(f"A after global_var_write call is '{A}'") def global_error(): # use A from global space, but no global keyword B = 3*A # thus trying to redefine a local variable with same name # will generate an Unbound Local Error A = 'loc' return B #global_error() # swap comme une fonction: def swap(a,b): if a>b: return b, a else: return a, b