简体   繁体   中英

Trying to extract an amount of numbers from a list in a range in python 3 using user input as starting point

x = input("How many numbers, between two and six?  ")
print("You have selected, " + x + " numbers!")
import random     # I would like to only print out the amount of numbers entered in the first line!!!
numbers = list(range(1,48))   # So if a user types six they get six random numbers and so on.
random.shuffle(numbers)
print(numbers)

After shuffling the list you can just pick x numbers from it;

for i in range(0,x):
    print(i)

This does of course assume the input is a number, and you've set the input as an integer with x = int(input("text")) .

import random
x = input("How many numbers, between two and six?  ")
print("You have selected, " + x + " numbers!")
numbers = list(range(1,48))
print([random.choice(numbers) for x in range(int(x))])

random.choice(numbers) is a function that takes a argument that must be list and give you any random number as return value, the for loop is used to run random.choice() function for range defined by x. suppose user enter the value 2 so we have x=2 then our for loop will run 2 times and we have 2 random value as output from our numbers list.

try this:

    for x in range(int(x)):
        print(random.randint(1, 48))

it will work you can also append into the list if you want.

have you tried this

import random

x = input("How many numbers, between two and six?  ")
print("You have selected, " + x + " numbers!")
li = [random.random() for x in range(int(x))]
print(li)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM