Devdit
 

Python รับค่าหลายตัว ด้วย for loop และ input

8.5K

สอนเขียนภาษา Python เพื่อรับค่าหลายตัว ด้วยคำสั่ง for loop และคำสั่ง input โดยจะวนลูปเท่ากับจำนวนที่ผู้ใช้งานกรอกเข้ามา สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง Python รับค่าหลายตัว ด้วย for loop และ input

try:
    rounds = int(input('Please enter the number of rounds : '))
except:
    rounds = 0

input_ = []
for v in range( rounds ):
    v = v + 1
    input_.append( input('Please input '+str(v)+' : ') )

print( input_ )

ผลลัพธ์

Please enter the number of rounds : 4
Please input 1 : 10
Please input 2 : 20
Please input 3 : 30
Please input 4 : 50
['10', '20', '30', '50']

คำอธิบาย

1. โค้ดด้านบนรับค่าจำนวนการ input จากผู้ใช้งาน และเก็บไว้ในตัวแปร n

2. สร้างตัวแปร input_ เป็นชนิด List

3. ใช้คำสั่ง for เพื่อวนลูปรับค่า ตามจำนวนค่าของตัวแปร n

4. รับค่า และเก็บผลลัพธ์ไว้ในตัวแปร input_ ด้วยคำสั่ง append

5. พิพม์ผลลัพธ์ออกมาด้วยคำสั่ง print

แก้ไข 2 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