Error message saying variable not defined when it is. Python

前端 未结 4 1491
时光取名叫无心
时光取名叫无心 2021-01-28 20:24

I am trying to create a simple encryption program in python using functions but am having a problem where I get an error message when I run the program saying (\'msgReversed\' i

4条回答
  •  一向
    一向 (楼主)
    2021-01-28 21:19

    When you return the msgReversed variable from the reverseMsg() function, you need to assign it to a new variable in the outside scope.

    msgReversed = reverseMsg(plaintext)
    (cipher)=encript(msgReversed,k)
    

    I suspect the confusion arises with the following line:

    return msgReversed  # Note, the brackets aren't required here
    

    This returns from the function reverseMsg() while passing out the variable msgReversed. However, this variable isn't assigned anywhere by default — the name msgReversed is specific to the function. To store a value returned from a function you need to provide a variable name to store it in. Hence the following:

    msgReversed = reverseMsg(plaintext)
    

    ...will store the value returned from your function in a new variable named msgReversed. You could also name that variable something else:

    this_is_another_msgReversed = reverseMsg(plaintext)
    

    If you don't provide a variable to assign the value to, it is simply lost:

    reverseMsg(plaintext)
    # No msgReversed variable here
    

提交回复
热议问题