0

I am new to coding, and just started learning Python last week. I made this Powerball number generator to practice:

import random

print(random.randrange(1, 70))

import random

print(random.randrange(1,70))

import random

print(random.randrange(1, 70))

import random

print(random.randrange(1,70))

import random

print(random.randrange(1, 70))

import random

print(random.randrange(1,27))

I am wondering, how can I shorten this, since the first 5 "import random prints" are exactly identical?

Thanks ahead for helping a noob!

I V
  • 9
  • 1
  • 2
    Only import once, then use a for loop: `import random ; for _ in range(5): print(random.randrange(1, 70)) ; print(random.randrange(1,27))` – mozway Nov 03 '22 at 13:38
  • @mozway the last print had a different range though – yem Nov 03 '22 at 13:38
  • 1
    @yem - They're importing 5x because they're a beginner: `just started learning Python last week` - passive aggressive questions don't help. – mikeb Nov 03 '22 at 13:48
  • 1
    @mikeb Valid point. I deleted the comment – yem Nov 03 '22 at 13:52

3 Answers3

1

To start, you only need to import random once before you use it for the first time. That should shorten it to this:

import random

print(random.randrange(1, 70))

print(random.randrange(1,70))

print(random.randrange(1, 70))

print(random.randrange(1,70))

print(random.randrange(1, 70))

print(random.randrange(1,27))

then you can shorten it more by creating a loop as @mikeb said in his solution which would make it look like this:

import random

for i in range(4):
   print(random.randrange(1,70))

print(random.randrange(1,27))

Also, while not so relevant for this specific code, a common way to shorten code that contains duplicate code is to place the code in a function like this:

import random

def powerball(n):
    print(random.randrange(1, n))

for i in range(4):
    powerball(70)

powerball(27)
yem
  • 529
  • 1
  • 6
  • 20
0

You only need to import random once, and you can use a loop:

import random

for _ in range(0, 5): # 0, 1, 2, 3, 4
  print(random.randrange(1, 70))

print(random.randrange(1,27))

Note that _ is a valid variable name and is typically what you use for the name of a variable that is not used. In this case, we don't care which iteration we are on (the value of the range generator) so we use _ to show that we are not using it on purpose.

mikeb
  • 10,578
  • 7
  • 62
  • 120
0

You can do it like this.

import random

for x in range(0, 5):
    print(random.randrange(1, 70))

Also imports you dont have to do multiple times. You just do it once in the file. here is some more information about python loops: https://www.w3schools.com/python/python_for_loops.asp