204111:lab1-code

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา

เน้นให้พิมพ์ตามและทดลองใช้ Wing IDE

โปรแกรมแรก: เกมทายเลข

ทายเลข ครั้งเดียว

<geshi lang="python"> from random import randint

s = randint(1,100) a = int(input("Guess a number (1 - 100):")) if a < s:

   print("Your guess is too low.  The answer is",s)

if a > s:

   print("Your guess is too high.  The answer is",s)

if a == s:

   print("You guessed correctly.")

</geshi>

ทายเลขจนกว่าจะถูก

<geshi lang="python"> from random import randint

s = randint(1,100) a = -1 while s != a:

   a = int(input("Guess a number (1 - 100):"))
   if a < s:
       print("Your guess is too low.")
   if a > s:
       print("Your guess is too high.")

print("You guessed correctly.") </geshi>

ทายเลขจนกว่าจะถูกนับจำนวนครั้งด้วย

<geshi lang="python"> from random import randint

s = randint(1,100) t = 0 a = -1 while s != a:

   a = int(input("Guess a number (1 - 100):"))
   t = t + 1
   if a < s:
       print("Your guess is too low.")
   if a > s:
       print("Your guess is too high.")

print("You guessed correctly. You guessed", t, "times.") </geshi>

โปรแกรมสอง: คอมพิวเตอร์ทายเลข

<geshi lang="python"> low = 1 high = 100

correct = False

while not correct:

   g = int((high + low) / 2)
   print("My guess is",g)
   hint = input("Please give your hint (H for too high, L for too low, C for correct:")
   if hint == 'H':
       high = g - 1
   if hint == 'L':
       low = g + 1
   if hint == 'C':
       correct = True

</geshi>