Devdit
 

เกมทายตัวเลข 1 ถึง 100 Python

7.2K

สอนเขียนเกมทายตัวเลข 1 ถึง 100 Python สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง เกมทายตัวเลข 1 ถึง 100 Python

import random

def gameRandom( number ):
    r = random.randint(1, 100)

    if( number > 0 and number < 101 ):
        if( number == r ):
            print(str(number)+' guess the number correctly')
        else:
            print(str(number)+' guess the wrong number, the correct number is '+str(r))


gameRandom( 10 )
gameRandom( 60 )
gameRandom( 99 )

ผลลัพธ์

10 guess the wrong number, the correct number is 21
60 guess the wrong number, the correct number is 5
99 guess the wrong number, the correct number is 94

คำอธิบาย

1. สร้างฟังก์ชันชื่อ gameRandom รับค่า 1 ตัวชื่อ number

2. ตัวแปร r เก็บค่า random ของเกมส์ทายตัวเลข โดย random ระหว่าง 1 - 100

3. กรณีตัวแปร number ตรงกับตัวแปร r แปลว่าทายถูก จะพิมพ์ข้อความว่า guess the number correctly

4. กรณีตัวแปร number ไม่ตรงกับตัวแปร r แปลว่าทายผิด จะพิมพ์ข้อความว่า guess the wrong number, the correct number is ตามด้วยตัวเลขที่ถูก

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