A custom function to return the length of a string












0















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 :-(










share|improve this question




















  • 4





    Why is the function taking a parameter at all? It's not using it

    – UnholySheep
    Jan 2 at 10:15











  • Thank you! I am new to coding. I thought, I need to add a parameter. But now I understand :-)

    – Comtron
    Jan 2 at 10:20






  • 2





    "This code does not work." is not a helpful statement. Please provide the input, the actual output and the expected output in your question. If your code is throwing an error, you should provide the complete error stack in your question.

    – Mike Scotty
    Jan 2 at 10:21













  • Welcome to StackOverflow! You may find the explanations given at idownvotedbecau.se helpful to avoid accidentally posting stuff which has downvote reasons within.

    – Alfe
    Jan 2 at 10:23






  • 1





    @Alfe: thanks! I assume you are referring to the same issue as Mike Scotty. As mentioned, I am new to StackOverflow and I will be more precise in the future.

    – Comtron
    Jan 2 at 10:37
















0















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 :-(










share|improve this question




















  • 4





    Why is the function taking a parameter at all? It's not using it

    – UnholySheep
    Jan 2 at 10:15











  • Thank you! I am new to coding. I thought, I need to add a parameter. But now I understand :-)

    – Comtron
    Jan 2 at 10:20






  • 2





    "This code does not work." is not a helpful statement. Please provide the input, the actual output and the expected output in your question. If your code is throwing an error, you should provide the complete error stack in your question.

    – Mike Scotty
    Jan 2 at 10:21













  • Welcome to StackOverflow! You may find the explanations given at idownvotedbecau.se helpful to avoid accidentally posting stuff which has downvote reasons within.

    – Alfe
    Jan 2 at 10:23






  • 1





    @Alfe: thanks! I assume you are referring to the same issue as Mike Scotty. As mentioned, I am new to StackOverflow and I will be more precise in the future.

    – Comtron
    Jan 2 at 10:37














0












0








0


1






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 :-(










share|improve this question
















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 :-(







python string function






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 2 at 10:28









Brian Tompsett - 汤莱恩

4,2421339102




4,2421339102










asked Jan 2 at 10:13









ComtronComtron

123




123








  • 4





    Why is the function taking a parameter at all? It's not using it

    – UnholySheep
    Jan 2 at 10:15











  • Thank you! I am new to coding. I thought, I need to add a parameter. But now I understand :-)

    – Comtron
    Jan 2 at 10:20






  • 2





    "This code does not work." is not a helpful statement. Please provide the input, the actual output and the expected output in your question. If your code is throwing an error, you should provide the complete error stack in your question.

    – Mike Scotty
    Jan 2 at 10:21













  • Welcome to StackOverflow! You may find the explanations given at idownvotedbecau.se helpful to avoid accidentally posting stuff which has downvote reasons within.

    – Alfe
    Jan 2 at 10:23






  • 1





    @Alfe: thanks! I assume you are referring to the same issue as Mike Scotty. As mentioned, I am new to StackOverflow and I will be more precise in the future.

    – Comtron
    Jan 2 at 10:37














  • 4





    Why is the function taking a parameter at all? It's not using it

    – UnholySheep
    Jan 2 at 10:15











  • Thank you! I am new to coding. I thought, I need to add a parameter. But now I understand :-)

    – Comtron
    Jan 2 at 10:20






  • 2





    "This code does not work." is not a helpful statement. Please provide the input, the actual output and the expected output in your question. If your code is throwing an error, you should provide the complete error stack in your question.

    – Mike Scotty
    Jan 2 at 10:21













  • Welcome to StackOverflow! You may find the explanations given at idownvotedbecau.se helpful to avoid accidentally posting stuff which has downvote reasons within.

    – Alfe
    Jan 2 at 10:23






  • 1





    @Alfe: thanks! I assume you are referring to the same issue as Mike Scotty. As mentioned, I am new to StackOverflow and I will be more precise in the future.

    – Comtron
    Jan 2 at 10:37








4




4





Why is the function taking a parameter at all? It's not using it

– UnholySheep
Jan 2 at 10:15





Why is the function taking a parameter at all? It's not using it

– UnholySheep
Jan 2 at 10:15













Thank you! I am new to coding. I thought, I need to add a parameter. But now I understand :-)

– Comtron
Jan 2 at 10:20





Thank you! I am new to coding. I thought, I need to add a parameter. But now I understand :-)

– Comtron
Jan 2 at 10:20




2




2





"This code does not work." is not a helpful statement. Please provide the input, the actual output and the expected output in your question. If your code is throwing an error, you should provide the complete error stack in your question.

– Mike Scotty
Jan 2 at 10:21







"This code does not work." is not a helpful statement. Please provide the input, the actual output and the expected output in your question. If your code is throwing an error, you should provide the complete error stack in your question.

– Mike Scotty
Jan 2 at 10:21















Welcome to StackOverflow! You may find the explanations given at idownvotedbecau.se helpful to avoid accidentally posting stuff which has downvote reasons within.

– Alfe
Jan 2 at 10:23





Welcome to StackOverflow! You may find the explanations given at idownvotedbecau.se helpful to avoid accidentally posting stuff which has downvote reasons within.

– Alfe
Jan 2 at 10:23




1




1





