Error with Python For Loop within Function

TheMattdavis17

So I am trying to better understand functions and using for loops to select from multiple lists. Here is the basic function that I created and it does work:

def my_function(person, feeling):
    print('Hello, %s, how are you? It seems that you are feeling %s!' %(person, feeling))

my_function('Matthew', 'rejuvinated')

But to take this further, I would like to pick a name and a feeling from their respective lists and insert them into the new function. When I try the following, I get an error. Any help would be greatly appreciated!

people = ['Colby', 'Hattie', 'Matthew', 'Stephen', 'Lee', 'Deb', 'Sharon', 'Pete']
feelings = ['happy', 'sad', 'cold', 'cranky', 'happy', 'successful', 'spunky', 'warm', 'nerdy']

def my_function(person, feeling): 
    """This function produces a statement which inserts a name and a feeling"""
    for p in enumerate(people):
            person = p
    for f in enumerate(feelings):
            feeling = f
    print('Hello, %s, how are you? It seems that you are feeling %s!' %(person, feeling)) 
    return my_function()

my_function(people, feelings)

Hello, (7, 'Pete'), how are you? It seems that you are feeling (8, 'nerdy')!
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-2b2a265c427c> in <module>
     11     return my_function()
     12 
---> 13 my_function(people, feelings)

<ipython-input-1-2b2a265c427c> in my_function(person, feeling)
      9             feeling = f
     10     print('Hello, %s, how are you? It seems that you are feeling %s!' %(person, feeling))
---> 11     return my_function()
     12 
     13 my_function(people, feelings)

TypeError: my_function() missing 2 required positional arguments: 'person' and 'feeling'
Charif DZ

Two loop over two list in the same time use, zip :

peoples = ['Colby', 'Hattie', 'Matthew', 'Stephen', 'Lee', 'Deb', 'Sharon', 'Pete']
feelings = ['happy', 'sad', 'cold', 'cranky', 'happy', 'successful', 'spunky', 'warm', 'nerdy']

def my_function(persons, feelings):
    """This function produces a statement which inserts a name and a feeling"""
    # python provide a zip built-in function to loop over multiple list in the same time
    for person, feeling in zip(persons, feelings):
        # print the message for every element
        print('Hello, %s, how are you? It seems that you are feeling %s!' %(person, feeling))

my_function(peoples, feelings)

The zip() function takes:

iterables - can be built-in iterables (like: list, string, dict), or user-defined iterables (object that has __iter__ method)

The zip() function returns an iterator of tuples based on the iterable object.

  • If no parameters are passed, zip() returns an empty iterator
  • If a single iterable is passed, zip() returns an iterator of 1-tuples. Meaning, the number of elements in each tuple is 1.
  • If multiple iterables are passed, ith tuple contains ith Suppose, two iterables are passed; one iterable containing 3 and other containing 5 elements. Then, the returned iterator has 3 tuples. It's because iterator stops when shortest iterable is exhaused.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Error with Python For Loop within Function

분류에서Dev

Slow .value function within for loop

분류에서Dev

Calling a function within a loop, "Undefined is not a function"

분류에서Dev

Repeating A Function From Within A Function In Python 3

분류에서Dev

Any Ideas how to iterate an element in the each loop in jQuery from within a click function within it?

분류에서Dev

Multiplot error with plots created using ggplot within a function

분류에서Dev

How can a (global) Python module be created within a function with the module name specified as an argument of the function?

분류에서Dev

if statement within PHP Function

분류에서Dev

checkValidity() not working within function

분류에서Dev

ltree postgres type using spring data jpa -- geting syntax error after defining a function and cast within postgres

분류에서Dev

Search for character in string, within an loop

분류에서Dev

Updating ProgressBar value within a for loop

분류에서Dev

user defined function returns error in python

분류에서Dev

Python Merge function array range error?

분류에서Dev

Python : SyntaxError 'return'outside function error

분류에서Dev

python: argument generated by a prior function error

분류에서Dev

python accessing another function variable error

분류에서Dev

How can I display a meaningful login error messages to user within python-social-auth?

분류에서Dev

Ordering within a MySQL Group function

분류에서Dev

Access "this" from within anonymous function

분류에서Dev

Spectal plotting within Python?

분류에서Dev

Reassign variable in a List within for-loop

분류에서Dev

Add to an array from within a loop using Ruby

분류에서Dev

readHTMLTable in R throws warning within for loop

분류에서Dev

Directly accessing matrix values within a for-loop

분류에서Dev

how to add a variable within each loop

분류에서Dev

How to create a matrix with the increments within a loop in matlab?

분류에서Dev

R: For Loop within a For Loop, rebuilding and exporting the output each round

분류에서Dev

python: Small Logical Error in a terminal function graphing class

Related 관련 기사

  1. 1

    Error with Python For Loop within Function

  2. 2

    Slow .value function within for loop

  3. 3

    Calling a function within a loop, "Undefined is not a function"

  4. 4

    Repeating A Function From Within A Function In Python 3

  5. 5

    Any Ideas how to iterate an element in the each loop in jQuery from within a click function within it?

  6. 6

    Multiplot error with plots created using ggplot within a function

  7. 7

    How can a (global) Python module be created within a function with the module name specified as an argument of the function?

  8. 8

    if statement within PHP Function

  9. 9

    checkValidity() not working within function

  10. 10

    ltree postgres type using spring data jpa -- geting syntax error after defining a function and cast within postgres

  11. 11

    Search for character in string, within an loop

  12. 12

    Updating ProgressBar value within a for loop

  13. 13

    user defined function returns error in python

  14. 14

    Python Merge function array range error?

  15. 15

    Python : SyntaxError 'return'outside function error

  16. 16

    python: argument generated by a prior function error

  17. 17

    python accessing another function variable error

  18. 18

    How can I display a meaningful login error messages to user within python-social-auth?

  19. 19

    Ordering within a MySQL Group function

  20. 20

    Access "this" from within anonymous function

  21. 21

    Spectal plotting within Python?

  22. 22

    Reassign variable in a List within for-loop

  23. 23

    Add to an array from within a loop using Ruby

  24. 24

    readHTMLTable in R throws warning within for loop

  25. 25

    Directly accessing matrix values within a for-loop

  26. 26

    how to add a variable within each loop

  27. 27

    How to create a matrix with the increments within a loop in matlab?

  28. 28

    R: For Loop within a For Loop, rebuilding and exporting the output each round

  29. 29

    python: Small Logical Error in a terminal function graphing class

뜨겁다태그

보관