首頁 >後端開發 >Python教學 >Python 日循環練習、數字遊戲和任務

Python 日循環練習、數字遊戲和任務

Barbara Streisand
Barbara Streisand原創
2024-11-29 22:31:15372瀏覽

Python Day-Looping-Exercises,Number game and Tasks

1)寫一個程式來取得以下輸出:
1 2 3 4 5 5 4 3 2 1

no = 1
top = 5
direction = 1
while no>0:
    print(no,end= ' ')
    if no == top:
        print(no,end=' ')
        direction = -1
    no = no + direction

輸出:

1 2 3 4 5 5 4 3 2 1

使用隨機模組:

2) 猜數字遊戲:
程式將一直運行直到我們猜出數字

import random

system_no = random.randint(1,20)

while True:
    guess = int(input("Enter the No. "))
    if guess == system_no:
        print("Hurray!  I got the number!! ")
        break
    elif guess > system_no:
        print("Your guess is too high! ")
    else:
        print("Your guess is too Low! ")

輸出:

Enter the No. 5
Your guess is too Low! 
Enter the No. 7
Your guess is too Low! 
Enter the No. 10
Your guess is too Low! 
Enter the No. 12
Hurray!  I got the number!! 

3) 數字中最大的數字:

no = int(input("Enter no. "))
max_no = 0
while no>0:
    rem = no%10
    if rem>max_no:
        max_no = rem
    no//=10

print(max_no)

輸出:

Enter no. 452
5

所以在 452 中,5 是數字中最大的數字。

任務:

1) 找出數字中最小的數字:

no = int(input("Enter no. "))
min_no = 9
while no>0:
    rem = no%10
    if rem<min_no:
        min_no=rem
    no//=10

print(min_no)

輸出:

Enter no. 452
2

2) 判斷所有數字是否相等

no=input("Enter the no. ")

num=1

while num <len(no):
    if no[num]==no[0]:   
        print("All digits are equal")
        break
    num+=1

else :
    print("Not equal")

輸出:

1)Enter the no. 4444
  All digits are equal
2)Enter the no. 46562
Not equal

以上是Python 日循環練習、數字遊戲和任務的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn