【问题标题】:How to specify the amount of numbers needed in a range with user input如何使用用户输入指定范围内所需的数字数量
【发布时间】:2016-04-18 10:27:25
【问题描述】:

我需要用户输入来指定要在该范围内打印的数字数量。
我有以下代码:

i = 0;
start_char = 65
end_char = 65
x = input("Enter numbers of plates:")
while (i < int(x)):
     if i%26 == 0 and i!= 0:
            end_char = (65)
            start_char += 1

            print((chr(start_char))+(chr(end_char)))
            end_char =end_char + 1
            i = i + 1
     for plate_code in (range(1000)):
         print(str(plate_code)  + ((chr(start_char))+(chr(end_char))))

【问题讨论】:

  • 您遇到了什么问题?
  • 也许您想尝试更高级的方法,使用来自string 模块的ascii_uppercase 和来自product()islice() 模块的islice()。然后外部循环以for start_char, end_char in islice(product(ascii_uppercase, ascii_uppercase), int(x)): 开始。

标签: python python-3.x input user-input


【解决方案1】:

您仅在 if 内部递增 i,并且由于最初是 i = 0,您的代码永远不会进入 if 并陷入无限循环。

i = i + 1 移出if

while (i < int(x)):
     if i%26 == 0 and i!= 0:
            end_char = (65)
            start_char += 1

            print((chr(start_char))+(chr(end_char)))
            end_char =end_char + 1
     i = i + 1  #move incrementation outside of if
     for plate_code in (range(1000)):
         print(str(plate_code)  + ((chr(start_char))+(chr(end_char))))

【讨论】:

  • 我很确定这还不够,增加end_char 也应该在if 之外。它还在用while 重新发明for 循环。
【解决方案2】:

只是不要试图重新发明for 循环:

def main():
    start_char = end_char = 65
    plate_count = int(input('Enter numbers of plates:'))
    for i in range(plate_count):
        if i and i % 26 == 0:
            end_char = 65
            start_char += 1
        print(chr(start_char) + chr(end_char))
        end_char += 1
        for plate_code in range(1000):
            print('{}{}{}'.format(plate_code, chr(start_char), chr(end_char)))


if __name__ == '__main__':
    main()

或者利用标准库的强大功能:

from itertools import islice, product
from string import ascii_uppercase


def main():
    plate_count = int(input('Enter numbers of plates: '))
    for start_char, end_char in islice(
        product(ascii_uppercase, ascii_uppercase), plate_count
    ):
        print('{}{}'.format(start_char, end_char))
        for plate_code in range(1000):
            print('{}{}{}'.format(plate_code, start_char, end_char))


if __name__ == '__main__':
    main()

【讨论】:

    猜你喜欢
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多