Bayram
Bayram

Reputation: 73

print on the same line after the loop in python

import sys

def main():
    try:
        filename = str(*sys.argv[1:])
        f = open(filename[6:],"r")
        readFile = f.readlines()
        f.close()
        for line in readFile:
            if (readInput(line)=="error"):
                print(line+"=error")

            else:
                exec(line)

    except FileNotFoundError:
        print("Failed to open",filename[6:])

def readInput(txt):
    numOfNonDigit = 0
    numbers = ""

    for char in txt:
        if char.isdigit():
            numbers += char
        elif numbers=="" and char==",":
            return 'error'
        elif char=="," and numbers!="":
            numbers=""
        elif numbers=="" and char==")":
            return 'error'
        elif char==" ":
            return 'error'

    for char in txt:
        if not char.isdigit():
            numOfNonDigit+=1

    if numOfNonDigit>7:
        return 'error'

def add(num1,num2): #https://www.geeksforgeeks.org/sum-two-large-numbers/

    str1 = str(num1)
    str2 = str(num2)
    size1 = len(str1)
    size2 = len(str2)
    carry = 0
    swap = 0
    total = []

    if (size1>40 or size2>40):
        return print("add(" + str1 + "," + str2 + ")=error")

    if (size1>size2):
        temp = str1
        str1 = str2
        str2 = temp
        temp = size1
        size1 = size2
        size2 = temp
        swap = 1

    str1 = str1[::-1]
    str2 = str2[::-1]

    for i in range(size1):
        t=int(str1[i])+int(str2[i])+carry
        if (t>9):
            total.append(t%10)
            carry=1
        else:
            total.append(t)
            carry=0

    for i in range(size1,size2):
        t=int(str2[i])+carry
        if (t>9):
            total.append(t%10)
            carry=1
        else:
            total.append(t)
            carry=0

    if (carry):
        total.insert(size2,1)

    str1 = str1[::-1]
    str2 = str2[::-1]    
    total = total[::-1]

    if (swap==1):
        temp = str1
        str1 = str2
        str2 = temp

    print("add(" + str1 + "," + str2 + ")=", end="")
    print(*total, sep="")

if __name__== "__main__":
  main()

(I will leave the output below) The program should take input from a text file, then add two numbers. At def readInput(), I am trying to catch some errors, like missing number or space between numbers, and etc. So on the line 10-11 I need to output add(a,b)=error, but for some reason, the error output goes on the next line, I tried using end='', it didn't help. Can someone please help me to fix this.

add(1,2)
=error
add(1, 2)
=error
add(1,)
=error
add(1,a)=error

Upvotes: 0

Views: 40

Answers (1)

user11955706
user11955706

Reputation:

maybe you should change this line:

print(line+"=error")

to this line:

print(line.replace("\n", "")+"=error")

Upvotes: 1

Related Questions