(Mar-24-2020, 10:30 PM)pythonuser1 Wrote: I want to optimize it. I have these two lines print(i,r) and return(r ). Is there a way I can get rid of one of these two lines and yet have the correct output giving only the multiple of a number ? I am asking this because the return(r ) sends "4" and in the 'if condition' I did not find an another way besides "print(i,r)" to show the multiples of a number.
- You should use Python 3. Currently you're using Python 2.7, which is outdated since January 2020.
- Encoding comment is not needed for Python 3. All source files are encoded with utf8
- Instead of comments, you can use docstrings
- You should change the shebang to #!/usr/bin/env python3
- Your function has side effects. Side effect means, that your function modifies the environment (print to stdout) and return a value. A Pure function takes arguments, does the work and return the result. Nothing else happens beside. Easy fix: remove the print from this function
- Use better names for objects. n, i, r are bad names.
- Give the user the flexibility to call your function with different range for start and end.
- To get rid of return, you could use a generator.
#!/usr/bin/env python3 # value is a positional argument # start and stop are keyword-only-arguments, the * does this def multiple_of(value, *, start, stop): """ Les nombre multiples de value compris entre start et stop start is inclusive stop is inclusive """ for factor in range(start, stop + 1): if factor % value == 0: yield factor, factor // value # <- this are the values for each step # which goes to the consumer multi_gen = multiple_of(15, start=1, stop=60) # multi_gen is a generator, lazy evaluation, no values yet my_results = list(multi_gen) # list consumes the generator print(my_results) # a generator can be consumed only once and then it's exhausted # if you need the elements in a different datatype as a list: # multi_gen = multiple_of(15, start=1, stop=60) # my_results = tuple(multi_gen) # You can also iterate over the generator: for result in multiple_of(15, start=1, stop=60): print(result) # Bonus # You can create also a dict from the results. # my_results_as_dict = dict(multiple_of(15, start=1, stop=60))
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!