Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python สุ่มตัวเลข 1-20 และเพิ่มลงใน List

สร้างฟังก์ชันสุ่มตัวเลขในช่วงที่กำหนดและเพิ่มลง List ด้วย random.randint() และ append()

ตัวอย่างโค้ด

import random

def random_gen(beg, end, my_num):
    my_result = []
    for j in range(my_num):
        my_result.append(random.randint(beg, end))
    return my_result

my_num = 19
beg = 1
end = 20
print("The number is :")
print(my_num)
print("The start and end values are :")
print(beg, end)
print("The elements are : ")
print(random_gen(beg, end, my_num))

ผลลัพธ์

The number is : 19
The start and end values are : 1 20
The elements are : [12, 12, 5, 12, 11, 1, 5, 12, 19, 19, 7, 15, 18, 18, 10, 14, 3, 2, 11]

คำอธิบาย

  • ฟังก์ชัน random_gen รับค่าเริ่มต้น, สิ้นสุด, และจำนวนครั้ง
  • วนลูปสุ่มตัวเลข random.randint(beg, end)
  • เพิ่มลง List ด้วย append()
  • คืนค่า List ผลลัพธ์