Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 485cfcc

Browse files
Add demo of generator function.
1 parent 02f3e5c commit 485cfcc

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

‎FunctionIntroduction/src/findprime.py

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ def optional_arg_func(a, b=None, c=30):
2323
print('since b and c have default values in the function arguments, these are optional.\nFunction call will woork even if b and c are not provided.')
2424
print('\'a\' has no default. Therefore, it becomes a mandatory argument for the function.')
2525
print('Value of b is None.\nNone is given as a variable value when variable is to be kept as optional in function arguments but one does not want to assign any value to it.')
26+
print('Default arguments cannot be defined before non-default arguments.')
2627

2728
if b is None:
2829
b = 433
@@ -50,14 +51,42 @@ def key_word_func_args(a, b, *args, **kargs):
5051

5152
for k in kargs:
5253
print('key = {} and value = {}'.format(k, kargs[k]))
53-
54+
5455
def func_return_multiple_val():
5556
print('Demo of returning multiple values in python')
5657
a = 1
5758
b = 2
5859
c = 3
5960
d = 'This is a string'
6061
return a, b, c, d
62+
63+
def generator_func_demo():
64+
print('This function is a demo of generator function.')
65+
print('Generator function returns an iterator object.')
66+
67+
print('The function used here, is a generator function for inclusive range.')
68+
for i in inclusive_range(0,10,1):
69+
print(i, end=' ')
70+
71+
def inclusive_range(*args):
72+
n_args = len(args)
73+
if n_args < 1: raise TypeError('Minimum 1 argument required.')
74+
75+
if n_args == 1:
76+
start = 0
77+
step = 0
78+
stop = args[0]
79+
elif n_args == 2:
80+
(start, stop) = args
81+
step = 1
82+
elif n_args == 3:
83+
(start, stop, step) = args
84+
else: raise TypeError('Maximum 3 arguments required. Given {} arguments to the function'.format(n_args))
85+
86+
i = start
87+
while i<=stop:
88+
yield i # yield makes the function as a generator function
89+
i += step
6190

6291
def main():
6392
for n in range(1, 20):
@@ -77,5 +106,8 @@ def main():
77106

78107
a, b, c, d = func_return_multiple_val()
79108
print('a={}, b = {}, c={}\nd={}'.format(a,b,c,d))
109+
110+
print()
111+
generator_func_demo()
80112

81113
if __name__ == '__main__': main()

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /