Devdit
 

ValueError: invalid literal for int() with base 10: Python คือ วิธีแก้ไข

4.9K

รันโค้ด Python รับค่าตัวเลขจากผู้ใช้งานด้วยคำสั่ง input กรณีถ้าใส่ข้อมูลทุกอย่างทำงานได้ปกติ แต่ถ้าไม่ใส่ข้อมูล หรือใส่แต่ไม่ใช่ตัวเลข จะขึ้นข้อความ Error ว่า ValueError: invalid literal for int() with base 10 ต้องแก้ไขอย่างไร

print("======= CRUD Python =======\n")
print("1. SELECT\n")
print("2. INSERT\n")
print("3. UPDATE\n")
print("4. DELETE\n")
print("===========================\n")
action = int(input("Please input number: ")

ผลลัพธ์

Please input number:
Traceback (most recent call last):
  File "D:\crud.py", line 9, in <module>
    action = int(input("Please input number: "))
ValueError: invalid literal for int() with base 10: ''

 

วิธีแก้ไข

ปัญหานี้เกิดจากตัวแปร action ต้องรับค่าเป็นตัวเลขจากผู้ใช้งาน กรณีหากผู้ใช้งานไม่ใส่ข้อมูลที่เป็นตัวเลขจะขึ้น Error ดังกล่าว แนะนำให้ใช้ try except เพื่อป้องกันปัญหาดังกล่าว สามารถเขียนโปรแกรมได้ดังนี้

print("======= CRUD Python =======\n")
print("1. SELECT\n")
print("2. INSERT\n")
print("3. UPDATE\n")
print("4. DELETE\n")
print("===========================\n")
action = int(input("Please input number: ")
try:
    action = int(input("Please input number: "))
except:
    action = 0

print(action)

นำโค้ดที่คาดว่าจะเกิด Error ไว้ใน try และกรณีถ้าเกิด Error ให้เขียนคำสั่งที่ต้องการลงใน except จากตัวอย่างโค้ดด้านบนกรณีถ้าผู้ใช้งานไม่ใส่ข้อมูลที่เป็นตัวเลข กำหนดให้ตัวแปร action เท่ากับ 0 ซึ่งจะไม่ทำให้โปรแกรมเกิด Error ValueError: invalid literal for int() with base 10 เกิดขึ้น เพราะตัวแปร action จะเป็นตัวเลขเสมอ (เลข 0) ถึงแม้ผู้ใช้งานจะไม่กรอกตัวเลขเข้ามาก็ตาม

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