New to Programming? No Worries! Start Learning Python from Scratch — Part 1: Mastering Python Operators

Rohollah
Python Mastery for Beginners
9 min readAug 10, 2024

Programming is a key skill in today’s world that lets us solve problems and bring ideas to life using computers. To start learning, it’s important to understand data types like numbers, text, and lists. In Python, choosing the right data type is crucial for making your programs efficient.

Python Datatypes
Variables are similar to the container

Variables are containers that store data, and each variable can hold a specific type of data. Depending on the data type, you can perform different operations, like doing math with numbers or combining text. Learning how to use variables and convert data between types is essential for flexible programming.

In this article, we’ll explore the basics of data types, variables, and data conversion to help you start programming with confidence.

Understanding Variables andData Types in Pyhton
Understanding Python Operators

How to Define and Use Variables in Python?

To define a variable, you simply write the name you want to give it, followed by an equal sign =, and then the value you want to store. For example:

First_name = "Alice"
age = 12
print(f"Hello {first_name}, congratulations on your {age}th birthday!")

This piece of code will print the following output:

Hello Alice, congratulations on your 12th birthday!

How Variables Are Stored Behind the Scenes

When we define a variable like First_name= "Alice", what actually happens? Where is "Alice" stored?
When you define a variable like First_name= "Alice", the Python interpreter stores the string "Alice" in memory and assigns the variable first_name as a reference(label) to that memory location.

Assign a reference (First_name) to the value(“Alice”)

Continuing with the code above, suppose you assign the value `”Alice”` to a variable named `nickname`:

# Define new variable
Nickname = "Alice"

# Print values
print("nickname =", Nickname)
print("first_name =", First_name)
assign 2 variables to one object
Assign Tow references to the value(“Alice”)

After executing the above code, the word “Alice” will be printed twice.

To Learn More About Python Variables, Check Out This Quick 2-Minute Guide

Python Variables Explained Simple (In 2 Minutes or Less) | by Igor Jovanovic M.Sc. | Python in Plain English

Python Data Type

Data types are essential in programming because they allow us to represent and work with different kinds of data in the most efficient and accurate way. By using the appropriate data type, we ensure that our code can handle and process information correctly, reducing the chances of errors and making our programs easier to understand and maintain. Each data type serves a specific purpose and is designed to handle a particular kind of data.

Python data types
Python data types

What data types do we have in Python?

  • Integers (`int`): Used to count things or represent whole numbers, like the number of items in a cart. Example: `item_count = 5`.
  • Floats (`float`): Used for measurements or prices that require decimal points, like `19.99`. Example: `price = 19.99`.
  • Strings (`str`): Used to work with text, such as names, addresses, or messages. Example: `name = “Alice”` or `greeting = “Hello, World!”`.
  • Booleans (`bool`): Help make decisions in code by representing `True` or `False`, like checking if a user is logged in. Example: `is_logged_in = True`.
  • Binary Data (`bytes`): Essential for working with low-level data, such as files or images, where data is stored in 0s and 1s.

By using these data types appropriately, we can build programs that are both robust and easy to maintain.

Because this article is aimed at beginners, I won’t dive deep into Python data types. However, to give you a quick overview, you can refer to the image below.

Python data types conversion

For more information on Python Data Types, click here.

Enforcing Python Data Types in 30 Seconds | by Liu Zuo Lin | Level Up Coding (gitconnected.com)

Data type conversion in python

To explain the concept of type conversion, I’ll use two simple examples. Suppose we have the following piece of code:

a = 4
b = 3.5
c = a + b

What do you think the value of c will be? a is an integer, and b is a float. So, what will the type of c be—float or integer? And what about its value—will it be 7 or 7.5?

In fact, behind the scenes, the Python interpreter automatically converts a from an integer to a float, so c will also be a float, and the value of c will be 7.5.

This is how Python handles it by default. However, you might want something different. For example, you might want the program to ignore the decimal point in 3.5 and add 3 to 4, resulting in an integer value for c. You can achieve this by explicitly converting b to an integer like this:

c = a + int(b)
Implicit and Explicit data type converion
Implicit and Explicit data type conversion

Implicit and Explicit Conversion:

Implicit Data Type Conversion:
This happens when Python automatically changes one data type to another behind the scenes, such as in the first code example where Python converts the integer `a` to a float during the operation. This automatic change is known as implicit conversion.

Explicit Data Type Conversion:
On the other hand, explicit conversion is when the programmer manually changes a data type using specific functions like `int()`, `float()`, or `str()`. For instance, in the second example where you convert `3.5` to `3`, you would use `int()` to explicitly convert the float to an integer. This approach gives you more control over how the data is processed in your code.

Before continuing to the next topic, let’s look at an interesting example.

In this simple number guessing game, the computer picks a random number between 1 and 10, and the player tries to guess it. The player enters a guess, and the game tells them if their guess is correct, too low, or too high. The program uses basic operations like comparing numbers and converting the player’s input from text to a number to make the game work.

import random

# Generate a random number between 1 and 10
secret_number = random.randint(1, 10)

# Ask the player to guess the number
guess = input("Guess a number between 1 and 10: ")

