Skip to main content
Chapter 3 of 8
~19 min read
Last reviewed July 17, 2026

Introduction to Python Programming

Core data types, arithmetic operators, input/output functions, comparison and logical operators, along with sample Python programs.

Written and reviewed by the IK Learning team

  • Data Types
  • Arithmetic Operators
  • Input & Output
  • Logical Operators
  • Operator Precedence
  • Python Programs

This chapter introduces Python programming fundamentals, covering core data types, arithmetic and logical operators, operator precedence, and how to use input() and print() to build simple interactive programs.

Chapter Introduction

What this chapter is about, and why it matters

This is where the planning you did in Class 9 becomes real code. Python is a good first language because it stays close to the pseudocode you already know — a WHILE loop in pseudocode and a while loop in Python look almost identical.

The chapter covers data types, operators and input/output. None of it is difficult individually; the errors come from the joins between them. The single biggest one is that input() always hands you text, even when the user typed a number, and forgetting to convert it produces a program that runs but gives nonsense.

Read code by predicting the output before running it. If your prediction and the computer disagree, you have found a gap in your understanding — which is far more useful than code that happened to work.

What You Will Learn

The skills this chapter is assessed on

  • Identify Python's core data types and choose the appropriate one for a given value.
  • Use arithmetic, comparison and logical operators correctly, including operator precedence.
  • Take input with input() and produce formatted output with print().
  • Convert between data types and explain why conversion is necessary after input().
  • Write and trace short Python programs that calculate a result from user input.

Key Concepts Explained

8 core ideas — each with its definition and a separate worked example

Variable

Definition

A variable is a named location in memory used to store a value that can be referred to and changed while a program runs.

Example

Three variables holding three different types of value:

name = "Ayesha"
age = 15
average = 82.5

Detailed Explanation

Python does not require you to declare a type in advance — assigning a value creates the variable and sets its type at that moment. Convenient, but it also means a typo in a variable name silently creates a brand-new variable instead of raising an error.

Core data types

Definition

Python's core data types include int for whole numbers, float for numbers with a decimal part, str for text, and bool for the two truth values True and False.

Example

The same digits behave very differently depending on their type:

a = 5        # int
b = 5.0      # float
c = "5"      # str
d = True     # bool

print(a + a)   # 10  (arithmetic)
print(c + c)   # 55  (text joined, not added)

Detailed Explanation

That last line is the one to remember. The `+` operator adds numbers but joins strings, so "5" + "5" gives "55". Nothing is broken — Python did exactly what the types asked for.

Arithmetic operators

Definition

Python's arithmetic operators are + (addition), - (subtraction), * (multiplication), / (division), // (floor division, discarding the remainder), % (modulus, giving the remainder) and ** (exponentiation).

Example

The three division-related operators applied to the same numbers:

print(17 / 5)   # 3.4  — true division, always a float
print(17 // 5)  # 3    — floor division, whole part only
print(17 % 5)   # 2    — modulus, the remainder
print(2 ** 3)   # 8    — 2 to the power of 3

Detailed Explanation

The modulus operator is more useful than it first appears. `n % 2 == 0` tests whether n is even, and `n % 10` extracts the last digit of a number — both are common exam tasks.

input() and type conversion

Definition

The input() function pauses the program, reads what the user types, and always returns it as a string. To use that value in arithmetic it must first be converted with int() or float().

Example

The same program, wrong then right:

# WRONG — joins two strings
age = input("Enter your age: ")
print(age + 1)          # TypeError

# CORRECT — converts to a number first
age = int(input("Enter your age: "))
print(age + 1)          # works

Detailed Explanation

This is the most common error in the whole chapter. input() cannot know whether you wanted a number, so it returns text and leaves the decision to you. Wrap it in int() or float() the moment you know the value is numeric.

print() and output formatting

Definition

The print() function displays output on the screen. It can print several values separated by commas, and f-strings allow variables to be embedded directly inside the text.

Example

Two ways to produce the same line of output:

name = "Bilal"
marks = 87

print("Student:", name, "scored", marks)
print(f"Student: {name} scored {marks}")

Detailed Explanation

f-strings are clearer once the message grows, because the sentence reads as a sentence instead of a chain of fragments. Note the f before the opening quotation mark — omit it and the braces print literally.

Comparison operators

Definition

Comparison operators compare two values and produce a Boolean result: == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to) and <= (less than or equal to).

