TutorialsISCClass 11Python

Python Variables, Data Types, and Operators – A Complete Guide for Students

Master Python variables, data types (int, float, string, bool, list, tuple, dictionary), operators, type conversion, and the input() function with clear examples and practice exercises for ICSE and ISC students.

Updated 12 min read
Python Variables, Data Types, and Operators – A Complete Guide for Students

Welcome back to our Python programming series! In Part 1, we installed Python, explored IDLE, and wrote our first program using print(). Now it is time to go deeper. In this tutorial, you will learn how Python stores information using variables, the different types of data Python understands, and how to perform calculations and comparisons using operators.

This is Part 2 of our Python for ICSE and ISC Students series. If you have not read Part 1 yet, we recommend starting there first.

What Are Variables in Python?

A variable is like a labelled container that holds a value in your program. Think of it as a box with a name tag. You put something inside the box, and whenever you need that value, you use the name tag to find it.

In Python, you create a variable simply by assigning a value to a name using the equals sign (=).

# Creating variables
name = "Aarav"
age = 15
height = 5.6
is_student = True

# Using variables
print(name)        # Output: Aarav
print(age)         # Output: 15
print(height)      # Output: 5.6
print(is_student)  # Output: True

Rules for Naming Variables

Python has some rules you must follow when choosing variable names:

  1. A variable name must start with a letter (a–z, A–Z) or an underscore (_).
  2. It can contain letters, digits (0–9), and underscores, but no spaces or special characters.
  3. Variable names are case-sensitive. So Age, age, and AGE are three different variables.
  4. You cannot use Python keywords like if, else, for, while, True, False, None as variable names.
# Valid variable names
student_name = "Priya"
_score = 95
totalMarks2 = 500

# Invalid variable names (these will cause errors)
# 2name = "Raj"       # Cannot start with a digit
# my name = "Raj"     # Cannot have spaces
# for = 10            # Cannot use keywords

Data Types in Python

Every value in Python has a type. The type tells Python what kind of data it is dealing with and what operations can be performed on it. Python automatically detects the type when you assign a value — this is called dynamic typing.

1. Integer (int)

Whole numbers without any decimal point. They can be positive, negative, or zero.

roll_number = 42
temperature = -5
zero = 0

print(type(roll_number))  # Output: <class 'int'>

2. Float (float)

Numbers that have a decimal point. Use these when you need precision, such as for measurements, percentages, or prices.

percentage = 87.5
pi = 3.14159
price = 49.99

print(type(percentage))  # Output: <class 'float'>

3. String (str)

A sequence of characters enclosed in single quotes or double quotes. Strings are used for text — names, messages, addresses, and more.

school = "Delhi Public School"
greeting = 'Hello, World!'

# String concatenation (joining strings)
first_name = "Ananya"
last_name = "Sharma"
full_name = first_name + " " + last_name
print(full_name)  # Output: Ananya Sharma

# String repetition
line = "-" * 30
print(line)  # Output: ------------------------------

# String length
print(len(school))  # Output: 18

4. Boolean (bool)

A Boolean holds only two possible values: True or False. Booleans are essential for decision-making in programs. Notice that True and False start with capital letters in Python.

is_passed = True
has_submitted = False

print(10 > 5)    # Output: True
print(3 == 7)    # Output: False
print(type(is_passed))  # Output: <class 'bool'>

5. List

A list is an ordered collection of items enclosed in square brackets. Lists can hold items of different types and can be changed after creation (they are mutable).

subjects = ["Maths", "Physics", "Chemistry", "Computer Science"]
marks = [92, 88, 76, 95]
mixed = ["Aarav", 15, True, 5.6]

# Accessing items (index starts from 0)
print(subjects[0])    # Output: Maths
print(subjects[2])    # Output: Chemistry

# Changing an item
subjects[1] = "Biology"
print(subjects)  # Output: ['Maths', 'Biology', 'Chemistry', 'Computer Science']

# Adding an item
subjects.append("English")
print(len(subjects))  # Output: 5

6. Tuple

A tuple is similar to a list, but it is enclosed in parentheses and cannot be changed after creation (it is immutable). Use tuples when you want to store data that should not be modified.

coordinates = (28.6139, 77.2090)  # Delhi coordinates
days = ("Monday", "Tuesday", "Wednesday")

print(coordinates[0])  # Output: 28.6139
print(len(days))       # Output: 3

# This will cause an error because tuples are immutable:
# days[0] = "Sunday"   # TypeError!

7. Dictionary (dict)

A dictionary stores data as key-value pairs inside curly braces. Each key is unique, and you use the key to retrieve its corresponding value. Dictionaries are very useful for storing structured information.

student = {
    "name": "Riya Patel",
    "class": 11,
    "school": "St. Xavier's",
    "percentage": 91.5
}

print(student["name"])        # Output: Riya Patel
print(student["percentage"])  # Output: 91.5

# Adding a new key-value pair
student["city"] = "Mumbai"
print(student.keys())

Type Conversion (Typecasting)

Sometimes you need to convert one data type into another. Python provides built-in functions for this purpose.

# String to Integer
age_text = "16"
age_number = int(age_text)
print(age_number + 1)  # Output: 17

