Python Forum
Output with none, print(x) in function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Output with none, print(x) in function
#4
I think putting a print statement in odd_numbers() is bad design. It makes the function useless. I cannot use your odd_numbers() to get a list of odd numbers for the program I am writing. I don't want the printing numbers side effect messing up the output in my program.

For something like this maybe I want a generator.
def odd_numbers(start=1, end=None):
    if start % 2 == 0:
        start += 1
    while True:
        if end and start > end:
             break
        yield start
        start += 2

# If I want to print odd numbers
print('Count from 11 to 21 by 2')
for x in odd_numbers(11, 21):
    print(x)

# If I want a list of odd nmbers
a = list(odd_numbers(1, 7))
b = [x for x in odd_numbers(13, 21)]
print('Combined lists =', a+b)

# Or an unknown number of odd numbers
odds_gen = odd_numbers()
odds = []
while sum(odds) < 100:
    odds.append(next(odds_gen))
print(f'sum{odds} = {sum(odds)}')
You would never do something like this for odd numbers. They are way too easy to generate ad hoc. But you might do this for a different sequence that is not so easy to generate and that might have several different uses.
Reply


Messages In This Thread
RE: Output with none, print(x) in function - by deanhystad - Nov-24-2020, 05:40 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  print doesnt work in a function ony 2 311 Mar-11-2024, 12:42 PM
Last Post: Pedroski55
  problem in output of a function akbarza 9 1,209 Sep-29-2023, 11:13 AM
Last Post: snippsat
  Python VS Code: using print command twice but not getting output from terminal kdx264 4 1,105 Jan-16-2023, 07:38 PM
Last Post: Skaperen
  How to print variables in function? samuelbachorik 3 916 Dec-31-2022, 11:12 PM
Last Post: stevendaprano
  How to output one value per request of the CSV and print it in another func? Student44 3 1,351 Nov-11-2022, 10:45 PM
Last Post: snippsat
  How to print the output of a defined function bshoushtarian 4 1,318 Sep-08-2022, 01:44 PM
Last Post: deanhystad
Sad Want to Save Print output in csv file Rasedul 5 10,993 Jan-11-2022, 07:04 PM
Last Post: snippsat
  Why does absence of print command outputs quotes in function? Mark17 2 1,390 Jan-04-2022, 07:08 PM
Last Post: ndc85430
  return vs. print in nested function example Mark17 4 1,757 Jan-04-2022, 06:02 PM
Last Post: jefsummers
Photo print output none 3lnyn0 4 1,842 Nov-01-2021, 08:46 PM
Last Post: 3lnyn0

Forum Jump:

User Panel Messages

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