Introduction

Welcome back! Today, our fun coding journey will guide us through the world of arithmetic and logical operations. These fundamental concepts are frequently used in Python programming and significantly assist in performing calculations as well as making evaluations that direct decision-making in code. By the end of this lesson, you'll master performing basic arithmetic operations, such as adding the numbers of a high score or dividing measurements for a recipe. You'll also understand how to use logical operations to check multiple conditions simultaneously, a deciding factor in a program that, for instance, only permits access if a user has not been banned and has entered the correct credentials. Let's embark on this exciting journey!

Basic Arithmetic Operators

Python enables us to seamlessly perform basic arithmetic operations — addition, subtraction, multiplication, and division — akin to how we would do them on paper. Let's open our CodeSignal IDE and work with these operations:

Python
# Addition
addition = 5 + 3
print(addition)  # prints 8

# Subtraction
subtraction = 5 - 3
print(subtraction)  # prints 2

# Multiplication
multiplication = 5 * 3
print(multiplication)  # prints 15

# Division 
division = 5 / 3
print(division)  # prints 1.6666666666666667

# Integer Division
# The integer division returns only the integer part of the division, always rounding the result down
integer_division = 5 // 3
print(integer_division) # prints 1

In this example, we conducted five basic arithmetic operations using Python operators and stored the results in correspondingly named variables such as addition, subtraction, multiplication, division, and integer_division. We then printed the results. These operations essentially serve as the foundation for more intricate calculations in your code.

Advanced Arithmetic Operations

Beyond the basic arithmetic operations, Python also offers operators for modulus (finding the remainder from division) and exponents (raising a number to the power of another). Let's delve into these with some examples:

# Modulus
remainder = 5 % 3
print(remainder)  # prints 2

# Exponents
cubed = 2 ** 3
print(cubed)  # prints 8 (2 * 2 * 2)

# Float exponents
square_root = 9 ** (1 / 2) # equals to (9 ** 0.5), or to square root of 9
print(square_root) # prints 3.0

In real-world programming, the modulus operator helps determine if a number is even (hint: number % 2) or odd, aiding in specific game algorithms. Similarly, the exponent operator is vital in computations like calculating the area of a shape or determining growth over time in compound interest math.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal