19. Create Your Own


#1


https://www.codecademy.com/courses/python-beginner-en-cxMGf/2/6?curriculum_id=4f89dab3d788890003000096

Your code threw the following error: 'set' object has no attribute 'getitem'

I expect the statement to be executed. Do I need to add an "else" statement?

a = {'ten', 'eleven', 'twelve', 'seven'}
for n in a:
    print a, a[key]


#2

problem1.

a = {'ten', 'eleven', 'twelve', 'seven'}

Your dictionary does not have keys.

eg..

if x is a dictionary..

x = {"a": 1, "b": 3}

"a" , "b" are called keys.
1,2 are called corresponding values.

so dictionary is collection ofkey: value pairs.

Problem2:
You have to use for/else statement (as mentioned in instruction)


#3

I modify my code with this:

n = {"a": 'ten', "b": 'eleven', "c": 'twelve', "d": 'seven'}
for n in a:
print n, n[key]

I just could not think of an 'else' statement.


#4

You have to use for/else statement now..

syntax of for/else..

for x in something:
    if condition:
        #your code
else:
    #yourcode

#5

Tried this new code:

n = {"a": 'ten', "b": 'eleven', "c": 'twelve', "d": 'seven'}
for n in a:
if n == "b"
print n, n[key]
else:
print n

What am I doing wrong now?


#6

Have you noticed that for and else have same indentation level ?
(also after if statement use break so it can stop any further loopings)


#7

Should they be indented at the same level?


#8

in for/else statement ! Yes!

for x in something:
    if condition:
        #your code
else:
    #yourcode

Not this..

for x in something:
    if condition:
        #your code
    else:
        #yourcode

#9

Thanks, that tip helped me well!


#10

Youre welcome! :thumbsup:


#11

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.