Stupid Beginner Question 2


#1

This seems like it should work, but it doesn’t:

print(“Which file would you like to open?”)
filevar=input()
open(filevar)
print(filevar)

Instead I have to use a variable to open another variable, like this:
print(“Which file would you like to open?”)
filevar=input()
openfile=open(filevar)
print(openfile.read())

Why do I need a 2nd variable to open the 1st variable?


#2

Because when you do open(filevar) it opens it, and now you need to read the opened file => open(filevar). You can not read filevar, because filevar is the un-opened file. Same with print, you must print the read opened file.


#3

There are no stupid questions. Just remember computers are dumb and need to be told things explicitly. They cannot make assumptions based on the context you were ‘talking’ in.


#4

@io_io and @gpkesley are right. Computers need to be told everything.
But it’s not true that you need a second variable to read the file. You could just do that:

print(open(filevar).read())

How you do it will mostly be a matter of what you want to achieve.


#5

What you see here is called ‘imperative programming’ and it means that a program consists of a sequence of instructions that dictate in what order what should be done by the computer.

In this particular example it is something like this:

Hope that helps.

For more info about this you can read here: https://en.wikipedia.org/wiki/Imperative_programming

There are some other programming paradigms such as ‘functional programming’, ‘object oriented programming’, ‘logical programming’ and others.


#6

These are all good explanations but let me add one more:

“Hey @dmatine, could you go get me a burrito and a puppy? I need to eat it.”

The above sentence is unclear because the word “it” could be the burrito or puppy. Now, we’re smart so we go “I’m sure Zed doesn’t want to eat a puppy sooooo…” but computers are stupid so when you don’t make everything very explicit they have no idea what you mean.

What you did was write the python version of this. You said, “Hey python, open the file named filevar and print it.” Python has no idea what you mean, and looking at this code you might not either. You need a variable to save the results of the open() call so that you can be explicit and say, “Hey python, open the file named filevar, save that file in openfile, read openfile, and print the results of reading openfile.”

It’s annoying, but if you aren’t explicit and let the computer guess then you’ll potentially have a hidden bug you can’t hunt down and will be very confused. It’s better to be more verbose and clear than to be loose and leave it up to the interpreter.


#7

Awesome explanation @zedshaw. That explicit thing is exactly what I struggled the most on the beginning, and still do a lot of times. That sentence about the burrito and the puppy is superb.