Example

Comparison produces True or False, never a number:

marks = 75
print(marks >= 50)   # True
print(marks == 100)  # False

Detailed Explanation

A single = assigns a value; a double == compares two values. Writing `if marks = 50` is a syntax error in Python, which is fortunate — in some languages the same mistake silently changes the variable.

Logical operators

Definition

Logical operators combine Boolean values: and gives True only when both operands are True, or gives True when at least one is True, and not reverses a Boolean value.

Example

Deciding whether a student passed both papers:

theory = 45
practical = 30

if theory >= 40 and practical >= 25:
    print("Passed")
else:
    print("Failed")

Detailed Explanation

These are the same AND, OR and NOT you met with logic gates in Class 9 — identical truth tables, different notation. Recognising that connection makes both chapters easier.

Operator precedence

Definition

Operator precedence is the fixed order in which Python evaluates operators within an expression: parentheses first, then exponentiation, then multiplication, division, floor division and modulus, then addition and subtraction, then comparisons, then not, and, or.

Example

Precedence changes the answer completely:

print(2 + 3 * 4)      # 14 — multiplication happens first
print((2 + 3) * 4)    # 20 — parentheses override precedence

Detailed Explanation

You do not need to memorise the full table if you use parentheses whenever an expression could be read two ways. Clear code is worth more than clever code, and in an exam it also shows the marker exactly what you intended.

Step-by-Step Worked Examples

How to lay the answer out so method marks are earned

A program that calculates the average of three marks

Question: Write a Python program that asks the user for three subject marks and displays their average to two decimal places.

  1. Identify the inputs: three marks. They will arrive as strings, so each needs converting.
  2. Choose float rather than int, because marks may include a decimal part.
  3. Read each mark with input() wrapped in float().
  4. Calculate the average by adding the three values and dividing by 3.
  5. Display the result using an f-string with :.2f to fix it to two decimal places.

Answer

m1 = float(input("Enter mark 1: ")) m2 = float(input("Enter mark 2: ")) m3 = float(input("Enter mark 3: ")) average = (m1 + m2 + m3) / 3 print(f"Average = {average:.2f}") The parentheses around the addition are essential — without them, precedence divides only m3 by 3.

Where This Is Used in Real Life

The same ideas, outside the syllabus

Why type errors matter outside the classroom

Treating a number as text is a genuine source of production bugs — a shopping cart that concatenates prices instead of adding them charges the wrong amount. The habit of converting input immediately is professional practice, not an exam rule.

The modulus operator in everyday logic

Alternating row colours in a table, checking whether a year is a leap year, and grouping items into pages all use `%`. It is the operator that turns a counter into a repeating pattern.

Reading error messages

Python names the error type and the line number. "TypeError on line 4" is a precise instruction, not a complaint. Learning to read the last line of a traceback first is the fastest debugging skill you can acquire.

Common Mistakes to Avoid

Errors that cost marks in this chapter, and the correction for each

Mistake

Forgetting to convert the result of input() before doing arithmetic.

Correct Approach

input() always returns a string. Wrap it: `age = int(input("Age: "))`. This single mistake accounts for most failed programs in this chapter.

Mistake

Using = instead of == in a condition.

Correct Approach

One equals sign assigns; two compare. `if x == 10:` is a test, `x = 10` is an instruction.

Mistake

Expecting / to give a whole number.

Correct Approach

In Python 3, / always produces a float — 10 / 2 gives 5.0, not 5. Use // when you want the whole part only.

Mistake

Omitting the f before an f-string.

Correct Approach

Without the f, `print("{name}")` prints the braces literally instead of the variable's value.

Mistake

Adding numbers stored as strings.

Correct Approach

"5" + "3" gives "53" because + joins strings. Convert both to int first.

Mistake

Assuming Python follows left-to-right order in every expression.

Correct Approach

Multiplication and division bind more tightly than addition and subtraction. Use parentheses whenever the order matters.

Exam Preparation Tips

Technique specific to this chapter

  • Write the input, process and output sections of a program as three clearly separated blocks. Markers follow that structure easily and it prevents you forgetting a step.
  • Include a helpful prompt inside every input() call. It costs nothing and is frequently part of the mark scheme.
  • Trace your code with a specific value before submitting — running "17" through a program on paper catches division and conversion errors instantly.
  • Indentation is part of Python's syntax, not decoration. Keep it consistent and visible in handwritten answers.
  • When a question asks for output to a set number of decimal places, use an f-string with :.2f. Rounding by hand loses marks for method.

Quick Revision Summary

The whole chapter in one screen — read this the night before

  • Data types: int, float, str, bool.
  • input() always returns a string — convert with int() or float().
  • + adds numbers but joins strings: "5" + "5" = "55".
  • / true division (float), // floor division, % remainder, ** power.
  • n % 2 == 0 tests for an even number.
  • = assigns, == compares.
  • Logical operators: and, or, not — same logic as AND, OR, NOT gates.
  • Precedence: () → ** → * / // % → + - → comparisons → not → and → or.
  • f-strings embed variables: f"Total is {total}".
  • Format to two decimals with {value:.2f}.

Glossary of Terms

Words used in this chapter, defined plainly

Syntax
The grammatical rules a programming language requires.
Type casting
Converting a value from one data type to another.
Concatenation
Joining two strings end to end.
Expression
A combination of values and operators that produces a result.
Statement
A single complete instruction in a program.
Traceback
The error report Python prints when a program fails, showing where and why.
Comment
A note in the code, starting with #, ignored when the program runs.

Practice Questions

Now test yourself on the concepts above. Collapse the answers to make it a real practice run.

Multiple Choice Questions with Explanations

9 MCQs — pick an option to check yourself, then read why the answer is right

1Which of these steps is NOT part of the basic programming process?

Correct answer: DIgnore Errors

Ignoring errors is never part of programming, since errors must be found and fixed, so Ignore Errors does not belong in the process.

2While installing Python, what should you do to make running it from the command line easier?

Correct answer: CCheck 'Add Python to PATH'

Selecting Add Python to PATH lets you run Python from any command-line location without typing its full path.

3What output does print(10 // 3) produce?

Correct answer: B3

The // operator performs floor division, so 10 divided by 3 gives 3 with the remainder discarded.

4In x = '123', what data type does variable x hold?

Correct answer: CString

Because the value is enclosed in quotation marks, x holds a string, not a number.

5Which operator carries the highest precedence in Python?

Correct answer: DParentheses ()

Parentheses have the highest precedence in Python, so expressions inside them are always evaluated first.

6What does the expression 5 > 3 and 2 < 1 evaluate to?

Correct answer: BFalse

Since 2 < 1 is False, the and operation returns False even though 5 > 3 is True.

7What is the function of the += operator?

Correct answer: CAdds and assigns

The += operator adds a value to a variable and then assigns the result back to that same variable.

8What does age = 25; print('Age:', age) output?

Correct answer: AAge: 25

The print() call outputs the text label followed by the value stored in the variable, giving Age: 25.

9Which symbol marks a comment in Python?

Correct answer: C#

In Python, the # symbol begins a comment, so the interpreter ignores the rest of that line.

Short Questions with Answers

8 short-answer questions

Comments are lines written inside a program that the computer ignores while running it. They matter because they explain the code, improve readability, document the logic, and make future maintenance easier. Example: # This line calculates the average marks of the students
A data type defines the kind of value a variable can store. Three basic data types in Python are int, which stores whole numbers, float, which stores decimal numbers, and str, which stores text or characters. Example: marks = 10 (int), price = 3.14 (float), name = "Hello" (str)
An integer (int) is a data type that stores whole numbers with no decimal point, while a float is a data type that stores numbers which include a decimal point. Example: age = 17 is an integer, whereas height = 5.9 is a float.
Logical operators are operators used to combine or compare two or more conditions in a program. Python has three of them: and, or, and not. Example: if age > 12 and age < 20: is true only when both conditions are true.
User input is obtained through the input() function, which reads whatever the user types on the keyboard and returns it to the program as a string. Example: name = input("Enter your name: ") stores the typed name in the variable name.
The print() statement is a built-in Python function used to display output, messages, or the values of variables on the screen. Example: print("Hello, World!") displays Hello, World! on the screen.
Operator precedence is the rule that determines the order in which operations are carried out within an expression. Example: 3 + 4 * 2 results in 11, because multiplication is performed before addition.
A variable name is the identifier given to a variable so its value can be stored and used. Three main naming rules are: it must begin with a letter or an underscore ( _ ), it cannot begin with a number, and it cannot be a Python keyword. Example: _marks and total1 are valid names, whereas 1total and for are invalid.

Long Questions with Detailed Answers

8 in-depth answers

In Python, variables can be created with different data types to hold various kinds of information. Some common variable types are: - Integer (int) Definition: Stores whole numbers with no decimal points. Example: age = 17 Here, age is an integer variable holding the value 17. - Floating-Point (float) Definition: Stores decimal numbers. Example: price = 19.99 Here, price is a float variable holding the value 19.99 - String (str) Definition: Stores text or characters. Strings are wrapped in quotes, either single (' ') or double (" "). Example: name = "Arshad" Here, name is a string variable holding the text "Arshad" - Boolean (bool) Definition: Stores True or False. Example: is_student = True Here, is_student is a boolean variable that holds the value True.
Arithmetic operators are used to carry out basic mathematical operations on numbers. Examples - Addition (+): Adds two numbers. a=10 b=3 print(a+b) # Output: 13 - Subtraction (−): Subtracts the second number from the first. print(a − b) # Output: 7 - Multiplication (*): Multiplies two numbers. print(a*b) # Output: 30 - Division (/): Divides the first number by the second (returns a float). print(a/b) # Output: 3.3333333333333335 - Floor Division (//): Divides and returns only the integer part of the quotient. print(a//b) # Output: 3 - Modulus (%): Returns the remainder left over from division. print(a%b) # Output: 1 - Exponentiation: Raises the first number to the power of the second. print(a**b) # Output: 1000 When to use: 1. Addition, subtraction, multiplication, and division are used for everyday calculations. 2. Modulus operators find remainders. They come in handy in loops, arrays, or checking even/odd numbers. 3. Exponentiation is used for powers or mathematical formulas. 4. Floor division is used when only whole-number results are needed.
- Input and Output Operations Input and output operations let a program interact with the user. You can ask the user to enter data (input) and show information back to the user (output). a. Input: The input() function is used to get user input. It displays a message on the screen and waits for the user to type something and press Enter. The text the user types is then stored in a variable. Example: name=input("Enter your name:") This line asks the user to enter their name and stores it in the variable name. b. Output: The print() function is used to display information on the screen. It accepts one or more arguments and displays them. Example: print("Hello, "+name+"!") This line displays a greeting message that includes the user's name. DID YOU KNOW? Q. Inside the print() function, which symbol separates multiple values/variables to be printed? Ans. Inside the print() function, a comma (,) is used to separate multiple values or variables to be printed. Q. In Python, what determines the structure or scope of code? Ans. Indentation determines the structure or scope of code in Python. Incorrect indentation can cause errors. - Handling Integer and Float Inputs To work with numeric inputs, convert the input using int() for whole numbers or float() for decimal numbers, since the input() function always returns a string. 1. Integer input example: user_age=int(input("Enter your age:")) print("Your age is:",user_age) Output: Enter your age: 16 Your age is: 16 1. Float input example: user_height=float(input("Enter your height in meters: ")) print("Your height is",user_height,"meter") Output: Enter your height in meters: 1.5 Your height is 1.5 meter
- Comparison operators compare two values or expressions and return a Boolean value (True or False). Examples include >, <, ==, !=, >=, <=. - Logical operators (and, or, not) combine multiple conditions or expressions and return Boolean results based on the evaluation. Example # Define variables x = True y = False # Logical AND logical_and = x and y print(x, "and", y, "=", logical_and) # Output: True and False = False # Logical OR logical_or = x or y print(x, "or", y, "=", logical_or) # Output: True or False = True Note: 1. and returns True only when both conditions are True. 2. or returns True when at least one condition is True. 3. not flips a Boolean value to its opposite.
name = input("Enter your name: ") print("Hello,", name) Output Enter your name: Arshad Mehmood Shah Hello, Arshad Mehmood Shah Explanation: This program reads the user's name as input and then displays a greeting message using the print() function.
num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) total = num1 + num2 print ("Sum:", total) Output Enter first number: 5 Enter second number: 7 Sum: 12
n1 = float(input("Enter first number: ")) n2 = float(input("Enter second number: ")) n3 = float(input("Enter third number: ")) n4 = float(input("Enter fourth number: ")) n5 = float(input("Enter fifth number: ")) average = (n1 + n2 + n3 + n4 + n5) / 5 print("Average:", average) Output: Enter first number: 10 Enter second number: 20 Enter third number: 30 Enter fourth number: 40 Enter fifth number: 50 Average: 30.0
Evaluating the expressions (using Python operator precedence): a) 8+3*4 − 2**2 #Exponentiation 8+3*4 −4 #Multiplication 8+12− 4 #Addition 20 − 4 #Subtraction 16 Ans. 16 b) 20%7*3+10//3 #Modulus 6* 3+10//3 #Floor Division 6* 3+3 #Multiplication 18+3 #Addition 21 Ans. 21 c) 2*3**2%4+10 − 6/2 #Exponentiation 2* 9%4+10 − 6/2 #Multiplication 18 %4+10−6/2 #Modulus 2 +10 − 6/2 #Division 2 +10 − 3 #Addition 12 − 3 #Subtraction Ans. 9.0

