亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何打印上一行/多行?

如何打印上一行/多行?

大話西游666 2021-06-08 13:08:36
key = int(input("Choose a Christmas Gift from 1 to 5!")) if type(key) != type(0):  print("Please enter a number.")  exit() if not (1 <= key <= 5):  print(key,"is an invalid number.")  exit()if key == 1: print("1 Partridge in a Pear Tree.")elif key == 2: print("2 Turtle Doves.")elif key == 3: print("3 French Hens.")elif key == 4: print("4 Calling Birds.")elif key == 5: print("5 Golden Rings.")我已經走了這么遠(我對此很陌生,我做了我在課堂上看到的),但是當你輸入一個數字時,我不知道如何打印前幾行。假設我輸入 3。輸出應該是:3 french hens.2 turtle doves1 partridge in a pear tree.它應該對所有有效數字都這樣做。編輯:我將 eval 更改為 int。任何建議都有幫助!謝謝你。
查看完整描述

2 回答

?
烙印99

TA貢獻1829條經驗 獲得超13個贊

反轉您的測試,使它們基于>=、not==和不使用elif(這使得通過的第一個測試阻止任何其他測試執行),只是簡單的if. 現在,每個通過的測試都會按順序打印。


if key >= 5:

    print("5 Golden Rings.")

if key >= 4:

    print("4 Calling Birds.")

if key >= 3:

    print("3 French Hens.")

if key >= 2:

    print("2 Turtle Doves.")

if key >= 1:

    print("1 Partridge in a Pear Tree.")


查看完整回答
反對 回復 2021-06-22
?
精慕HU

TA貢獻1845條經驗 獲得超8個贊

我所做的是反轉它們,以便它們從最大到最小打印,如果大于該數字,則將 == 設置為 >= 進行打印。


from sys import exit

key = int(input("Choose a Christmas Gift from 1 to 5!"))

if type(key) != type(0):

    print("Please enter a number.")

    exit()

if not (1 <= key <= 5):

    print(key,"is an invalid number.")

    exit()


if key >= 5:

    print("5 Golden Rings.")

if key >= 4:

    print("4 Calling Birds.")

if key >= 3:

    print("3 French Hens.")

if key >= 2:

    print("2 Turtle Doves.")

if key >= 1:

    print("1 Partridge in a Pear Tree.")

但是,如果您想擴展它,請執行以下操作:


from sys import exit

    key = int(input("Choose a Christmas Gift from 1 to 5!"))

    if type(key) != type(0):

        print("Please enter a number.")

        exit()

    if not (1 <= key <= 5):

        print(key,"is an invalid number.")

        exit()

gifts = ["1 partridge in a pair tree","2 turtle doves","etc..","etc..","etc.."]

printer = [print (val) for ind,val in enumerate (gifts) if ind >=key]

打印機通過使用列表理解來工作,這與所說的相同


for ind,val in enumerate(gifts):

   if ind >= key:

      print(val)


查看完整回答
反對 回復 2021-06-22
  • 2 回答
  • 0 關注
  • 253 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號