0
0
Pythonprogramming~15 mins

Why scope matters in Python - See It in Action

Choose your learning style9 modes available
Why scope matters
๐Ÿ“– Scenario: Imagine you are organizing a small party. You have a list of guests and a separate list of snacks. You want to count how many guests and snacks you have, but you need to keep these counts separate so they don't get mixed up.
๐ŸŽฏ Goal: You will create two separate counts for guests and snacks using variables inside and outside a function to see how scope affects their values.
๐Ÿ“‹ What You'll Learn
Create a list called guests with exactly these names: 'Alice', 'Bob', 'Charlie'
Create a list called snacks with exactly these items: 'Chips', 'Cookies'
Create a variable called guest_count and set it to 0
Create a function called count_snacks that creates a variable snack_count and sets it to the length of snacks
Inside the function count_snacks, print the value of snack_count
Outside the function, print the value of guest_count
๐Ÿ’ก Why This Matters
๐ŸŒ Real World
Understanding scope helps you write programs where different parts do not interfere with each other, like keeping guest and snack counts separate at a party.
๐Ÿ’ผ Career
Scope is a basic concept in programming that helps prevent bugs and makes code easier to read and maintain, important for all software development jobs.
Progress0 / 4 steps
1
Create the guest and snack lists
Create a list called guests with these exact names: 'Alice', 'Bob', 'Charlie'. Also create a list called snacks with these exact items: 'Chips', 'Cookies'.
Python
Need a hint?

Use square brackets [] to create lists with the exact names and items.

2
Create the guest count variable
Create a variable called guest_count and set it to 0.
Python
Need a hint?

Use = to assign the number zero to guest_count.

3
Create a function to count snacks
Create a function called count_snacks. Inside it, create a variable called snack_count and set it to the length of the snacks list using len(snacks). Then print the value of snack_count inside the function.
Python
Need a hint?

Remember to indent the lines inside the function.

4
Print guest count and call snack count function
Call the function count_snacks(). Then print the value of guest_count outside the function.
Python
Need a hint?

Call the function by writing its name followed by parentheses. Use print(guest_count) to show the guest count.