Devdit
 

Input ใน Python คืออะไร ใช้ทำอะไร

2.2K

Input ใน Python คือ คำสั่งสำหรับรับค่าจากผู้ใช้งานผ่าน command prompt โดยสามารถรับเป็นข้อมูลใดๆ ก็ได้ เช่น ตัวอักษร ข้อความ ตัวเลข หรืออักขระพิเศษ สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง Input ใน Python คืออะไร ใช้ทำอะไร

try:
    name = input('What is your name ? ')
    age = int(input('How old are you ? '))
except:
    name = ''
    age = 0

if name != '' and age > 0 :
    print('Hello,',name,age,'year old')

ผลลัพธ์

What is your name ? Devdit
How old are you ? 99
Hello, Devdit 99 year old

คำอธิบาย

1. ใช้คำสั่ง input รับค่าชื่อเก็บไว้ที่ตัวแปร name เป็นชนิดข้อความ (String)

2. ใช้คำสั่ง input รับค่าอายุเก็บไว้ที่ตัวแปร age โดยมีการแปลงค่าที่รับมาให้เป็นชนิดตัวเลข (Integer)

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