简体   繁体   中英

Is there a way to use a variable in a 'for loop' inside python?

i need to make a program for school that prints the amount of lines in a text file and the amount of times the user input is inside the file. So my idea was to make two loops, one that counts the amount of lines in the file, and one that counts how many times the letter that the user put in is in the file. like this:

def file_len(fname):
    amountOfLines = 0
    line = ''
    with open(fname, 'r') as f:
        for line in f:
            amountOfLines += 1
    return amountOfLines

letter= input('Put in a letter: ')
amountOfTimes= 0

for letter in open('scripting week 5.txt', 'r'):
    amountOfTimes += 1
print('The amount of lines in the file is', file_len('scripting week 5.txt'))
print('The letter you put in appears', amountOfTimes, 'times.')

But that doesn't work, because the for loops are not taking my variables as variables, they are just iterating through the file. Is there any way i could make this work, or will i have to start over from scratch with a different approach?

I hope you guys can help me, any help would be greatly appreciated! ps. pls note that i am a complete python noob, so excuse my dumb question.

Your file_len function is fine. You just have to modify the for-loop that you use to count the number of occurrences of the letter:

for line in open('scripting week 5.txt', 'r'):
    for char in line:
        if char==letter:
            amountOfTimes+= 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM