TIME NOW CALENDAR CONVERT LENGTH CONVERT TEMPERATURE DICTIONARIES, LISTS SCIENCE EDUCATION RELIGION WORK CALCULATOR CALCULATE LIFE

Python 3 programming language, learn python, tutorial

ALL TOPICS

Python 3. functions

1. Scope of functions. Default value arg=5. Restult is 5:
i = 5

def f(arg=i):
print(arg)

i = 6
f()

1a. Error:
def a():
foo = 'A'

def b():
foo = 'B'

b()
a()
print (foo)

1b. Scope. y is global, z is local:
y = 3                            # first we associate the name 'y' with the number 3

def print_stuff():               # then we associate the name print_stuff with this function
print "calling print_stuff"          #  (***)
print y
z = 4
print z
print "exiting print_stuff"

print_stuff()                    # we call print_stuff and the program execution goes to (***)
print y                          # works fine
print z

1b. Error:
def a(foo = 'A'):
return foo

def b(foo = 'B'):
return foo

b()
a()
print (foo)

1c. Error:
def a(foo = 'A'):
global foo

def b(foo = 'B'):
global foo

b()
a()
print (foo)

1d. No errors:
def a():
global foo
foo = 'A'

def b():
global foo
foo = 'B'

b()
a()
print (foo)

2. Accumulation of values:
def f(a, L=[]):
L.append(a)
return L

print(f(1))
print(f(2))
print(f(3))

Result:
[1]
[1, 2]
[1, 2, 3]

2a. Values are not accumulated:
def f(a):
a=a+1
return a

print(f(1))
print(f(1))
print(f(1))

2a. Values are not accumulated:
def f(a, b = 1):
b = b + a
return b

print(f(1))
print(f(1))
print(f(1))

3. Arguments of function:
def converter(Aunit, Avalue ='10', Aconversion='needed', Atype='finish'):
print("Unit = ", Aunit, ", Value = " , Avalue , end=' ')
print("Conversion = ", Aconversion, "and type = ", Atype)

converter('mile')
converter(Aunit = 'foot')
converter (1, 2, 3)
converter('km', Atype = 'well')
converter(Aunit = 'km', Atype = 'well', Aconversion = 'yes', Avalue = '1000' )

Result:
Unit =  mile , Value =  10 Conversion =  needed and type =  finish
Unit =  foot , Value =  10 Conversion =  needed and type =  finish
Unit =  1 , Value =  2 Conversion =  3 and type =  finish
Unit =  km , Value =  10 Conversion =  needed and type =  well
Unit =  km , Value =  1000 Conversion =  yes and type =  well

4. Arguments of functions. *name receives a tuple containing the positional arguments beyond the formal parameter list. *name must occur before **name. When a formal parameter **name is present, it receives a dictionary containing all keyword arguments except for those corresponding to a formal parameter.::
def converter(kind, *arguments, **keywords):
print(kind, ":")
for arg in arguments:
print(arg)
print("-" * 40)

keys = sorted(keywords.keys())
for kw in keys:
print(kw, ":", keywords[kw])

converter("units", "cm", "km", "miles", days = 10 , months = "20", year = "2016" )

Result:
units :
cm
km
miles
----------------------------------------
days : 10
months : 20
year : 2016

5. Unpacking Argument Lists. Dictionaries and list can deliver keyword arguments:
###
###  lists can deliver keyword arguments
###

args = [3, 6]
print( list(range(*args)))            # call with arguments unpacked from a list

###
###  dictionaries can deliver keyword arguments
###

def converter(unit_one, unit_two ='yard', action ='delete'):
print(unit_one, unit_two, action)

d = {"unit_one": "mile", "unit_two": "kilometer", "action": "convert"}

converter(**d)

6. Empty function, needed for some construction in code:
def initlog(*args):
pass

Create dictionary from the two rows, using the example below:
def conv(*args):
pass

str1="jonas - 10, simas - 20, petras - 30"
str2="elena - 10, rokas - 40, morta - 50"

conv (str1, str2)

Result:
Amount of strings - arguments can differ.
{"jonas":10, "simas":20 ...}

Create calculator function. Operations (+-*/):
def calculator (num1, num2, operation):
...
...

print (calculator(2,2,"+"))

7. Function with one parameter. Function is called twice:
def fib(n):    # write Fibonacci series up to n
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()

fib (2000)

# uncomment below
# f = 5

f = fib

# uncomment below
# f = 5

f(30)

f(0)

print(f(0)) # result is [none], function returns nothing

Result:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
0 1 1 2 3 5 8 13 21

None

8. Small functions in functions:
def make_incrementor(n):
return lambda x: x + n

