Python Forum
help with assignment 2
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
help with assignment 2
#1
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!
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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)
Reply
#4
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).
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
Thanks, I made the changes !
Reply


Forum Jump:

User Panel Messages

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