如何通过用户输入指定一个范围内所需的数字数量



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

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))))

您只在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))))

只是不要试图重新发明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()

相关内容

  • 没有找到相关文章

最新更新