Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
question about loops
#8
There is one print, the print in the function named Q9().
def Q9(n):
    for i in range(n):
        print(i)
Q9(5)
Output:
0 1 2 3 4
As rob101 said, you can modify the print command to put all the output on 1 line.
def Q9(n): # n is an arbitrary variable name
    for i in range(n):
        print(i, end=" ")  # This prints numbers
Q9(5)  # This calls the function that prints the numbers
Output:
0 1 2 3 4
jIn both instances there is 1 print for each number counting up from 0 to n. It is just a matter of printing all the numbers on one line or separate lines.

If that doesn't resolve your confusion, there is one other thing that may be producing extra output in a jupyter notebook.

Jupyter is a bit odd in that it automatically prints results without having to call print(). If you call a function and it returns a result that is not None, jupyter automatically prints the result. I modified Q(n) to return n. Jupyter will see a non-None result and print it. This code will print the numbers, then it prints n.
def Q9(n):
    for i in range(n):
        print(i, end=" ")
    return(n)
Q9(5)
Output:
0 1 2 3 4 5
The automatic printing can be suppressed by adding a semicolon to the end of the line.
def Q9(n):
    for i in range(n):
        print(i, end=" ")
    return(n)
Q9(5);
If you are seeing extra prints that you don't expect, look for function calls that return values. To stop them from printing, add semicolons to those lines.
Reply


Messages In This Thread
question about loops - by rpang - Nov-05-2022, 07:19 AM
RE: question about loops - by rob101 - Nov-05-2022, 07:58 AM
RE: question about loops - by rpang - Nov-05-2022, 08:03 AM
RE: question about loops - by rpang - Nov-05-2022, 08:25 AM
RE: question about loops - by rob101 - Nov-05-2022, 08:31 AM
RE: question about loops - by rpang - Nov-05-2022, 11:11 PM
RE: question about loops - by rob101 - Nov-05-2022, 11:47 PM
RE: question about loops - by deanhystad - Nov-07-2022, 09:42 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Homework help:While Loops question Midhat_School 6 3,187 Jul-26-2020, 10:23 AM
Last Post: pyzyx3qwerty

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020