1

I am new to Python and I understand this might be a naive question but I am so confused:

My question is what is the difference between line 13 and 24 in the image below? I want to see a value of something, when should I use print() and when just having the value will print it? for example, in line 13 if I don't put the print there, it doesn't show me the value. However the exact same thing in line 24 it will show me the value.

the same thing about type, when should I use it this way :print(type(a)) to see the type on the screen and when type(a) will be sufficient to see the type?

Is there a problem with the site that I am practicing with or is there something deeper that I am missing?

enter image description here

Marios
  • 26,333
  • 8
  • 32
  • 52
Sean
  • 81
  • 1
  • 7
  • 2
    Normally if you're typing commands into a Python interactive session, if you enter an expression, its value will be output in the session. But if you're writing a script, you need to `print` something to output to stdout when the script is executed. – khelwood Aug 21 '20 at 22:33
  • 1
    By default, Jupyter will print the output of the last instruction, such as line 24. If there are multiple items in one interactive cell, they need print statements. Otherwise, change the interactive shell parameter to `all`. [How to display full output in Jupyter, not only last result?](https://stackoverflow.com/questions/36786722) – Trenton McKinney Aug 21 '20 at 22:49
  • the first one prints the result of the expression, the other one simply evaluates the expression. – juanpa.arrivillaga Aug 21 '20 at 23:16

2 Answers2

1

As have been mentioned in the previous comments. It is really related to how you run the code. If you are typing/copying it line by line in an interactive terminal, including or not including print will both show you the results. However, when you are running the script as a whole (instead of line by line putting into the terminal), only the line where you use print will be printed out.

If it's too much to remember for now, just use print for everything, and you will get to see whatever you want to print out on the screen.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Yolanda
  • 13
  • 2
1

Thanks to all. As mentioned by @Trenton,Jupyter will print the output of the last instruction. If there is only one, no need to put the print(), otherwise changing the interactive shell parameter to all solves the issue.

The following link advised by @ Trenton is for further reference is very useful: How to display full output in Jupyter, not only last result?

Sean
  • 81
  • 1
  • 7