Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีตรวจสอบเลขคี่/เลขคู่ด้วย Python

ตัวดำเนินการ Modulo (%) ของ Python (เรียกอีกอย่างว่า Remainder Operator) มีประโยชน์ในการกำหนดว่าเลขเป็นคี่หรือคู่ เราหาเศษจากการหารเลขด้วย 2 หากเป็น 0 คือเลขคู่ มิฉะนั้นคือเลขคี่

no = int(input('enter number: '))
if no % 2 == 0:
    print('{} is even'.format(no))
else:
    print('{} is odd'.format(no))

ผลลัพธ์

enter number 25
25 is odd
enter number 40
40 is even