# Convert the player's guess from string to integer
guess = int(guess)

# Check if the guess is correct using comparison operators
if guess == secret_number:
print("Congratulations! You guessed the correct number.")
elif guess < secret_number:
print("Too low! The correct number was:", secret_number)
else:
print("Too high! The correct number was:", secret_number)

Notice how we used the `int()` function to convert the `guess` variable from a string to an integer.

Python Operators

Python operators are special symbols or keywords used to perform operations on variables and values. They allow you to manipulate data and perform tasks such as arithmetic calculations, comparisons, logical decisions, and more within your Python programs. Examples of Python operators include `+` for addition, `==` for comparison, and `and` for logical conjunction.

Python operators

Let’s explain the most common operators in Python:

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations.

  • Addition (+)
    Adds two numbers.
  • Subtraction (-)
    Subtracts the second number from the first.
  • Multiplication (*)
    Multiplies two numbers.
  • Division (/)
    Divides the first number by the second.
  • Floor Division (//)
    Divides the first number by the second and rounds down to the nearest integer.
  • Modulus (%)
    Returns the remainder of the division.
  • Exponentiation (**)
    Raises the first number to the power of the second number.
# Arithmetic Operators
a = 5
b = 3

addition = a + b # 8
subtraction = a - b # 2
multiplication = a * b # 15
division = a / b # 1.666...
floor_division = a // b # 1
modulus = a % b # 2
exponentiation = a ** b # 125

Relational (Comparison) Operators

Relational operators compare two values and return a Boolean result.

  • Equal to (==)
    Checks if two values are equal.
  • Not equal to (!=)
    Checks if two values are not equal.
  • Greater than (>)
    Checks if the first value is greater than the second.
  • Less than (<)
    Checks if the first value is less than the second.
  • Greater than or equal to (>=)
    Checks if the first value is greater than or equal to the second.
  • Less than or equal to (<=)
    Checks if the first value is less than or equal to the second.
# Relational Operators
x = 10
y = 7

equal = x == y # False
not_equal = x != y # True
greater_than = x > y # True
less_than = x < y # False
greater_than_equal = x >= y # True
less_than_equal = x <= y # False

Logical Operators

Logical operators are used to combine multiple Boolean expressions.

  • AND (and)
    Returns True if both conditions are True.
  • OR (or)
    Returns True if at least one condition is True.
  • NOT (not)
    Reverses the Boolean value.
# Logical Operators
a = True
b = False

and_result = a and b # False
or_result = a or b # True
not_result = not a # False

Bitwise Operators

Bitwise operators perform operations on the binary representations of integers.

  • Bitwise AND (&)
    Performs a binary AND operation on two integers.
  • Bitwise OR (|)
    Performs a binary OR operation on two integers.
  • Bitwise XOR (^)
    Performs a binary XOR operation on two integers.
  • Bitwise NOT (~)
    Flips all bits in the binary representation of the integer.
  • Left Shift (<<)
    Shifts the bits of the number to the left by a specified number of positions.
  • Right Shift (>>)
    Shifts the bits of the number to the right by a specified number of positions.
# Bitwise Operators
x = 6 # 110 in binary
y = 3 # 011 in binary

bitwise_and = x & y # 2 (010 in binary)
bitwise_or = x | y # 7 (111 in binary)
bitwise_xor = x ^ y # 5 (101 in binary)
bitwise_not = ~x # -7 (inverted bits and adding 1)
left_shift = x << 1 # 12 (1100 in binary)
right_shift = x >> 1 # 3 (011 in binary)

Assignment Operators

Assignment operators are used to assign values to variables.For example, if you write code like:

a = 5
a += 2 // It is equivalent to writing `a = a + 2`

The value of a will be updated to 7. Similar operators exist for multiplication (*), exponentiation (**), division (/), and floor division (//).

# Assignment Operators
a = 10
b = 3
a -= 2 # It is equivalent to writing `a = a - 2` so a becomes 8
b *= 4 # It is equivalent to writing `b = b * 4` so b becomes 12

Operator precedence

In Python programming, operator precedence determines the order in which operations are performed in an expression. For example, in the expression 2 + 3 * 4, the multiplication is performed before the addition because the multiplication operator (*) has a higher precedence than the addition operator (+).

If you want the addition to be performed first, you can use parentheses to change the order, like this: (2 + 3) * 4.

# Example of operator precedence

result_1 = 2 + 3 * 4 # Multiplication is done first, then addition; result_1 = 14
result_2 = (2 + 3) * 4 # Parentheses change the order; result_2 = 20
result_3 = 10 - 2 ** 2 # Exponentiation is done first, then subtraction; result_3 = 6
result_4 = 10 / 2 + 3 # Division is done first, then addition; result_4 = 8.0

# The values of result_1, result_2, result_3, and result_4 will be calculated based on the operator precedence.

This code shows how different operators have different levels of precedence, and how parentheses can be used to control the order of operations in an expression.

For more information on Python Operators, click here.

Python Operators from Scratch!!! — A Beginner’s Guide | by Tanu N Prabhu | Towards Data Science

--

--