On day 1, you’ve set up Python and explored the print() function. It’s time to dive into the core building blocks of Python programming: variables, data types, input/output operations, operators, and string manipulation. Mastering these fundamentals will give you a strong foundation for writing more complex programs.
Day 2 of 10: Python Data Types & Operations
Variables and Data Types
What are Variables?
A variable is a named location in a computer’s memory to store data. Variables can hold many different types of data, e.g., integers (whole numbers like 0, -1, 2, etc.), floats or floating-point numbers (real numbers with a decimal component like 0.1, -5.89898, 3.1416, etc.), strings (letters, words, sentences, etc.). In Python, you don’t need to declare variable types explicitly; the interpreter determines them automatically. What do I mean by that?
It means that variable types are determined at runtime in Python. In contrast, variables, for example, in C need to be declared explicitly. Let’s see an example:
int num = 10; // Explicitly declaring 'num' as an integer
printf("%d\n", num);In the above example, we had to declare the ‘num’ variable as an integer (int) in C. Now, if we assign a string to this variable, e.g., num = “Hello”, it will result in a compilation error.
num = 10 # No type declaration needed
print(num)On the other hand, the ‘num’ variable in the above example did not require an explicit declaration. Python automatically infers that ‘num’ is an integer (the number 10). In addition, we can assign a string (or any other data type) to ‘num’ later, e.g., num = “Hello”, and Python will automatically declare ‘num’ as a string instead of throwing an error. This is the flexibility of Python in variable declaration.
You can find out the data type using the built-in Python function ‘type( )’. Try the following code:
num = 10
print(type(num))
# The print function prints what's inside the bracket. type(num) outputs the data type of the variable num.
x = "Bangladesh"
print(type(x)) # type(x) outputs the data type of the variable x.Output:
class ‘int’
class ‘str’
Let’s look at the common data types in Python…
| Data Type | Description | Example |
| int (i.e., integer) | Stores integers or whole numbers – positive, negative, and zero. | x = 10 x = -20 |
| float (i.e., floating-point numbers) | Stores decimal numbers. | x = 3.1416 x = 10.0 |
| str (i.e., String) | Stores a string, i.e., a collection of characters or text. | x = “Tanim” |
| bool (i.e., Boolean) | Stores ‘True’ or ‘False’ states (0 or 1) | x = True y = False |
| list | Stores an ordered collection of items. Different data types can be stored. Mutable, i.e., contents can be modified after declaration. | nums = [ 1, 3, 5] fruits = [“apples”, “mangoes”] x = [1, “hello”, 3.14, True] |
| tuple | Stores an immutable (contents cannot be modified after initialization) ordered collection. | coord = (-2, 4) x = (1, “hello”, 3.14, True) |
| dict (i.e., Dictionary) | Stores unordered key-value pairs. Each unique key maps to a value. | person = {“name”: “Alice”, “age”: 25} “name” & “age” are keys mapping to corresponding values, “Alice” & “25”. |
User Inputs
We have printed the values of a variable. If you want to change the value of a variable, say from x =10 to x =20, you will have to find the variable in your code (where you assigned it) and then change the value on every spot. However, this may become cumbersome for long codes. To avoid this, you can take the value as a user input. Python’s ‘input( )’ function lets you do this easily. Try the following code:
name = input("Enter your name: ") # Press enter after you write your name.
print("Hello,", name)⚠️ Note: By default, input() returns a string. You must convert it using other built-in functions like int(), float(), etc., if needed.
Let’s look at an example.
age = input("Enter your age: ")
# Let's print the data type
print("Data type:", type(age))
# It's a string. Hence, the following will throw an error.
print("Next year, you will be", age + 1) # cannot add string to an integer.Let’s do it again properly.
age = int(input("Enter your age: ")) # int() converts the string into an integer
# Let's print the data type again
print("Converted data type:", type(age))
print("Next year, you will be", age + 1)Operators in Python
Python operators are special symbols or keywords that let you perform operations on one or more operands (variables or values). They are categorized into several types based on the operations they perform. Let’s look at the most important ones.
Arithmetic Operators (Mathematical Operations)
| Operator | Description | Example |
| + | Addition | 5 + 3 = 8 |
| – | Subtraction | 5 – 3 = 2 |
| * | Multiplication | 5 * 3 = 15 |
| / | Division | 5 / 2 = 2.5 |
| // | Floor Division (returns integer part) | 5 // 2 = 2 |
| % | Modulus (returns the remainder) | 5 % 2 = 1 |
| ** | Exponentiation | 5 ** 2 = 25 |
Try the following code. Replace the ‘+’ operator with other operators to practice.
x = 10
y = 3
print("Addition:", x + y)You must remember that these mathematical operators follow the standard mathematical order of precedence. The acronym PEMDAS or BEDMAS can be used to remember the precedence. The precedence is as follows:
- Parentheses / Brackets
(): Expressions enclosed in parentheses are always evaluated first, regardless of the operators within them. This allows explicit control over the order of operations. - Exponentiation **: The exponentiation operator has the next highest precedence.
- Multiplication
*, Division/, Floor Division//, Modulo%: These operators have the same level of precedence and are evaluated from left to right if multiple appear in an expression. - Addition
+, Subtraction-: These operators have the lowest precedence among the basic arithmetic operations and are also evaluated from left to right when they appear together.
Let’s consider the following example. First, calculate it on paper. Then confirm if your result matches Python’s output.
expression = 5 + 2 * 3**2 - (10 / 5)
print(expression)Assignment Operators
- The Assignment ( = ) operator is used to assign a value to a variable. We have already used it many times, e.g., x = 10 assigns the value 10 to the variable x.
- Compound Assignment Operators
+=,-=,*=,/=,//=,%=,**=are used to perform an operation (left operand) and then assign (right operand) the final value to the variable. For example:
x += 5 means x = x + 5. Similarly, x *= 5 means x = x * 5, x **= 5 means x = x ** 5, and so on. Try this…
x = 10
print(x += 5) # Try other compound assignment operators too.Comparison (Relational) Operators
Used to compare two values and return a Boolean (True/False) result.
| Operator | Description | Example |
| == | Returns True if values are equal. | 5 == 5 outputs ‘True’, 5 == 3 outputs ‘False’ |
| != | Returns True if values are not equal. | 5 != 3 outputs ‘True’, 5 != 5 outputs ‘False’ |
| > | Returns True if the value on the left is Greater than the value on the right. | 5 > 3 outputs ‘True’, 3 > 5 outputs ‘False’ |
| < | Returns True if the value on the left is Less than the value on the right. | 3 < 5 outputs ‘True’, 5 < 3 outputs ‘False’ |
| >= | Returns True if the value on the left is Greater than or Equal to the value on the right. | 5 >= 5 outputs ‘True’, 6 >= 5 outputs ‘True’, 3 >= 5 outputs ‘False’ |
| <= | Returns True if the value on the left is Less than or Equal to the value on the right. | 5 <= 5 outputs ‘True’, 3 <= 5 outputs ‘True’, 6 <= 5 outputs ‘False’ |
Logical Operators (conditional statements)
| Operator | Description | Example |
| and | Returns True only if both conditions are true. | 5 > 3 and 10 > 5 outputs ‘True’, 5 < 3 and 10 > 5 outputs ‘False’, 5 < 3 and 10 < 5 outputs ‘False’ |
| or | Returns True if at least one condition is true. | 5 > 3 or 10 > 5 outputs ‘True’, 5 < 3 or 10 > 5 outputs ‘True’, 5 < 3 and 10 < 5 outputs ‘False’ |
| not | Reverses the result. | not (5 > 3) outputs ‘False’, not (5 < 3) outputs ‘True’. |
Identity Operators
Used to check if two variables refer to the same object in memory.
- Operator is returns True if both variables point to the same object in memory.
- On the other hand, operator is not returns True if they are not the same object.
Try the following code…
x = [1,2]
y = x
print(x is y) # Output: True
x = [1,2]
y = [1,2] # different memory location with the same value
print(x is y) # Output: FalseMembership Operators
Used to test if a value is present in a sequence (e.g., string, list, tuple).
- Operator in returns True if a value exists in a sequence. For example, ‘a’ in ‘apple’ outputs True.
- On the other hand, operator not in returns True if a value does not exist in a sequence. For example, 3 not in [1,2,4] outputs True.
Challenge Time!
- Challenge 1: Guess the data type
Predict the data types of the following variables:
a = 42, b = 3.14, c = “42”, d = True.
Now, use a Python function to determine the data type and verify your predictions. - Challenge 2: Club member?
Complete the following program where necessary. It is supposed to ask the user to guess an integer and then check if the number belongs to the predefined club. Don’t worry if you can’t understand the code completely. Just try to fill in the proper expressions with the right operators.
num = # finish the code to take a user input (integer)
club = [0, 0, 1, 1, 2, 3, 5, 8, 13] # Predefined list. This is part of a famous series. Do you know the name?
if num : # complete the rest of the expression between num and the colon :
# The expression should check if num exists inside club.
print(f"{num} exists inside the series, {club}.")
else:
print(f"{num} doesn't exist inside the series, {club}.")
Bonus Challenge: Assign grades
Write a program that takes a student’s score (0–100) as user input. Then assigns a grade as follows:
- Print ‘Grade: A’ if score >= 90
- Print ‘Grade: B’ if score >= 75
- Print ‘Grade: C’ if score >= 60
- Print ‘Grade: D’ if score >= 40
- Print ‘Grade: F’ otherwise
Try solving the challenges to test your knowledge so far. It’s okay if you cannot solve the bonus challenge. However, do try it yourself. You can find the solution to the bonus challenge in the next part. Good luck!
Conclusion
This concludes day 2 of ‘Learn Python in 10 Days’. We will discuss an interesting topic on day 3 – control flow, i.e., conditional flow and loops. BTW, don’t forget to comment how you solved the challenges. Good luck!