ในบทช่วยสอนนี้ เราจะเรียนรู้วิธีรับอินพุตหลายรายการจากผู้ใช้ใน Python .
ข้อมูลที่ป้อนโดยผู้ใช้จะอยู่ใน สตริง รูปแบบ. ดังนั้นเราจึงสามารถใช้ split() วิธีแบ่งข้อมูลที่ผู้ใช้ป้อน
ลองใช้หลายสตริงจากผู้ใช้
ตัวอย่าง
# taking the input from the user
strings = input("Enter multiple names space-separated:- ")
# spliting the data
strings = strings.split()
# printing the data
print(strings) ผลลัพธ์
หากคุณเรียกใช้โค้ดด้านบน คุณจะได้ผลลัพธ์ดังต่อไปนี้
Enter multiple names space-separated:- Python JavaScript Django React ['Python', 'JavaScript', 'Django', 'React']
เกิดอะไรขึ้นถ้าเราต้องการนำตัวเลขหลายตัวเป็นอินพุต? เราสามารถแปลงอินพุตแต่ละรายการเป็นจำนวนเต็มโดยใช้ แผนที่ และ int การทำงาน. มาดูตัวอย่างกัน
ตัวอย่าง
# taking the input from the user
numbers = input("Enter multiple numbers space-separated:- ")
# spliting the data and converting each string number to int
numbers = list(map(int, numbers.split()))
# printing the data
print(numbers) ผลลัพธ์
หากคุณเรียกใช้โค้ดด้านบน คุณจะได้ผลลัพธ์ดังต่อไปนี้
Enter multiple numbers space-separated:- 1 2 3 4 5 [1, 2, 3, 4, 5]
บทสรุป
คุณสามารถแก้ไขรหัสตามความต้องการของคุณและรับข้อมูลจากผู้ใช้ หากคุณสอบถามในบทช่วยสอน โปรดระบุในส่วนความคิดเห็น