@Alfe: thanks! I assume you are referring to the same issue as Mike Scotty. As mentioned, I am new to StackOverflow and I will be more precise in the future.

– Comtron
Jan 2 at 10:37





@Alfe: thanks! I assume you are referring to the same issue as Mike Scotty. As mentioned, I am new to StackOverflow and I will be more precise in the future.

– Comtron
Jan 2 at 10:37












2 Answers
2






active

oldest

votes


















3














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.






share|improve this answer


























  • Million thanks! :-)

    – Comtron
    Jan 2 at 10:18











  • your welcome @Comtron, Please consider this: stackoverflow.com/help/someone-answers

    – Mehrdad Pedramfar
    Jan 2 at 10:19











  • @mehrdad-pedramfar you can add another way where user pass the string as parameter to the function . both case

    – prashant rana
    Jan 2 at 10:19











  • I voted up :-)Thanks again!

    – Comtron
    Jan 2 at 10:22











  • @prashantrana yes, thanks, i will update.

    – Mehrdad Pedramfar
    Jan 2 at 10:22



















1














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.





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54004482%2fa-custom-function-to-return-the-length-of-a-string%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    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.






    share|improve this answer


























    • Million thanks! :-)

      – Comtron
      Jan 2 at 10:18











    • your welcome @Comtron, Please consider this: stackoverflow.com/help/someone-answers

      – Mehrdad Pedramfar
      Jan 2 at 10:19











    • @mehrdad-pedramfar you can add another way where user pass the string as parameter to the function . both case

      – prashant rana
      Jan 2 at 10:19











    • I voted up :-)Thanks again!

      – Comtron
      Jan 2 at 10:22











    • @prashantrana yes, thanks, i will update.

      – Mehrdad Pedramfar
      Jan 2 at 10:22
















    3














    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.






    share|improve this answer


























    • Million thanks! :-)

      – Comtron
      Jan 2 at 10:18











    • your welcome @Comtron, Please consider this: stackoverflow.com/help/someone-answers

      – Mehrdad Pedramfar
      Jan 2 at 10:19











    • @mehrdad-pedramfar you can add another way where user pass the string as parameter to the function . both case

      – prashant rana
      Jan 2 at 10:19











    • I voted up :-)Thanks again!

      – Comtron
      Jan 2 at 10:22











    • @prashantrana yes, thanks, i will update.

      – Mehrdad Pedramfar
      Jan 2 at 10:22














    3












    3








    3







    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.






    share|improve this answer















    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.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jan 2 at 10:25

























    answered Jan 2 at 10:16









    Mehrdad PedramfarMehrdad Pedramfar

    6,33411643




    6,33411643













    • Million thanks! :-)

      – Comtron
      Jan 2 at 10:18











    • your welcome @Comtron, Please consider this: stackoverflow.com/help/someone-answers

      – Mehrdad Pedramfar
      Jan 2 at 10:19











    • @mehrdad-pedramfar you can add another way where user pass the string as parameter to the function . both case

      – prashant rana
      Jan 2 at 10:19











    • I voted up :-)Thanks again!

      – Comtron
      Jan 2 at 10:22











    • @prashantrana yes, thanks, i will update.

      – Mehrdad Pedramfar
      Jan 2 at 10:22



















    • Million thanks! :-)

      – Comtron
      Jan 2 at 10:18











    • your welcome @Comtron, Please consider this: stackoverflow.com/help/someone-answers

      – Mehrdad Pedramfar
      Jan 2 at 10:19











    • @mehrdad-pedramfar you can add another way where user pass the string as parameter to the function . both case

      – prashant rana
      Jan 2 at 10:19











    • I voted up :-)Thanks again!

      – Comtron
      Jan 2 at 10:22











    • @prashantrana yes, thanks, i will update.

      – Mehrdad Pedramfar
      Jan 2 at 10:22

















    Million thanks! :-)

    – Comtron
    Jan 2 at 10:18





    Million thanks! :-)

    – Comtron
    Jan 2 at 10:18













    your welcome @Comtron, Please consider this: stackoverflow.com/help/someone-answers

    – Mehrdad Pedramfar
    Jan 2 at 10:19





    your welcome @Comtron, Please consider this: stackoverflow.com/help/someone-answers

    – Mehrdad Pedramfar
    Jan 2 at 10:19













    @mehrdad-pedramfar you can add another way where user pass the string as parameter to the function . both case

    – prashant rana
    Jan 2 at 10:19





    @mehrdad-pedramfar you can add another way where user pass the string as parameter to the function . both case

    – prashant rana
    Jan 2 at 10:19













    I voted up :-)Thanks again!

    – Comtron
    Jan 2 at 10:22





    I voted up :-)Thanks again!

    – Comtron
    Jan 2 at 10:22













    @prashantrana yes, thanks, i will update.

    – Mehrdad Pedramfar
    Jan 2 at 10:22





    @prashantrana yes, thanks, i will update.

    – Mehrdad Pedramfar
    Jan 2 at 10:22













    1














    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.





    share|improve this answer




























      1














      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.





      share|improve this answer


























        1












        1








        1







        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.





        share|improve this answer













        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.






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 2 at 10:27









        alfandangoalfandango

        4616




        4616






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54004482%2fa-custom-function-to-return-the-length-of-a-string%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

            SQL update select statement

            'app-layout' is not a known element: how to share Component with different Modules