Reputation: 3501
I'm trying to do a task from a tutorial which is to define a function that will repeat an inputted word an inputted number of times, so far I have:
s = raw_input("Enter a word:")
n = input("Enter a number:")
def repeat_this(s, n):
print s * n
However s and n aren't defined locally in repeat_this, but I couldn't get the user input to work when I defined s and n inside the function, could anyone provide any tips of how to get this to work?
N.B. When I run the file containing this it accepts input for s and n, but then leaves a blank line and starts a new empty line, where repeat-this is not defined.
Upvotes: 0
Views: 5853
Reputation: 3107
Aside from the embedded print, your repeat_this()
function is effectively the multiply operator, which can be used as a function on it's own:
from operator import mul
s = raw_input("Enter a word:")
n = input("Enter a number:")
print mul(s, n)
Upvotes: 0
Reputation: 184200
You're not calling the function. Add this to the end of the script:
repeat_this(s, n)
Also, your inputs should both be raw_input()
(coerce the number to an integer using int()
rather than dangerously allowing Python to parse it) and should probably go below the function definition (it'll work either way, but it's better style to put all the script stuff together below your function and global variable definitions). Putting it all together:
def repeat_this(s, n):
print s * n
s = raw_input("Enter a word:")
n = int(raw_input("Enter a number:"))
repeat_this(s, n)
Upvotes: 2