Reputation: 27
I want to define a function which takes an input from the user, returns the length of the input string and prints this out.
I have the following code:
def str_length(my_string):
my_string = input("give me a string: ")
return len(my_string)
print(str_length(my_string))
This code does not work. When I exchange the parameter in the last line to "hello" the code works.
def str_length(my_string):
my_string = input("give me a string: ")
return len(my_string)
print(str_length("hello"))
Can anyone explain to me why the first code does not work while the second one works? I am totally confused :-(
Upvotes: 0
Views: 811
Reputation: 111
As @UnholySheep pointed out, your function is taking a parameter it doesn't seem to need.
Let's break it down
Def str_length (): # start of function definition
# promt user for the string and put it in the variable "my _string"
my_string = input ("give me a string:")
# return the length of input string
return len(my_string)
print(str_length ()) # the function is called inside print () and therefore returns the length of the user input string to print () to be printed on screen.
Upvotes: 1
Reputation: 11073
You should define it like this:
def str_length():
my_string = input("give me a string: ")
return len(my_string)
print(str_length())
When you call the function with my_string
you get NameError
because there is no my_string
define yet. you define it inside the function. (After you call it). that is the reason.
Thanks to @prashantrana, You can also define your function like this:
def str_length(my_string):
return len(my_string)
my_string = input("give me a string: ")
print(str_length(my_string))
The difference here is that we get input from user out of the function scope, the pass it to function.
Upvotes: 3