Create your own


#1



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


Hey guys, my code is working fine, no errors. However i'm not getting the result that i'm trying to achieve.
Just to be clear, i'm trying to get this printed out in a separate line:
Reactive metals are made up of:
Element Caesium
Element Potassium

I'm trying to get "K": "Potassium" printed out as well. My question is why isn't the 2nd condition 'elif x == "K":' not working?


PeriodicTable = {
    "Mg": "Magnesium",
    "Cs": "Caesium",
    "K": "Potassium",
    "Fe": "Iron"
    } 
print "Reactive metals are made up of: "
for x in PeriodicTable:
    if x == "Cs":
        print "Element", PeriodicTable[x]
    elif x == "K":
        print "Element", PeriodicTable[x]
    else:
        break
    print "The rest are non-reactive metals"


#2

break will break the loop, so the moment you have a non-reactive metal, the loop ends


#3

PeriodicTable = {
    "Mg": "Magnesium",
    "Cs": "Caesium",
    "K": "Potassium",
    "Fe": "Iron"
    } 
print "Reactive metals are made up of: "
for x in PeriodicTable:
    if x == "Cs":
        print "Element", PeriodicTable[x]
    elif x == "K":
        print "Element", PeriodicTable[x]
    else:
        print "The rest are non-reactive metals"

Thanks! I removed break, however i'm now getting this result.

Reactive metals are made up of:
Element Caesium
The rest are non-reactive metals
Element Potassium
The rest are non-reactive metals
None

I'm trying to get something like this:

Reactive metals are made up of:
Element Caesium
Element Potassium
The rest are non-reactive metals
None

that explains why i placed break to break the loop and now i understand that it breaks the loop completely. May i ask what can i do to make the loop not read the else statement when the first if condition is met?


#4

this would require that your loop only prints the reactive metals, and then after the loop you print the rest are non-reactive metals


#5

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