2

I need help with some code with I can't get to work, I have to make code so that it prints;

Country    Capital
France     Paris 
Uk         London
Belgium    Brussels
etc..

This is what I have wrote so far..

Country = ["France","UK","Belgium","Spain"]
Capital = ["Paris","London","Brussels","Madrid"]
print("\n\t Country \t Capital")
for country in Country:
  print("\t",country)
for capital in Capital:
  print("\t",capital)

but it prints ;

 Country     Capital
 France
 UK
 Belgium
 Spain
 Paris
 London
 Brussels
 Madrid

i cant seem to get the capitals to be under the capital section. please help, thanks

armallah
  • 101
  • 1
  • 7

2 Answers2

4

It's because you're using two separate loops to print, so they come one after the other, you'll want one loop, like this:

Country = ["France","UK","Belgium","Spain"]
Capital = ["Paris","London","Brussels","Madrid"]
print("\n\t Country \t Capital")
for i in range(len(Country)):
  print("\t",Country[i], "\t", Capital[i], "\n")

That way, you'll have tab-separated columns instead of all the countries, then all the capitals.

Will
  • 4,299
  • 5
  • 32
  • 50
  • Note that your print syntax inside the for-loop only works in Python 3. To keep it compatible with both Python 2 and 3, I'd recommend changing the loop print statement to this: `print("\t%s\t%s" % (Country[i], Capital[i]))` – Niema Moshiri Nov 21 '17 at 19:17
  • @NiemaMoshiri, no, it works in Python 2 as well, just prints a tuple. – ForceBru Nov 21 '17 at 19:18
  • @ForceBru, But printing a tuple isn't the intended output format specified by OP: the output is supposed to be tab-delimited country-capital pairs – Niema Moshiri Nov 21 '17 at 19:19
  • 1
    @NiemaMoshiri The `print` function is available in Python 2.6+ via `from __future__ import print_function`. You really shouldn't use the `print` statement in new code these days. – PM 2Ring Nov 21 '17 at 19:26
  • @PM2Ring, I agree, but this import was not included in the solution. It should at least be mentioned for it to be complete – Niema Moshiri Nov 21 '17 at 19:28
  • 1
    @NiemaMoshiri The OP has tagged the question Python 3, so there's no need to make a solution that also works on Python 2. – PM 2Ring Nov 21 '17 at 19:35
3

You can do this in a one-liner:

print("\n".join("\t".join(t) for t in zip(Country, Capital)))

output:

France  Paris
UK      London
Belgium Brussels
Spain   Madrid
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54