如何打印之前/多个行?

2024-06-01 07:21:22 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: keyinfromnumberinputiftypeexit
2条回答

反转您的测试,使它们基于>=,而不是==,并且不要使用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.")

我所做的是把它们倒过来,这样它们就从最大到最小打印出来,并使==变成>;=如果它大于那个数字就打印出来

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)

相关问题 更多 >