繁体   English   中英

从多个打印语句打印到同一行

[英]Print to the same line from multiple print statements

更新:它来了。 尽管如此,它仍然存在一些问题,我需要将行号和推荐星号打印在与乐谱相同的行上。 这没有发生。

这是代码:

def main():
    fil_inp_stu = open("student_test_scores.txt", "r")

    #Variables
    num_rec = 0
    num_com = 0
    per_com = 0
    total_scores = 0
    avg_scores = 0
    
    print("#\tScore\tCommendation\n----------------------------")

    one_score = fil_inp_stu.readline()
    
    while one_score != "":

        one_score_int = int(one_score)
        print("\t", one_score_int)

        num_rec = num_rec + 1
        print(f"{num_rec}:")
       
        one_score = fil_inp_stu.readline()

        total_scores += one_score_int
        avg_scores = total_scores / num_rec

        per_com = num_com / num_rec

    
        num_com = one_score_int >= 100
        while num_com:

          print("\t\t\t*")
          break 
    
   
      

    print(f"\nNumber of records: {num_rec}")
    print(f"Average test score: {avg_scores:.2f}")
    print(f"Number of commendations: {num_com}")
    print(f"Percentage of commendations: {per_com:.2%}")
     
    fil_inp_stu.close()

main()

这是 output:

#   Score   Commendation
----------------------------
     69
1:
     9
2:
     129
3:
            *
     131
4:
            *
     146
5:
            *
     109
6:
            *
     71
7:
     69
8:
     18
9:
     129
10:
            *
     94
11:
     53
12:
     25
13:

Number of records: 13
Average test score: 80.92
Number of commendations: False
Percentage of commendations: 0.00%

感谢到目前为止的帮助

这是你要找的吗? 不确定我是否理解正确。

def main():
    print("#\tScore\tCommendation\n----------------------------")

    num_records = 0
    total_scores = 0

    with open("student_test_scores.txt", "r") as fil_inp_stu:
        one_score = fil_inp_stu.readline()

        while one_score != "":
            num_records += 1

            one_score_int = int(one_score)
            total_scores += one_score_int

            if one_score_int > 100:
                print(f"\t{one_score}*")
            else:
                print(f"\t{one_score}")

            one_score = fil_inp_stu.readline()

    avg_score = total_scores // num_records

    print(
        f"Number of records: {num_records}"
        f"Total scores: {total_scores}"
        f"Average score: {avg_score}"
    )


main()

请注意,我添加了一个上下文管理器(带有语句)以简化并使其更安全。 如果您的代码在到达 .close() 行之前崩溃,那么对于 open 和 close 语句,您将面临导致文件出现问题的风险。

暂无
暂无

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

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