จะรับค่าจากผู้ใช้งานด้วย Python ยังไง
Python ใช้คำสั่ง input สำหรับรับค่าจากผู้ใช้งานผ่านแป้นพิมพ์
name = input('What is you name: ')
print('Hello '+name)// ผลลัพธ์
What is you name: Devdit
Hello Devditโค้ดนี้รับค่าข้อความ (string) ด้วยคำสั่ง input เก็บค่าไว้ในตัวแปรชื่อ name
และใช้คำสั่ง print แสดงข้อความ Hello ตามด้วยค่าของตัวแปร name
แล้วถ้าต้องการรับค่าตัวเลขด้วยคำสั่ง input ละ
number = int(input('Please input number: '))
print('You input number '+str(number))// ผลลัพธ์
Please input number: 8
You input number 8เพิ่มคำสั่ง input คลุมคำสั่ง input เพื่อแปลงค่าที่รับเป็นตัวเลข
เวลาแสดงก็อย่าลืมใช้คำสั่ง str เพื่อแปลงตัวเลขเป็นข้อความก่อน
ลองเขียนรับค่าตัวเลขทศนิยม แต่เกิด Error
f = int(input('Please input float: '))
print('You input float: '+str(f))Please input float: 10.98
Traceback (most recent call last):
File "C:\python\code.py", line 1, in
f = int(input('Please input float: '))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: '10.98'เกิด Error เพราะคำสั่ง int ไม่สามารถรับค่าตัวเลขทศนิยมได้ ให้ใช้ float แทน
f = float(input('Please input float: '))
print('You input float: '+str(f))// ผลลัพธ์
Please input float: 10.98
You input float: 10.98ยอดเยี่ยมไปเลย
คำสั่ง input มีประโยชน์อย่างมากสำหรับการรับค่าจากผู้ใช้งาน
ถูกต้อง แต่ต้องให้ความสำคัญกับชนิดของข้อมูลที่จะรับเข้ามาด้วย
| รับข้อความ หรือตัวอักษร เช่น 'Devdit', 'D' | ใช้ input หรือ str ร่วมกับ input |
| รับตัวเลข เช่น 10, -20 | ใช้ int ร่วมกับ input |
| รับตัวเลขทศนิยม เช่น 98.45, -12.69 | ใช้ float ร่วมกับ input |
ประมาณนี้ก่อน ไว้เจอกันใหม่บทหน้า
แล้วเจอกัน เดียวทักไป