Advertisement
Rementai

Range jako generator

Mar 23rd, 2023
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.20 KB | None | 0 0
  1. def my_range(*args):
  2.     number_of_args = len(args)
  3.     if number_of_args == 1:
  4.         start, stop, step = 0.0, args[0], 1.0
  5.     elif number_of_args == 2:
  6.         start, stop, step = args[0], args[1], 1.0
  7.     elif number_of_args == 3:
  8.         start, stop, step = args[0], args[1], args[2]
  9.     else:
  10.         raise ValueError("Function needs 1 to 3 arguments.")
  11.  
  12.     if step == 0:
  13.         raise ValueError("Step argument cannot be 0")
  14.  
  15.     while step > 0 and start < stop:
  16.         yield start
  17.         start += step
  18.     while step < 0 and start < stop:
  19.         yield stop
  20.         stop += step
  21.  
  22.  
  23.  
  24. def main():
  25.     try:
  26.         for val in my_range(1.1, 2.2, 0.5):
  27.             print(val, end=" ")
  28.         print()
  29.         for val in my_range(1.1, 2.1, 0.5):
  30.             print(val, end=" ")
  31.         print()
  32.         for val in my_range(1.1, 2.2):
  33.             print(val, end=" ")
  34.         print()
  35.         for val in my_range(2.2):
  36.             print(val, end=" ")
  37.         print()
  38.         for val in my_range(1.1, 2.2, -0.5):
  39.             print(val, end=" ")
  40.         print()
  41.         for val in my_range():
  42.             print(val, end=" ")
  43.  
  44.     except ValueError as e:
  45.         print("Error:", e)
  46.  
  47. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement