Automatically translated.View original post

🔁 Casting to understand!

Data type conversion is a very important basic skill for manipulating and computing data in Python! We use these functions to change the type of a variable:

⚙️ 3 main functions in Casting:

• 1. int() (convert to integer)

• Can accept Int, Float, or String values that are whole numbers.

• Important! If it comes from Float (2.8), the function will truncate the decimal places to 2, not round up!

• 2. float() (convert to decimal)

• Can accept Int, Float, or String numbers (both integer and decimal)

• If it comes from Int (1), it will be a decimal (1.0).

• 3. str() (convert to text)

• Can be obtained from almost any type of data (Int, Float, Bool, List, Dict, etc.)

• The result will always be a String.

💡 Caution: Converting a String to a number (int() or float()) only works if the String is in a valid numeric format, otherwise an error will occur.

Understanding the principles of casting will help make our code more resilient and error-proof.

#programming #programmer #data #ai #learnonlemon8

2025/11/6 Edited to

... Read moreการแปลงชนิดข้อมูล (Casting) เป็นทักษะที่จำเป็นเมื่อต้องทำงานกับข้อมูลหลายประเภทใน Python โดยที่เรามักจะพบปัญหาเมื่อต้องเปลี่ยนชนิดข้อมูลเพื่อให้โปรแกรมทำงานได้ถูกต้องหรือเกิดผลลัพธ์ตามที่ต้องการ ตัวอย่างเช่น การใช้ฟังก์ชัน int() เพื่อแปลงค่าจาก float เช่น 2.8 เป็น 2 จะเกิดการตัดทศนิยมออกโดยไม่ปัดเศษ ซึ่งอาจส่งผลให้ข้อมูลไม่แม่นยำในบางครั้ง ต้องระวังและเลือกใช้ฟังก์ชันแปลงข้อมูลให้เหมาะสมตามบริบท อีกทั้งการแปลงค่าจาก string เป็นตัวเลขต้องตรวจสอบว่าสตริงนั้นเป็นตัวเลขที่ถูกต้องจริงๆ ถ้าเป็น string ธรรมดาที่ไม่ใช่ตัวเลข เช่น "abc" จะทำให้เกิดข้อผิดพลาด (Error) เมื่อแปลงข้อมูล นอกจากฟังก์ชันหลักอย่าง int(), float() และ str() แล้ว ใน Python ยังมีการแปลงข้อมูลชนิดอื่นๆ อีกเช่นการแปลง list เป็น string หรือแปลง boolean เป็นตัวเลข ซึ่งช่วยให้การเขียนโปรแกรมยืดหยุ่นมากขึ้นและเหมาะกับการใช้งานที่หลากหลาย สำหรับผู้เริ่มต้น แนะนำให้ทดลองเขียนโค้ดที่แปลงข้อมูลชนิดต่างๆ ดูผลลัพธ์และตรวจสอบชนิดข้อมูลด้วยฟังก์ชัน type() เพื่อเข้าใจการเปลี่ยนแปลงและการทำงานจริงของฟังก์ชันเหล่านี้ ซึ่งจะช่วยป้องกันข้อผิดพลาดที่อาจเกิดขึ้นในโครงการจริง สุดท้าย การเข้าใจหลักการ Casting อย่างถูกต้องไม่เพียงช่วยให้โปรแกรมทำงานได้อย่างถูกต้อง แต่ยังช่วยพัฒนาโค้ดที่มีความเสถียรและปรับแต่งได้ง่าย ตอบโจทย์ทั้งนักเรียน นักศึกษา และนักพัฒนาที่ต้องการพัฒนาทักษะการเขียนโปรแกรมใน Python อย่างมั่นใจ