Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

I wanted to test out the different scopes of this example, so I added print statements to the function and it got weird.

So I added the code below and when I run it in my Python shell the result is 5 and a, not 10 and b like I would expect. Any thoughts on how that would happen?

num = 10
letter = 'b'

def set_num():
    num = 5
    letter = 'a'
    print(num)
    print(letter)

set_num()

For the record, I'm executing this script with phython3 functions.py

2 Answers

Mark Sebeck
MOD
Mark Sebeck
Treehouse Moderator 38,304 Points

I would expect 5 and a to be printed inside the function. Inside those values would override. Try printing outside the function after the function call and you should get 10 and b.

It looks like that printed 10 and b. Thanks!

Mark Sebeck
Mark Sebeck
Treehouse Moderator 38,304 Points

You are welcome. Another ‘fun’ thing to try would be to print the values in the function before you assign 5 and a. Should be 10 and b at that point.