Important Questions for Revision

5 high-priority questions

- Integer (int): Stores whole numbers with no decimals. Example: age = 17 - Float (float): Stores decimal numbers. Example: price = 19.99 - String (str): Stores text enclosed in quotes. Example: name = "Ali" Bonus: Boolean (bool) stores True or False. Example: is_student = True
Logical operators combine or compare conditions and return a Boolean result (True/False). The three logical operators in Python are: - and — returns True only when both conditions are True - or — returns True when at least one condition is True - not — flips the Boolean value (True becomes False)
Operator precedence determines the order in which operations are carried out within an expression. Python evaluates higher-precedence operators before lower ones. Order (highest to lowest): Parentheses () → Exponentiation ** → Multiplication/Division/Modulus */% → Addition/Subtraction +- Example: 3 + 4 * 2 = 11 (multiplication happens first), but (3+4) * 2 = 14 (parentheses first).
Python arithmetic operators: + Addition: 5 + 3 = 8 - Subtraction: 5 - 3 = 2 * Multiplication: 5 * 3 = 15 / Division: 10 / 3 = 3.333 // Floor Division: 10 // 3 = 3 % Modulus (remainder): 10 % 3 = 1 Exponentiation: 2 3 = 8
input() function: Used to collect data from the user. It shows a message and waits for the user to type. Example: name = input("Enter your name: ") This stores whatever the user types into the variable name. print() function: Used to display output on the screen. Example: print("Hello,", name) Output: Hello, Ali Note: print() adds a newline by default; use end="" to prevent this.

Frequently Asked Questions

6 quick answers to common questions about this chapter

An int stores whole numbers with no decimal point, like 17. A float stores numbers with decimals, like 5.9. Even though both represent numbers, Python treats them differently internally, which matters for things like division results and precision in calculations.
Yes, by default. The input() function always returns a string, even if the user types a number. To use that input in a math calculation, it has to be explicitly converted using int() for whole numbers or float() for decimals — otherwise Python will treat "25" as text, not the number 25.
In the expression 3 + 4 * 2, Python doesn't calculate left to right — it follows operator precedence rules and multiplies first, giving 3 + 8 = 11, not 14. This is exactly the same order of operations taught in math class.
Comments (written with #) are ignored by Python when the code runs, but they help human readers — including your future self — understand what a section of code is meant to do. Well-commented code is much easier to debug, share, and maintain later.
Yes. Python data types, arithmetic and logical operators, operator precedence, input/output functions, and writing simple Python programs are all part of the Class 10 syllabus and are examined through MCQs and short/long answer questions.
Regular division (/) always returns a decimal result, like 10 / 3 = 3.333. Floor division (//) returns only the whole number part of that result and discards the remainder, so 10 // 3 = 3. It's useful whenever only a whole-number answer makes sense.

Chapter Test

9 questions with the answers hidden — check what you actually remember

You have just read the explanations above. This checks whether they stuck. The answers stay hidden until you finish, so it is closer to exam conditions than scrolling through the notes again.

  • 9 questions, one at a time — no time limit.
  • You can move back and change an answer before submitting.
  • Afterwards you get your score, every explanation, and what to re-read.

Your score is saved in this browser only. No account, nothing sent anywhere.

Related Topics in the Other Class