Open woneuy01 opened 4 years ago
when there is no return in the function, it returns NONE.
def hello2(s): print("Hello " + s) print("Glad to meet you")
hello2("Iman" + " and Jackie") hello2("Class " * 3)
==============
Hello Iman and Jackie Glad to meet you Hello Class Class Class Glad to meet you
def weird(): print("here") return 5 print("there") return 10
x = weird() print(x)
===============
here 5
def longer_than_five(list_of_names): for name in list_of_names: # iterate over the list to look at each name if len(name) > 5: # as soon as you see a name longer than 5 letters, return True # then return True! return나오면 뒤에 나머지는 다 건너뜀
return False # You will only get to this line if you
# ##iterated over the whole list and did not get a name where
# ## the if expression evaluated to True, so at this point, it's correct to return False!
list1 = ["Sam","Tera","Sal","Amita"] list2 = ["Rey","Ayo","Lauren","Natalie"]
print(longer_than_five(list1)) print(longer_than_five(list2))
==========================
False True
def intro(st): string= 'Hello, my name is {} and I love SI 106.'.format(st) return string
intro("Mike")
def decision(st): if len(st)>17: return "This is a long string" else: return "This is a short string"
def mylen(seq): c = 0 # initialize count variable to 0 for _ in seq: c = c + 1 # increment the counter for each item in seq return c
print(mylen("hello")) print(mylen([1, 2, 7]))
================
5 3
def total(list): tot=0 for num in list: tot=tot+num return tot
You passed: 100.0% of the tests
def count(list): tot=0 for int in list: tot=tot+1 return tot
def square(x): y = x * x return y
z = square(10) print(y)
===============
Error NameError: name 'y' is not defined on line 6
The variable y only exists while the function is being executed — we call this its lifetime. When the execution of the function terminates (returns), the local variables are destroyed
Formal parameters are also local and act like local variables. For example, the lifetime of x begins when square is called, and its lifetime ends when the function completes its execution.
def badsquare(x): y = x ** power return y
power = 2 result = badsquare(10) print(result)
========== 100 Although the badsquare function works, it is silly and poorly written. We have done it here to illustrate an important rule about how variables are looked up in Python. First, Python looks at the variables that are defined as local variables in the function. We call this the local scope. If the variable name is not found in the local scope, then Python looks at the global variables, or global scope.
Functions can call other functions (Composition)¶
It is important to understand that each of the functions we write can be used and called from other functions we write.
def most_common_letter(s): frequencies = count_freqs(s) return best_key(frequencies)
def count_freqs(st): d = {} for c in st: if c not in d: d[c] = 0 d[c] = d[c] + 1 return d
def best_key(dictionary): ks = dictionary.keys() best_key_so_far = list(ks)[0] # Have to turn ks into a real list before using [] to select an item for k in ks: if dictionary[k] > dictionary[best_key_so_far]: best_key_so_far = k return best_key_so_far
print(most_common_letter("abbbbbbbbbbbccccddddd"))
======================== b
Execution always begins at the first statement of the program. Statements are executed one at a time, in order, from top to bottom. Function definitions do not alter the flow of execution of the program, but remember that statements inside the function are not executed until the function is called.
def double(y): y = 2 * y
def changeit(lst): lst[0] = "Michigan" lst[1] = "Wolverines"
y = 5 double(y) print(y)
mylst = ['our', 'students', 'are', 'awesome'] changeit(mylst) print(mylst)
==================
5 ['Michigan', 'Wolverines', 'are', 'awesome'] 첫번째 function은 안바꼈는데 두번째는 바꼈다.
Try running it. Similar to examples we have seen before, running double does not change the global y. But running changeit does change mylst. The explanation is above, about the sharing of mutable objects. Try stepping through it in codelens to see the difference.
12.14. Side Effects We say that the function changeit has a side effect on the list object that is passed to it. Global variables are another way to have side effect
global y y = 2 * n
y = 5 double(y) print(y)
============== 10
def reverse(astring): leng=len(astring) str=[] for ins in range(leng): new_leng=leng-(ins+1) str.append(astring[new_leng]) x=''.join(str) return x
test=reverse("admin") print(test)
==== nimda
Tuple Packing¶ Wherever python expects a single value, if multiple expressions are provided, separated by commas, they are automatically packed into a tuple. For example, we can omit the parentheses when assigning a tuple of values to a single variable.
julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia")
julia = "Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia" print(julia[4])
2009
lst_tups = [('Articuno', 'Moltres', 'Zaptos'), ('Beedrill', 'Metapod', 'Charizard', 'Venasaur', 'Squirtle'), ('Oddish', 'Poliwag', 'Diglett', 'Bellsprout'), ('Ponyta', "Farfetch'd", "Tauros", 'Dragonite'), ('Hoothoot', 'Chikorita', 'Lanturn', 'Flaaffy', 'Unown', 'Teddiursa', 'Phanpy'), ('Loudred', 'Volbeat', 'Wailord', 'Seviper', 'Sealeo')] t_check=[] for ls in lst_tups: t_check.append(ls[2])
print(t_check)
==================== ['Zaptos', 'Charizard', 'Diglett', 'Tauros', 'Lanturn', 'Wailord']
tups = [('a', 'b', 'c'), (8, 7, 6, 5), ('blue', 'green', 'yellow', 'orange', 'red'), (5.6, 9.99, 2.5, 8.2), ('squirrel', 'chipmunk')]
seconds=[]
for tu in tups: seconds.append(tu[1])
print(seconds)
=========================== ['b', 7, 'green', 9.99, 'chipmunk']
Tuple Assignment with Unpacking¶
Python has a very powerful tuple assignment feature that allows a tuple of variable names on the left of an assignment statement to be assigned values from a tuple on the right of the assignment.
julia = "Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia"
name, surname, birth_year, movie, movie_year, profession, birth_place = julia
Swapping Values between Variables¶
2 1 1
with tuple
2 1
a = 1 b = 2 (a, b) = (b, a) print(a, b)
first name: Paul last name: Resnick first name: Brad last name: Miller first name: Lauren last name: Murphy
The Pythonic Way to Enumerate Items in a Sequence
fruits = ['apple', 'pear', 'apricot', 'cherry', 'peach'] for n in range(len(fruits)): print(n, fruits[n])
0 apple 1 pear 2 apricot 3 cherry 4 peach
fruits = ['apple', 'pear', 'apricot', 'cherry', 'peach'] for item in enumerate(fruits): print(item[0], item[1])
0 apple 1 pear 2 apricot 3 cherry 4 peach
fruits = ['apple', 'pear', 'apricot', 'cherry', 'peach'] for idx, fruit in enumerate(fruits): print(idx, fruit)
0 apple 1 pear 2 apricot 3 cherry 4 peach
pokemon = {'Rattata': 19, 'Machop': 66, 'Seel': 86, 'Volbeat': 86, 'Solrock': 126} p_names=[] p_number=[]
for k,v in pokemon.items(): p_names.append(k) p_number.append(v)
def circleInfo(r): """ Return (circumference, area) of a circle of radius r """ c = 2 3.14159 r a = 3.14159 r r return c, a
print(circleInfo(10))
(62.8318, 314.159)
def circleInfo(r): """ Return (circumference, area) of a circle of radius r """ c = 2 3.14159 r a = 3.14159 r r return c, a
print(circleInfo(10))
circumference, area = circleInfo(10) print(circumference) print(area)
circumference_two, area_two = circleInfo(45) print(circumference_two) print(area_two)
(62.8318, 314.159) 62.8318 314.159 282.7431 6361.71975
def add(x, y): return x + y
print(add(3, 4)) z = (5, 4) print(add(z)) # Z means insert as a tuple
def numDigits(n): n_str = str(n) return len(n_str)
print(numDigits(50)) print(numDigits(20000)) print(numDigits(1))
2 5 1
def reverse(mystr): reversed = '' for char in mystr: reversed = char + reversed return reversed
def mirror(mystr): return mystr + reverse(mystr)
assert mirror('good') == 'gooddoog' assert mirror('Python') == 'PythonnohtyP' assert mirror('') == '' assert mirror('a') == 'aa'
def reverse(mystr): reversed = '' for char in mystr: reversed = char + reversed return reversed
def mirror(mystr): return mystr + reverse(mystr)
assert mirror('good') == 'gooddoog' assert mirror('Python') == 'PythonnohtyP' assert mirror('') == '' assert mirror('a') == 'aa'
2 True [9, 8, 7, 6, 5, 4, 3, 2, 2, 1, 1, 0] 3 [0, 1, 1, 2, 'cat', 2, 3, 4, 5, 6, 7, 8, 9]
import random
def max(lst): max = 0 for e in lst: if e > max: max = e return max
lst = [] for i in range(100): lst.append(random.randint(0, 1000))
print(max(lst))
998
import random
def countOdd(lst): odd = 0 for e in lst: if e % 2 != 0: odd = odd + 1 return odd
lst = [] for i in range(100): lst.append(random.randint(0, 1000))
print(countOdd(lst))
50
import random
def sumNegative(lst): sum = 0 for e in lst: if e < 0: sum = sum + e return sum
lst = [] for i in range(100): lst.append(random.randrange(-1000, 1000))
print(sumNegative(lst))
-24582
def sumTo(aBound): """ Return the sum of 1+2+3 ... n """
theSum = 0
aNumber = 1
while aNumber <= aBound:
theSum = theSum + aNumber
aNumber = aNumber + 1
return theSum
print(sumTo(4))
print(sumTo(1000))
10 500500
eve_nums=[] num=0
while num<15: if num%2==0: eve_nums.append(num) num +=1 print(eve_nums)
[0, 2, 4, 6, 8, 10, 12, 14]
list1 = [8, 3, 4, 5, 6, 7, 9]
accum = 0
n=0
while n<len(list1):
accum=accum+list1[n]
n+=1
print(accum)
42
def hello(): """This function says hello and greets you"""
=============================
docstrings If the first thing after the function header is a string (some tools insist that it must be a triple-quoted string), it is called a docstring and gets special treatment in Python and in some of the programming tools. Another way to retrieve this information is to use the interactive interpreter, and enter the expression.doc, which will retrieve the docstring for the function. So the string you write as documentation at the start of a function is retrievable by python tools at runtime. This is different from comments in your code, which are completely eliminated when the program is parsed.
By convention, Python programmers use docstrings for the key documentation of their functions.