# Integer to Float
whole = 10
decimal = float(whole)
print(decimal)  # Output: 10.0

# Number to String
score = 95
message = "Your score is " + str(score)
print(message)  # Output: Your score is 95

# Float to Integer (removes decimal, does not round)
print(int(7.9))   # Output: 7
print(int(3.2))   # Output: 3

Important: You cannot convert a non-numeric string to an integer. For example, int("hello") will cause a ValueError.

The input() Function

The input() function allows your program to receive data from the user while the program is running. It always returns a string, so you need to convert it if you want a number.

# Getting text input
name = input("Enter your name: ")
print("Hello, " + name + "!")

# Getting numeric input
age = int(input("Enter your age: "))
print("Next year you will be", age + 1)

# Getting decimal input
height = float(input("Enter your height in feet: "))
print("Your height is", height, "feet")

A common beginner mistake is forgetting to convert the input. If you write age = input("Enter age: ") and then try age + 1, Python will give a TypeError because it tries to add a number to a string.

Operators in Python

Operators are special symbols that perform operations on values. Let us explore the main categories.

Arithmetic Operators

a = 17
b = 5

print(a + b)    # Addition:         22
print(a - b)    # Subtraction:      12
print(a * b)    # Multiplication:   85
print(a / b)    # Division:         3.4   (always returns float)
print(a // b)   # Floor Division:   3     (removes decimal part)
print(a % b)    # Modulus:          2     (remainder)
print(a ** b)   # Exponent:         1419857  (17 to the power 5)

Exam tip: The difference between / and // is a very common exam question. The / operator always gives a float result, while // gives an integer result by removing the decimal portion (floor division).

Comparison (Relational) Operators

x = 10
y = 20

print(x == y)   # Equal to:                False
print(x != y)   # Not equal to:            True
print(x > y)    # Greater than:            False
print(x < y)    # Less than:               True
print(x >= 10)  # Greater than or equal:   True
print(x <= 5)   # Less than or equal:      False

Logical Operators

Logical operators combine multiple conditions. Python uses the English words and, or, and not instead of symbols.

age = 16
has_id = True

# and: Both conditions must be True
print(age >= 16 and has_id)     # True

# or: At least one condition must be True
print(age >= 18 or has_id)      # True

# not: Reverses the result
print(not has_id)               # False

# Combining conditions
marks = 85
attendance = 90
print(marks > 75 and attendance > 80)  # True

Assignment Operators

score = 100

score += 10   # Same as: score = score + 10  -> 110
score -= 20   # Same as: score = score - 20  -> 90
score *= 2    # Same as: score = score * 2   -> 180
score //= 3   # Same as: score = score // 3  -> 60
score %= 7    # Same as: score = score % 7   -> 4

print(score)  # Output: 4

Putting It All Together: Student Report Card

Let us write a complete program that uses variables, data types, input(), and operators together.

# Student Report Card Calculator
print("=" * 40)
print("   STUDENT REPORT CARD GENERATOR")
print("=" * 40)

name = input("Enter student name: ")
roll = int(input("Enter roll number: "))

print("\nEnter marks for each subject (out of 100):")
english = float(input("English: "))
maths = float(input("Mathematics: "))
science = float(input("Science: "))
computer = float(input("Computer Science: "))
hindi = float(input("Hindi: "))

total = english + maths + science + computer + hindi
average = total / 5

if average >= 90:
    grade = "A+"
elif average >= 75:
    grade = "A"
elif average >= 60:
    grade = "B"
else:
    grade = "C"

all_passed = english >= 33 and maths >= 33 and science >= 33 and computer >= 33 and hindi >= 33

print("\n" + "=" * 40)
print("         REPORT CARD")
print("=" * 40)
print("Name:       ", name)
print("Roll No:    ", roll)
print("-" * 40)
print("Total:      ", str(total) + "/500")
print("Average:    ", round(average, 2))
print("Grade:      ", grade)
print("Status:     ", "PASSED" if all_passed else "FAILED")
print("=" * 40)

Quick Quiz: Test Your Understanding

Q1. What is the output of print(type(3.0))?

Answer: <class 'float'> — The decimal point makes it a float even though 3.0 looks like a whole number.

Q2. What is the difference between 17 / 5 and 17 // 5?

Answer: 17 / 5 gives 3.4 (regular division, always float). 17 // 5 gives 3 (floor division, removes the decimal).

Q3. What will print("5" + "3") output?

Answer: 53 — Both are strings, so Python concatenates them instead of adding.

Q4. Can you change an item in a tuple?

Answer: No. Tuples are immutable — their items cannot be changed after creation.

Q5. What does not (5 > 3 and 2 < 1) evaluate to?

Answer: True — 5 > 3 is True, 2 < 1 is False. True and False = False. not False = True.

Summary

  • Variables store values and have naming rules
  • Data types include int, float, str, bool, list, tuple, and dict
  • Type conversion uses int(), float(), str() to change types
  • input() reads user input as a string
  • Operators perform arithmetic, comparison, logical, and assignment operations

What is Next?

In Part 3 of this series, we will put your knowledge to the test with practice questions and solved programs — output prediction, error finding, and complete programs to write on your own. Make sure you are comfortable with Parts 1 and 2 before moving on.

Happy coding!