Movatterモバイル変換


[0]ホーム

URL:


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

Commit485cfcc

Browse files
committed
Add demo of generator function.
1 parent02f3e5c commit485cfcc

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
ifbisNone:
2829
b=433
@@ -50,14 +51,42 @@ def key_word_func_args(a, b, *args, **kargs):
5051

5152
forkinkargs:
5253
print('key = {} and value = {}'.format(k,kargs[k]))
53-
54+
5455
deffunc_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
returna,b,c,d
62+
63+
defgenerator_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+
foriininclusive_range(0,10,1):
69+
print(i,end=' ')
70+
71+
definclusive_range(*args):
72+
n_args=len(args)
73+
ifn_args<1:raiseTypeError('Minimum 1 argument required.')
74+
75+
ifn_args==1:
76+
start=0
77+
step=0
78+
stop=args[0]
79+
elifn_args==2:
80+
(start,stop)=args
81+
step=1
82+
elifn_args==3:
83+
(start,stop,step)=args
84+
else:raiseTypeError('Maximum 3 arguments required. Given {} arguments to the function'.format(n_args))
85+
86+
i=start
87+
whilei<=stop:
88+
yieldi# yield makes the function as a generator function
89+
i+=step
6190

6291
defmain():
6392
forninrange(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)

[8]ページ先頭

©2009-2025 Movatter.jp