Python Forum
Why does my code not execute? (def function with 'for in' iteration over a dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why does my code not execute? (def function with 'for in' iteration over a dictionary
#1
Hi^^

I have troubles to find my mistake within following code:
def printPicnic(itemsDict, leftWidth, rightWidth):
    print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-'))
    for k, v in itemsDict.items():
        print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth))
        picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies':8000}
        printPicnic(picnicItems, 12, 5)
        printPicnic(picnicItems, 20, 6)
I have checked the code line by line several times and compared to the description my my study book, but could not spot my mistake.
It just would not execute.

Anyone could help out and hint me where I got it wrong?

Regards,
Placebo
Reply
#2
Last 3 lines should be outside the function, i.e. no indentation at all
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(Oct-18-2018, 06:07 AM)Placebo Wrote: It just would not execute.
In fact this code does execute very well, but you don't see anything because all it does is define a function named printPicnic and this function is never called. As Buran said you need to unindent the last three lines to obtain the intended effect.
Reply
#4
Omg, Im obviously still such a big noob xD

Thanks a lot for clearing it up:)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  passing dictionary to the function mark588 2 956 Dec-19-2022, 07:28 PM
Last Post: deanhystad
  Can a program execute code in iPython shell and get result? deanhystad 3 1,722 Jun-17-2022, 03:45 AM
Last Post: Larz60+
  Dictionary within html code ebolisa 4 2,579 Aug-09-2021, 11:36 AM
Last Post: ebolisa
  Putting code into a function breaks its functionality, though the code is identical! PCesarano 1 1,976 Apr-05-2021, 05:40 PM
Last Post: deanhystad
  Writing a lambda function that sorts dictionary GJG 1 2,010 Mar-09-2021, 06:44 PM
Last Post: buran
  Using Dictionary to Test Evenness of Distribution Generated by Randint Function new_coder_231013 6 3,247 Feb-23-2021, 01:29 PM
Last Post: new_coder_231013
  Picking a function to execute palladium 1 1,597 Feb-09-2021, 04:47 PM
Last Post: deanhystad
  Iterating over a dictionary in a for loop - checking code has worked sallyjc81 1 1,917 Dec-29-2020, 05:14 PM
Last Post: ndc85430
  list call problem in generator function using iteration and recursive calls postta 1 1,888 Oct-24-2020, 09:33 PM
Last Post: bowlofred
  new help with dictionary and dataframe iteration AlphFinan 0 1,514 Oct-13-2020, 11:04 PM
Last Post: AlphFinan

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020