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.
So what it comes down to is that
int()
,float()
, andinput()
(as well asprint()
) are functions that you are calling. In the case ofint()
andfloat()
, they return (simply put, when you make a function call it “becomes” the return value) anint
orfloat
type object based on the argument (the value between the parentheses) that you passed in. In the case ofprint()
, it causes the program to print out the provided argument.input()
is a little more complicated. It prints out the provided argument (in your case:Who are you?
) and then puts the program on pause while it waits for the user to input some text and press enter. Once they have done so, theinput
function returns the text the user has entered. So as mentioned before, the codeinput('Who are you? ')
“becomes” the text the user input, which then gets assigned to the variablenam
.I think where you may be getting confused is what exactly defines “text”. The only things that python considers text (referred to as a
string
) are characters surrounded by “” or ‘’. In your example,input('Who are you? ')
is not a string, but code to be executed (although the argument being passed toinput
,'Who are you? '
, is a string). As an experiment, try surrounding that code with quotation marks (name = "input('Who are you? ')"
) and see what happens!Oh! I get it now!
It’s because while int() and float() are instantaneous, while input() uses the fourth dimension, time, and thus depends on a future input by the user. (May not make sense the way I’m putting it, but it makes sense to me. Lol.) In other words, while float() and int() have all the data they need to produce an output (i.e. what’s in the parentheses), input() “outputs” the text in the parentheses, then puts itself into a pending state to await further user input, then outputs that second user input.
Am that about the right of it? :)
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, ifinput
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!
U got this 😎
Yay!
The only actual good answer.
I think you’ve already gotten some good answers here regarding the function itself:
It sits and waits for the user to input something and hit Enter, and returns the value the user entered, which is then assigned to your
nam
variable. (See the documentation for the function.I might also offer the advice of confirming your understanding of the flow of a program. That is, understand that, in the general sense, the computer must resolve the right-hand side of the equals sign to a value before it can assign it to the left.
For example, if the right-hand side is a literal value, it’s already resolved. For example, a line like
name = “Joe”
is easy—assign the string literal “Joe” to the variablename
, when the line is run.If the right hand side is a mathematical equation, it must be resolved to a value when the line is run. For example, for a line like
value = 2+2
, the2+2
must be resolved to4
before it can be assigned to the variable.Then, for something like
name = input(“Who are you?”)
, in order to resolve the right-hand side, the computer must first run the function before it can assign a value to the variablename
.It can, of course, get more complicated, where you can call multiple functions on a line, and the results of one feed into the next, and so on. But, that can be an exercise for the near future.
That’s a good point! That is something I’ve noticed. Traditional mathematics uses PEMDAS, which is bidirectional, but Python uses…PEMDRAS, I guess, which is...bi-monodirectional(?), that is, left-to-right in all cases, except in the exception of variables which is right-to-left.
I swear this makes sense to me. My brain just thinks weirdly. Haha.
If it helps, think of the contents of the variable as being the result of the formula. If the formula is 2 + 2, the result is 4. The variable is the value we are trying to determine. If I want to know my speed, I calculate distance / time. So in Python I would say speed = distance / time, because speed is the unknown that I want to know.
But then with Python we can have more complex “formulas”. For example, we can say laugh = “Ho” * 3
Yeah, you can multiply a string. The result is that print(laugh) prints “HoHoHo”.
In the example you gave, the function is the formula, so input() evaluates to a result that is stored in the variable.
If functions are nested, each nested function resolves before the one that contains it. So, for example, you can do print(input("Who are you? ")). The nested function (input) resolves first, obtaining the user input, which is then printed. The difference is that doing it this way just prints directly without storing the input as a variable.
You can also do print("Hello ", input("Who are you? ")). Again, the nested function resolves first, so the user is presented a prompt to give their name. Then print combines the two comma separated statements ("Hello ", and the result of the input function) to display “Hello <name>”. Try it for yourself.
But then with Python we can have more complex “formulas”. For example, we can say laugh = “Ho” * 3
Yeah, you can multiply a string. The result is that print(laugh) prints “HoHoHo”.
Okay, that’s just fucking cool. :3
You’re setting ‘nam’ to whatever the output of the function called ‘input’ is. The string asking who are you is an argument to the ‘input’ function. What that function does happens to be that it prints its argument out to the console, waits for the user to enter text, and returns whatever text was entered as its output. I would recommend actually trying out the code and playing around with it if you want to understand it better.
The other two functions you mentioned work similarly. The output of the function named ‘int’ is a new integer. Usually you will give it a number as an argument to set the value of that integer.
“The other two functions work similarly” noo I wouldn’t say that! :D On a very abstract way, maybe. But especially to a beginner, they don’t. One just processes it’s input a bit (casting) while the other displays text, reads from stdin, etc.
I believe OPs confusion stems exactly from presuming strong similarities between all functions, while only
float()
andint()
are similar andinput()
being a completely different thing (relatively speaking…)
You’re setting the
nam
var to whatever the user input is.input()
prompts the user to input a value.Perhaps an example with another function helps, but I will use a list of numbers (lists’ syntax uses square brackets).
values = [1, 2, 3] total = sum(values)
I’m not sure if I’m the best at explaining this, as I’m more fluent in C++, but effectively what is happening is you’re providing a prompt for the user’s input. The user’s input is then assigned to the variable.
In a lot of languages, this would be two lines of code and look something like this:
Output:"Please enter your name" Name=input
Python is trying to simplify this process
So input(x) prints out x and then puts itself into a waiting mode of sorts, waiting for the user to supply a value, and then once it has that value it outputs that particular value.
Am I right?
Yeah, pretty much!
Thanks!
nam
is assigned the value returned byinput
.This is not some edge case behavior by the
input
function. This is always how function calls work. You can think of it like substitutinginput('Who are you? ')
with the value returned by it, which is the string typed in by the user in this case.Many people have given you answers of varying lengfhs, so I feel free to ask my counter-question…
You say you had int() and float() but would do you assume would happen if you had just replaced ‘input(Who are you?)’ with ‘int(7)’? What value would be assigned to name if the statement was ‘nam = int(7)’?
Following the logic you’re espousing in the OP, ‘nam’ would be equal to the string “int(7)” and the print statement would output “Welcome int(7)”. Either you understand why that wouldn’t be the case and should see why your original example works. Or you don’t and you should double check your understanding of functions and keep tapping people here for help.
I think I misworded my thoughts, to be honest.
As I understand it:
int(2.1) would print out 2 since it just converts it to an integer by truncating it.
float(2) would print out 2.0 since it just converts it to a floating-point value by appending a .0 to the end.
I feel the need to point out that a float isn’t an integer with a decimal stuck on. A floating point number is called that because the precision on both sides of the decimal point changes depending on the size of the number.
It’s actually stored as an exponent and a value to apply the exponent to. This allows you to express incredibly tiny numbers and incredibly large numbers, but the gaps between representable numbers is inconsistent.
You know how 10 / 3 * 3 is often not 10 because the decimal representation loses the repeating .33? In float, you run into the same issue but in much less predictable places.
Oh!
I think I’ve not quite gotten to that part yet in the lesson. Lol.
But it’s good to know, so thanks for pointing that out! I’ll be sure to remember it when I get to that point. Haha.
A lot of responses here so I’ll suggest a different approach. You can watch your python code execute line by line using a debugger. That might help with understanding how it all works.
def my_sum(list): result = 0 for number in list: result += number return result my_list = [1, 2, 3, 4, 5] list_sum = my_sum(my_list) print(list_sum) # Prints 15
If you run the above code line by line in a debugger, you’ll see that when it gets to
list_sum = my_sum(my_list)
the program will jump into the functionmy_sum(list)
where “list” is a variable holding the value of “my_list”. The program continues line by line inside of the function until it hits thereturn result
statement. The program then returns to the line it was at before jumping into the function. “my_sum(my_list)” now has an actual value. It’s the value that the return statement provided. The line would now readlist_sum = 15
to python.A debugger shows you which lines get executed in which order and how the variables update and change with each line.
Just a note: python has a built-in
sum()
function you could use instead of writing your ownmy_sum()
function, but a debugger won’t show you how built-in functions work! They’re built into the language itself. You’d need to look up Python’s documentation to see how they actually function under the hood.I think you need to look into string concatenation, the easiest and best of which is f strings. You could do something like;
print(f’welcome, {nam}')
You could also “add” the strings together.
print('welcome, ’ + nam)
Another thing, when assigning the output of something to a variable, you can think of it as “the result of the code right of the equals sign is the value of the variable”.
The input function assumes that the value should be interpreted as a string, but what if want it to be a number? You can just wrap another function around your input
user_number = int(input(‘what’s the number?’))
user_number = int(input(‘what’s the number?’))
But then what’s
input('what's the number?')
result in? I understand int() and float(), but I can’t wrap my head around what exactlyinput
does to the text within the succeeding parentheses.Edit: I get it now! Another user helped me understand it, and I get it now! Thank you for your help too! You’re awesome!
Yup. You’ll see functions wrapped inside other functions all the time. The function on the inside will run first, then the next, etc.
In the example I gave, the value of nam is a string. But it you need to perform some mathematical function to it, it needs to be interpreted as a number. So once the value is received, int() will convert it into a number. Finally, that final value will be assigned to nam. Wrapping functions inside of functions is a great way to write concise code.
That’s pretty cool. It’s almost like a…time-based Excel function! Lol.
@EveryMuffinIsNowEncrypted i maybe wrong
input() is a python function that accepts arguments and returns value of type string.
int() and float() are special type of functions called constructor, magical.
int, or integer, on itself is a datatype like str, or string, is a datatype, to create an int you’d use its costructor int(‘23’) something like that
int is a builtin datatype, so by typing 23, you already have an instance of int
input
prints the text based as an argument to the command line, waits for the user to type text followed by a new line to the command line, and returns the text as a string as its return value.TLDR
input
asks the user for text via the command line.
I recommend u try one of those free online python programming learning things with inbuilt quizzes etc they tend to explain programming in a way that someone who doesnt program can understand better than a programmer ever can. Once u know how to program one language u pretry much know em all and are now completely incapable of describing thibgs without thinking about it as a programmatic proccess.
No,
nam
is a placeholder for whatever is inputed into the function input by the user when the program is ran. Input prints to screen whatever you put () when you first call it. It expects something to then be inputted by the user when the program runs by prompting the user with the message in the (). Whatever the user inputs is then referred to by the variable, in this case “Chuck” was inputted.It will make a bit more sense when you start writing functions, you can return whatever results you want from calling a function. Those returns will be referred to by the variable you label it, word on the left of the =.
In short, whatever is returned by a function is what is “saved” in the variable.
You got a club? Maybe a nine iron? How about some mayo and a few lacrosse balls?
I will definitely make you understand that input variable.
...I am confuzzled and slightly afraid. :|