简体   繁体   中英

Beginner in Python; For Loops & Zips

So I'm a freshman comp sci major. I'm taking a class that teaches Python. This is my assignment:

Create a function that takes a string and a list as parameters. The string should contain the first ten letters of the alphabet and the list should contain the corresponding numbers for each letter. Zip the string and list into a list of tuples that pair each letter and number. The function should then print the number and corresponding letter respectively on separate lines. Hint: Use the zip function and a loop!

This is what I have so far:

def alpha(letter, number):
    letter = "abcdefghij"
    number = [1,2,3,4,5,6,7,8,9,10]
    return zip(letter, number)
print alpha(letter, number)

The problem I have is an error on line 5 that says 'letter' is not defined. I feel like there should be a for loop but, I don't know how to incorporate it. Please help me.

zip works on iterables (strings and lists are both iterables), so you don't need a for loop to generate the pairs as zip is essentially doing that for loop for you. It looks like you want a for loop to print the pairs however.

Your code is a little bit confused, you'd generally want to define your variables outside of the function and make the function as generic as possible:

def alpha(letter, number):
    for pair in zip(letter, number):
        print pair[0], pair[1]

letter = "abcdefghij"
number = [1,2,3,4,5,6,7,8,9,10]
alpha(letter, number)

The error you are having is due to the scope of the variables. You are defining letter and number inside of the function, so when you call alpha(letter,number) they have not been defined.

For printing the result you could iterate the result of zip , as in the following example:

def alpha(letters, numbers):
    for c,n in zip(letters,numbers):
        print c,n

letters = "abcdefghij"
numbers = range(1,11)
alpha(letters, numbers)

Output:

a 1
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
j 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM