Python Forum

Full Version: help with assignment 2
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I have to write a program:
1. User enters the upper and lower range.
2. The code generates a random number, divisible by x and y.
I have to use the random module and list comprehension.

x=5 and y=7
I've done this so far...

low=int(input("Enter start number:"))
upp=int(input("Enter end number:"))
for i in range (low,upp+1):
    if(i%7==0 and i%5==0):
        import random
            list_nums = ["low","upp"]
            random.choice(list_nums)
Thanks in advance for your help!
First, import random should be at the top of the code. You want to import it once, not repeatedly in a loop.

You've got the right idea, to use random.choice on a list of numbers. However, you are not building the list right. Your loop and your if condition are good: they give you the numbers in the range that are factors of the desired numbers. But what you want to do it initialize list_nums to an empty list ([]) before the loop, and then in the conditional append the new number to list_nums.

Then, after the loop is done, you do the random.choice from the finished list.
I'm still doing something wrong...

import random
low=int(input("Enter start number:"))
upp=int(input("Enter end number:"))
list_nums = ["low","upp"]
a = []
random.choice(list_nums)
for i in range (low,upp+1)
    if(i%7==0 and i%5==0):
              list_nums.append(a)
              print (a)
list_nums should be defined as an empty list, random.choice should come after the loop and not before it, and you should append i to list_nums, not a (you don't need a at all).
Thanks, I made the changes !