f = make_incrementor(42)

print(f(0))

print(f(1))

Equivalent:
def f (x):
return x**2

print (f(8))

g = lambda x: x**2
print (g(8))

Condition:
g = lambda x: 'big' if x > 100 else 'small'
print (g(1000))

9. Return a list containing the Fibonacci series up to n.
def fib2(n): # return Fibonacci series up to n

result = []
a, b = 0, 1
while a < n:
result.append(a)    # see below
a, b = b, a+b
return result

result = fib2(1000)

print(result)

Result:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]

10. Function with many parameters. in keyword:
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise IOError('refusenik user')
print(complaint)

11. Function documentation:
def my_function():
"""Do nothing, but document it.

No, really, it doesn't do anything.
"""
pass

print(my_function.__doc__)

12. Scope for variables. http://stackoverflow.com/questions/1261875/python-nonlocal-statement:
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"

spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)

Result:
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

13.
a = 0    #1. global variable with respect to every function in program

def f():
a = 10          #2. nonlocal with respect to function g
def g():
nonlocal a
a=a+1
print("The value of 'a' using nonlocal is ", a)
def h():
global a
#3. using global variable
a=a+5
print("The value of a using global is ", a)
def i():
#4. variable separated from all others
#error
#a=a+1
print("The value of 'a' inside a function is ", a)
def j():
#5. variable separated from all others

a=100
print("The value of 'a' inside a function is ", a)
g()
h()
i()
j()
g()
i()
i()

print("The value of 'a' global before any function", a)
f()
print("The value of 'a' global after using function f ", a)

Task 3. Get dictionary from strings and print it. Template:
names1 = "Jonas - 30, Petras - 25, Simas - 10"
names2 = "Arnas - 40, Morta - 45, Janina - 50"
names3 = "Maryte - 40, Ana - 45, Marius - 50"

def converter(*keywords):

def get_dictionary ():
pass

def print_dictionary():
pass

converter(names1, names2, names3,)
ALL TOPICS

 Andrius:1. def sum( arg1, arg2 ):   total = arg1 + arg2   print ("Suma lygi: ", total)   return totalarg1=int(input("Iveskite pirmaji nari: "))arg2=int(input("Iveskite antraji nari: "))sum(arg1, arg2)2.def lyginimas(irasymas): while True: x = int(input(irasymas)) if x in (1,1):  return True if x in (1,10): return Falselyginimas("Iveskite x: ")2015-11-04 07:04:26
 Vitalij:<1> def kmi(mase,ugis): return mase/pow(ugis,2) print ("Kuno mases indekso skaiciuokle") m=int(input("Svoris kilogramais: ")) u=float(input("Ugis metrais: ")) print("Kuno mases indeksas: ", round(kmi(m,u),2),"\nOptimalus svorio indeksas - nuo 18,5 iki 25") <2> def k2(x,y): return x*y def k3(z): return k2(x,y)*z while True: x=int(input("K2/3 skaiciuokle.\nX: ")) y=int(input("Y: ")) print("Plotas: ",k2(x,y)) kk=input("Ar norite papildyti Z? - ") if kk in ('y', 'ye', 'yes','1','taip','t'): z=int(input("Iveskite Z: ")) print("Turis: ",k3(z)) kk=input("dar karta? - ") if kk in ('n', 'no','0','ne'): break2015-11-05 08:45:10
 Mindaugas:print("============pirmas pavyzdys ================")def lastFirst(firstName, lastName):    separator = ', '    result = lastName + separator + firstName    return resultprint(lastFirst('Benjamin', 'Franklin'))print(lastFirst('Andrew', 'Harrington'))print("===============antras pavyzdys =================")def changeme( mylist ):   "This changes a passed list into this function"   mylist.append([1,2,3,4]);   print ("Values inside the function: ", mylist)   return# Now you can call changeme functionmylist = [10,20,30];changeme( mylist );print ("Values outside the function: ", mylist)print("===============trecias pavyzdys =================")def changeme( mylist ):   "This changes a passed list into this function"   mylist = [1,2,3,4]; # This would assig new reference in mylist   print ("Values inside the function: ", mylist)   return# Now you can call changeme functionmylist = [10,20,30];changeme( mylist );print("===============ketvirtas pavyzdys =================")def sumProblemString(x, y):    sum = x + y    return 'The sum of {} and {} is {}.'.format(x, y, sum)def main():    print(sumProblemString(2, 3))    print(sumProblemString(1234567890123, 535790269358))    a = int(input("Enter an integer: "))    b = int(input("Enter another integer: "))    print(sumProblemString(a, b))main()print ("Values outside the function: ", mylist)2016-04-19 12:10:43