1. 程式人生 > >Python實踐:猜數字小程序Collatz序列

Python實踐:猜數字小程序Collatz序列

alt 猜數字小遊戲 tin lse error: block con 數字 num

猜數字

  • 代碼
‘‘‘
猜數字小遊戲,不斷輸入你所猜的數(1-100),程序會根據你的輸入提醒你進行
適當調整所猜數的大小,直到最後猜出這個隨機數
‘‘‘
guessNumber = random.randint(1,100)
print("I‘m thinking a number between 1 and 100.")

while True:
    print(‘Take a guess.‘)

    guess = int(input())

    if guess > guessNumber:
        print("It‘s too high")
    elif guess < guessNumber:
        print("It‘s to low")
    else:
        print("Congratulations, you win.")
        break
  • 結果
    技術分享圖片

Collatz序列

  • 代碼
#Collatz序列
def collatz(number):
    if (number % 2 == 0):
        return number / 2
    else:
        return number * 3 + 1

print(‘Input a number.‘)

while True:
    global number1
    try:
        number1 = int(input())
    except ValueError:
        print(‘Please input a number‘)
        continue
    if collatz(number1) != 1:
        print(int(collatz(number1)))
    else:
        print(int(collatz(number1)))
        break
  • 結果
    技術分享圖片

Python實踐:猜數字小程序Collatz序列