猿问

如何打印上一行/多行?

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 doves

1 partridge in a pear tree.

它应该对所有有效数字都这样做。


编辑:我将 eval 更改为 int。


任何建议都有帮助!谢谢你。


大话西游666
浏览 259回答 2
2回答

烙印99

反转您的测试,使它们基于>=、not==和不使用elif(这使得通过的第一个测试阻止任何其他测试执行),只是简单的if. 现在,每个通过的测试都会按顺序打印。if key >= 5:&nbsp; &nbsp; print("5 Golden Rings.")if key >= 4:&nbsp; &nbsp; print("4 Calling Birds.")if key >= 3:&nbsp; &nbsp; print("3 French Hens.")if key >= 2:&nbsp; &nbsp; print("2 Turtle Doves.")if key >= 1:&nbsp; &nbsp; print("1 Partridge in a Pear Tree.")

精慕HU

我所做的是反转它们,以便它们从最大到最小打印,如果大于该数字,则将 == 设置为 >= 进行打印。from sys import exitkey = int(input("Choose a Christmas Gift from 1 to 5!"))if type(key) != type(0):&nbsp; &nbsp; print("Please enter a number.")&nbsp; &nbsp; exit()if not (1 <= key <= 5):&nbsp; &nbsp; print(key,"is an invalid number.")&nbsp; &nbsp; exit()if key >= 5:&nbsp; &nbsp; print("5 Golden Rings.")if key >= 4:&nbsp; &nbsp; print("4 Calling Birds.")if key >= 3:&nbsp; &nbsp; print("3 French Hens.")if key >= 2:&nbsp; &nbsp; print("2 Turtle Doves.")if key >= 1:&nbsp; &nbsp; print("1 Partridge in a Pear Tree.")但是,如果您想扩展它,请执行以下操作:from sys import exit&nbsp; &nbsp; key = int(input("Choose a Christmas Gift from 1 to 5!"))&nbsp; &nbsp; if type(key) != type(0):&nbsp; &nbsp; &nbsp; &nbsp; print("Please enter a number.")&nbsp; &nbsp; &nbsp; &nbsp; exit()&nbsp; &nbsp; if not (1 <= key <= 5):&nbsp; &nbsp; &nbsp; &nbsp; print(key,"is an invalid number.")&nbsp; &nbsp; &nbsp; &nbsp; 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):&nbsp; &nbsp;if ind >= key:&nbsp; &nbsp; &nbsp; print(val)
随时随地看视频慕课网APP

相关分类

Python
我要回答