เมื่อต้องการสร้าง Dictionary ที่มีตัวเลขในช่วงที่กำหนดในรูปแบบเฉพาะ ให้รับ input จากผู้ใช้ และใช้ลูป 'for' ธรรมดา
ตัวอย่าง
my_num = int(input("Enter a number.. "))
my_dict = dict()
for elem in range(1, my_num + 1):
my_dict[elem] = elem * elem
print("The generated elements of the dictionary are : ")
print(my_dict)
ผลลัพธ์
Enter a number.. 7
The generated elements of the dictionary are : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49}
คำอธิบาย
- รับตัวเลขจากผู้ใช้
- สร้าง Dictionary ว่าง
- วนลูปตัวเลข
- เก็บกำลังสองของตัวเลขใน Dictionary
- แสดงเป็นเอาต์พุทบนคอนโซล