Home 03. Arithmetic Operators
Post
Cancel

03. Arithmetic Operators

Problem: Arithmetic Operators

Solution 1: Using print() function

1
2
3
4
5
6
if __name__ == '__main__':
    a = int(input())
    b = int(input())
    print(a+b)
    print(a-b)
    print(a*b)

Solution 2: Using f-string

1
2
3
4
if __name__ == '__main__':
    a = int(input())
    b = int(input())
    print(f'{a+b}\n{a-b}\n{a*b}')

Solution 3: Using format()

1
2
3
4
if __name__ == '__main__':
    a = int(input())
    b = int(input())
    print('{}\n{}\n{}'.format((a+b),(a-b),(a*b)))

Solution 4: Using sep parameter

1
2
3
4
if __name__ == '__main__':
    a = int(input())
    b = int(input())
    print(a+b, a-b, a*b, sep='\n')

Solution 5: Using for loop

1
2
3
4
5
6
7
8
9
10
if __name__ == '__main__':
    a = int(input())
    b = int(input())
    for i in range(3):
        if i == 0:
            print(a+b)
        elif i == 1:
            print(a-b)
        else:
            print(a*b)

Solution 6: Using eval()

1
2
3
4
if __name__ == '__main__':
    a = int(input())
    b = int(input())
    print(*map(eval, ['a+b', 'a-b', 'a*b']), sep='\n')

Solution 7: Using eval() and for loop

1
2
3
4
5
if __name__ == '__main__':
    a = int(input())
    b = int(input())
    for i in range(3):
        print(eval('a+b', 'a-b', 'a*b')[i])

Solution 8: Using eval() and list comprehension

1
2
3
4
if __name__ == '__main__':
    a = int(input())
    b = int(input())
    print(*[eval('a+b', 'a-b', 'a*b')[i] for i in range(3)], sep='\n')

Solution 9: Using eval() and dictionary

1
2
3
4
if __name__ == '__main__':
    a = int(input())
    b = int(input())
    print(*[eval('a+b', 'a-b', 'a*b')[i] for i in range(3)], sep='\n')

Solution 10: One liner solution

1
2
a, b = int(input()), int(input())
print(f'{a+b}\n{a-b}\n{a*b}')
This post is licensed under CC BY 4.0 by the author.

02. Python If-Else

04. Python Division