วันพฤหัสบดีที่ 5 พฤษภาคม พ.ศ. 2559

การประกาศตัวแปรในภาษา python


ตอนที่ 2 การประกาศตัวแปรในภาษา python

data types ในภาษา python มีคร่าวๆดังนี้

Types are a category for things within Python with which Python will work. Types are
integers 
Whole numbers from negative infinity to infinity, such as 1, 0, -5, etc.
float 
Short for "floating point number," any rational number, usually used with decimals such as 2.8 or 3.14159.
strings 
A set of letters, numbers, or other characters.
tuples 
A list with a fixed number of elements. ie x=(1,2,3) parentheses makes it a tuple.
lists 
A list without a fixed number of elements. ie x=[1,2,3] note the square brackets, a list
dictionaries 
A type with multiple elements i.e. x = {1: 'a','b': 2,3: 3} where you address the elements with, e.g., a text.

เผิ่นว่ามี data types ชนิดต่างๆใน python ดังนี้
intergers ก็คือตัวเลขต่างๆตั้งแต่ค่าลบ ไปจนถึงค่าบวกเช่น 1,0,-5, อื่นๆ
float เป็นชื่อย่อของ floating point numer คือจำนวนจริงที่ใช้กับเลขฐาน 10 เช่น 2.8 หรือ 3.14159
strings ก็คือเซ็ทของข้อความ, ตัวเลข, หรืออักขระอื่นๆ
tuples คือ รายการของจำนวนตัวเลขที่มีการกำหนดค่าคงที่ เช่น x=(1,2,3) อยู่ในวงเล็บ
lists คือ รายการของตัวเลขที่ไม่ได้ถูกกำหนดค่าคงที่ เช่น x=[1,2,3]
dictionaries คือชนิดของข้อมูลหลายองค์ประกอบ เช่น x={1:'a','b':2,3:3} 
where you address the elements with, e.g., a text.
------
การประกาศตัวแปร
ก็พิมพ์ค่าของตัวแปรเข้าไปได้เลยโดยไม่จำเป็นต้องระบุชนิด เหมือนภาษา C/C++
ซึ่งถือว่าค่อนข้างง่ายมากๆ 
เช่น 

a=10
b=20.3
c='a'
d=(1,2,3)
e=[4,5,6]
x={1: 'a','b': 2,3: 3}

print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(x))

ลองรันดูด้วยคำสั่ง python3 ตามด้วยชื่อไฟล์ที่ท่านเขียน ก็จะได้



<class 'int'>

<class 'float'>

<class 'str'>

<class 'tuple'>

<class 'list'>

<class 'dict'>


ออกทางหน้าจอ

ลืมบอกไปเรื่องคำสงวน คือคำที่ไม่สามารถเอามาใช้เป็นชื่อตัวแปรได้ มีดังนี้

คำสงวน
            คำสงวน คือ ชื่อหรือคำที่ภาษาไพธอนสงวนไว้เฉพาะเพื่อใช้เป็นคำสั่ง   หรือมีไว้เพื่อเขียนเป็นโครงสร้างของตัวภาษาเอง ฉะนั้นผู้เขียนโปรแกรมจึงควรหลีกเลี่ยงคำสงวนเหล่านี้ในการตั้งชื่อโปรแกรม  ตัวแปร  หรือชื่อใด ๆ ก็ตามที่ตั้งขึ้นมาใหม่แล้วตรงกับคำสงวน  คำสงวนมีด้วยกัน 31 คำดังต่อไปนี้
and
as
assert
break
class
continue
def
del
elif
else
except
exec
finally
for
from
global
if
import
in
is
lambda
not
or
pass
print
raise
return
try

แหล่งที่มาแอบอ้าง
https://en.wikiversity.org/wiki/Python/Basic_data_types
https://sites.google.com/site/dotpython/installation/variable

ไม่มีความคิดเห็น:

แสดงความคิดเห็น