this post was submitted on 12 Jun 2024
43 points (93.9% liked)

Python

6378 readers
133 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

๐Ÿ“… Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

๐Ÿ Python project:
๐Ÿ’“ Python Community:
โœจ Python Ecosystem:
๐ŸŒŒ Fediverse
Communities
Projects
Feeds

founded 1 year ago
MODERATORS
 

I'm currently learning Python and am learning about very basic functions such as int(), float(), and input().

I have the first two down pat, but I'm struggling to understand the last. The example I'm looking at is found at 12:26 of this video:

nam = input('Who are you? ')
print('Welcome', nam)

Who are you? Chuck
Welcome Chuck

In this case, wouldn't nam be a variable equal to the text on the right side of the = sign?

In which case, if nam is equal to input('Who are you? '), then wouldn't print('Welcome', nam) just result in

Welcome input(Who are you? )?

Obviously not (nor does it work in a compiler), which leads me to believe I'm clearly misunderstanding something. But I've rewatched that section of the video several times, and looked it up elsewhere on the web, and I just can't wrap my head around it.

Could someone help me with this?

Thanks.

you are viewing a single comment's thread
view the rest of the comments
[โ€“] ICastFist@programming.dev 4 points 5 months ago (1 children)

Yes, you got the gist of how it works.

To give a bit more context, functions are basically snippets of code that are executed when called. One way to look at the input("What's your name?") function is this (not how the actual function looks like, just an abstraction):

function input(text_to_show):
    print(text_to_show)
    input_from_user = get_keyboard_input()
    return input_from_user

That return is something you will see often in many functions, and when you call a function, that's the result it sends to the line that called. So, if input was actually coded like this:

function input(text_to_show):
    print(text_to_show)
    input_from_user = get_keyboard_input()
    return 1

Every time you called it, you would receive 1 as a result. In your example, nam = input('Who are you? ') would always assign 1 to nam, because the return is 1 rather than the variable that receives whatever you typed in.

That's so cool! Thank you!