简体   繁体   English

在while循环中打印function不打印

[英]print function in while loop not printing

I'm new to python and i have several questionable things that are happening.我是 python 的新手,我有几件可疑的事情正在发生。 I am trying to figure out what i'm doing wrong with this problem:我试图弄清楚我在这个问题上做错了什么:

This exercise assumes you have completed Programming Exercise 7, Random Number File Writer.本练习假设您已完成编程练习 7,随机数文件编写器。 Write another program that reads the random numbers from the file, display the numbers, and then display the following data: • The total of the numbers • The number of random numbers read from the file编写另一个程序,从文件中读取随机数,显示数字,然后显示以下数据: • 数字的总数 • 从文件中读取的随机数的数量

Writing the file:编写文件:

import random

def main():

    randomcount = int(input('How many numbers should i generate?'))

    randomfile = open('randomnumber.txt', 'w')

    total = 0
    for numbers in range(randomcount):
        number = random.randint(1,100)
        total+= number
        randomfile.write((str(number)) + '\n')
        randomfile.write((str(total)) + '\n') 

    randomfile.close()
    print('File updated')

main()

output: output:

How many numbers should i generate?5 (enter)
file updated                    -       **Question 1**
file updated                     | ---- this is new.. while doing 
file updated                    -       trial and error this started
                                        repeating. First 2 times then 
                                        after awhile 3 times. 
                                        Refreshed kernel and outputs 
                                        still does this

reading the file: <-- # main issue读取文件:<-- #主要问题

def main():
    randomfile = open('randomnumber.txt','r')

    contents = randomfile.readline()

    while randomfile !='':
        total = randomfile.readline()

        contents = contents.rstrip('\n')
        total = total.rstrip('\n')

        print(contents)

        contents = randomfile.readline()

   print('total: ',total)
   randomfile.close()

main()

output: output:

90                      -
22                       |
17                       |--- Randomly generated
2                        |
75                      -
        **Question 2**
        <--- print('total: ', total) not showing up


        -
         |
         |
         |
         .   **Question 3**
         .   <--------- Space goes on forever like if its printing 
         .              space. so much that theres a scroll bar just
         .              for empty space. if i try to scroll all the 
         |              way to the bottom so that i can see if maybe 
         |              its printing at the end i never reach the end 
         |              of it because for some reason the program 
        -               keeps adding more and more space.

change readline to readlines hopefully, that should work希望将readline更改为readlines ,这应该可以

Clearly the issue is that in your first line you opened with a single quote ' and closed with a double quote " . Change:显然问题在于,在您的第一行中,您使用单引号'打开并以双引号"关闭。更改:

def main():

    randomcount = int(input('How many numbers should i generate?"))

to:至:

def main():

    randomcount = int(input('How many numbers should i generate?'))

The problem is that the line that writes the total is being execute each iteration.问题是写入总数的行正在执行每次迭代。 That's why there are double the number of lines as there are generated numbers.这就是为什么生成的数字是行数的两倍。

The solution is unindenting that line, which I did here:解决方案是取消缩进该行,我在这里做了:

import random

def main():

    randomcount = int(input('How many numbers should i generate?'))

    randomfile = open('randomnumber.txt', 'w')

    total = 0
    for numbers in range(randomcount):
        number = random.randint(1,100)
        total+= number
        randomfile.write((str(number)) + '\n')
    randomfile.write((str(total)) + '\n') # <<<<<<<<<<<<<<This line was indented, it is fixed now.

    randomfile.close()
    print('File updated')

main()

EDIT: Fixing the read function:编辑:修复读取 function:

def main():
    randomfile = open('randomnumber.txt', 'r')
    lines = randomfile.readlines()
    total = 0

    for line in lines:
        if line is lines[-1]:
            print(f"Total: {line.replace('\n', '')}") #Since the write function includes the total as the last line, you don't need to calculate here.
        else:
            print(line.replace('\n', ''))

main()

I restructured my code and made it a for loop instead of a while loop.我重组了我的代码,并使其成为 for 循环而不是 while 循环。 You don't need to rstrip numbers that are being converted to int.您不需要 rstrip 正在转换为 int 的数字。 Put the accumulator in the input file portion instead of the output file portion.将累加器放在输入文件部分而不是 output 文件部分。 Mae the code cleaner and it works! Mae 代码清理器,它的工作原理!

import random随机导入

def main():

    randomcount = int(input('How many numbers should i generate?'))

    randomfile = open('randomnumber.txt', 'w')

    for numbers in range(1,randomcount + 1):
        numbers = random.randint(1,100)

        randomfile.write(str(numbers) + '\n') 

    randomfile.close()

    randomfile = open('randomnumber.txt','r')
    total = 0

    for numbers in randomfile:
        numbers = int(numbers)
        total+= numbers

        print(numbers)
    print('total',total)

main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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