Im trying to write a program so that I get a result of...
5 : Rowan
6 : Rowan
7 : Rowan
8 : Rowan
9 : Rowan
10 : Rowan
11 : Rowan开发者_如何学运维
12 : Rowan
I want to be able to set it so that I can change the starting number, the amount of times it repeats and the word that it repeats.
this is what i have so far...
def hii(howMany, start, Word):
Word
for howMany in range (howMany):
print howMany + start, ":", "-"
Im just having trouble making it so i can change the word that repeats
The range
iterator takes a start value:
def hii(howMany, start, Word):
for i in range(start, start+howMany):
print i, ":", Word
Note that it's not a good idea to use the same name for a local variable as for a parameter (howMany
). I have used i
instead.
From Python 2.6 upwards enumerate has a start parameter:
import itertools
def hii(how_many, start, word):
seq = itertools.repeat(word, how_many)
return enumerate(seq, start=start)
for n, w in hii(8, 5, 'Rowan'):
print n, w
How about:
def hii(howMany, start, Word):
for howMany in range (howMany):
print howMany + start, ":", Word
Is there anything wrong with that?
To use:
hii(10, 4, "Weeee!!!!")
python 2.x
>>> def repeater(start, end, word):
... for i in range(start, end):
... print i, ":", word
>>> repeater(2,8, "hello")
for python3.x
>>> def repeater(start, end, word):
... for i in range(start, end):
... print(i , ":" , word)
>>> repeater(2,8, "hello")
精彩评论