循环退出意外的Python

时间:2015-09-05 14:20:29

标签: python loops python-3.x for-loop ascii-art

我正在创建一个程序,该程序使用以ASCII艺术编写的A-Z文件。该程序需要3行输入:Hight,Width和要写入的单词(全部大写和空格)。我设法让程序打印迭代的第一个字母,但由于某种原因,似乎我设置的for循环停止了。

temp = []
hi = input('Height: ')
wi = input('Width: ')
tx = input('Text: ')
fi = open("font.txt")
for n in range(len(tx)):
    for i in tx:
        temp = cd[i]
        var1 = int(temp[0])
        ra1 = (var1 * int(hi))
        ra1n = (ra1 + int(hi))
        temp = []
        lines = fi.readlines()
        print(''.join(lines[ra1:ra1n]), end='')

这是它输出的内容

Height: 8
Width: 9
Text: WOW

|\     /|
| )   ( |
| | _ | |
| |( )| |
| || || |
| () () |
(_______)

2 个答案:

答案 0 :(得分:1)

您正在尝试重新读取font.txt而不倒回文件位置。

添加file.seek(0)调用,或在循环外读取一次文件;在循环之外使用lines = fi.readlines()比每次使用fi.seek(0)更有效。

你的循环也太多了;你不需要在这里循环range(len(tx)),因为你已经遍历tx本身。

with open("font.txt") as fi:
    lines = fi.readlines()

for character in tx:
    var1 = int(cd[character])
    ra1 = (var1 * int(hi))
    ra1n = (ra1 + int(hi))
    print(''.join(lines[ra1:ra1n]), end='')

答案 1 :(得分:0)

file.seek(0)之前循环尝试lines = fi.readlines()

    temp = []
    hi = input('Height: ')
    wi = input('Width: ')
    tx = input('Text: ')
    fi = open("font.txt")
    for n in range(len(tx)):
        for i in tx:
            temp = cd[i]
            var1 = int(temp[0])
            ra1 = (var1 * int(hi))
            ra1n = (ra1 + int(hi))
            temp = []
            fi.seek(0) # Here
            lines = fi.readlines()
            print(''.join(lines[ra1:ra1n]), end='')

或打开循环中的file

temp = []
hi = input('Height: ')
wi = input('Width: ')
tx = input('Text: ')
for n in range(len(tx)):
    for i in tx:
        temp = cd[i]
        var1 = int(temp[0])
        ra1 = (var1 * int(hi))
        ra1n = (ra1 + int(hi))
        temp = []
        fi = open("font.txt") # Here
        lines = fi.readlines()
        print(''.join(lines[ra1:ra1n]), end='')