Python Variables and Operators
Chapter 5 · Tamil Nadu State Board
- 11 min read
- 5-question quiz
Every key point below shows the sentence from your textbook it comes from. Book back answers are solved and checked against the book; answers we could not prove are left out. How we check content
In short
This lesson teaches how to write Python programs in Interactive mode and Script mode, and how input and output work. It explains variables, tokens, literals, data types, indentation, and several kinds of operators. These ideas help students create, understand, and run Python code.
Written by AI from this lesson. How we check it
Key points
- Python code can be entered interactively for immediate results or written and saved as a script.
From your textbook
“In Python, programs can be written in two ways namely Interactive mode and Script mode.”
- A script can be reused and edited instead of retyping its code each time.
From your textbook
“Python Scripts are reusable code. Once the script is created, it can be executed again and again without retyping.”
- The input() function accepts data during program execution, while print() displays results.
From your textbook
“The input() function helps to enter data at run time by the user and the output function print() is used to display the result”
- Python uses spaces or tabs to mark blocks, and statements in one block need consistent indentation.
From your textbook
“all statements within the block must be indented with same amount spaces.”
- Tokens are the basic components into which Python divides each logical line.
From your textbook
“Python breaks each logical line into a sequence of elementary lexical components known as Tokens.”
- Python includes arithmetic, relational, logical, assignment, and conditional operators.
From your textbook
“Operators are categorized as Arithmetic, Relational, Logical, Assignment etc.”
Formulas in this chapter
- input() syntaxVariable = input (“prompt string”)Explained here
- Conditional operator syntaxVariable Name = [on_true] if [Test expression] else [on_false]Explained here
Python and its main features
Python is a general purpose programming language created by Guido Van Rossum from CWI in Netherlands. It was released in I991 and named after “Monty Python’s Flying Circus”. Python supports both Procedural and Object Oriented programming approaches.
Key features of Python
- It can be used for scientific and non-scientific programming.
- It is platform independent.
- Python programs are easy to read and understand.
Interactive mode and Script mode
Two ways to work in Python
| Interactive mode | Script mode |
|---|---|
| Type code at the Python command prompt (>>>). | Write Python statements in a separate file. |
| The interpreter displays results immediately. | Save the file with the extension .py, then execute it. |
| It can be used as a simple calculator. | Scripts can be edited and run again without retyping. |
In IDLE, the prompt (>>>) shows that the interpreter is ready to accept instructions. To create a script, choose File → New File or press Ctrl + N. Save it with File → Save or Ctrl + S, then run it with Run → Run Module or F5.
Python files are saved with the extension .py by default. If code has an error, IDLE shows it in red. Correct the code, save it, and run it again.
Python input and output functions
Definition
- print() function
- The print() function displays text, variables, or results on the screen.
The print() function evaluates an expression before displaying it. Use a comma to separate more than one item. You can display a string, a variable, or a mixture of strings and variables.
Common print() forms
- print (“string to be displayed as output ” )
- print (variable )
- print (“String to be displayed as output ”, variable)
- print (“String1 ”, variable, “String 2”, variable, “String 3” ……)
Definition
- input() function
- The input() function accepts data typed by the user at run time and stores it in a variable.
A prompt string tells the user what to enter. Without a prompt string, no message appears, so the user may not know what to type. input() accepts the entered data as a string, even when the user types a number.
Variable = input (“prompt string”)
Variable stores the entered data; prompt string is the message shown to the user.
Worked example
Ask for two numbers and display their sum.
Try it first, then show the solutionSolution
- Use x = int (input(“Enter Number 1: ”)) to accept the first value as an integer.
- Use y = int (input(“Enter Number 2: ”)) to accept the second value as an integer.
- Display the result with print (“The sum = ”, x+y).
Answer: For inputs 34 and 56, the output is The sum = 90.
Remember: Use int() to convert a number entered through input() into integer data before doing calculations.
Python Comments and Indentation
A comment is ignored by the Python interpreter. A single-line comment starts with #. A multiline comment is enclosed in triple quotes, ''' '''.
Python uses spaces or tabs to show which statements belong to a program block. Every statement in the same block must use the same amount of indentation. The number of spaces or tabs is not fixed.
Remember: Use the same indentation for every statement in one block.
Python Tokens, Identifiers and Keywords
Definition
- Token
- A token is an elementary lexical component that Python identifies in a logical line of a program.
Types of tokens
- Identifiers
- Keywords
- Operators
- Delimiters
- Literals
Definition
- Identifier
- An identifier is a name used for a variable, function, class, module or object.
Identifier rules
- Start with an alphabet letter or underscore (_).
- May contain digits (0 .. 9).
- Are case sensitive, so uppercase and lowercase letters are distinct.
- Must not be a Python keyword.
- Must not contain punctuation such as %,$, @.
Valid and invalid identifiers
| Valid | Invalid |
|---|---|
| Sum | 12Name |
| total_marks | name$ |
| regno | total-mark |
| num1 | continue |
Definition
- Keyword
- A keyword is a special word with a specific meaning to the Python interpreter, so it cannot be used for another purpose.
Python keywords
- False, None, True
- and, as, assert, async, await
- break, class, continue, def, del
- elif, else, except, finally, for
- from, global, if, import, in
- is, lambda, nonlocal, not, or
- pass, raise, return, try, while
- with, yield
Remember: Leave whitespace between tokens, and do not use a keyword as an identifier.
Python Operators
Definition
- Operand
- An operand is a value or variable used with an operator.
Arithmetic operators
| Operator | Operation and example result |
|---|---|
| + | Addition: a + b gives 110 |
| - | Subtraction: a – b gives 90 |
| * | Multiplication: a*b gives 1000 |
| / | Division: a / b gives 10.0 |
| % | Modulus: a % 30 gives 10 |
| ** | Exponent: a ** 2 gives 10000 |
| // | Floor Division: a//30 gives 3 |
For these arithmetic examples, a=100 and b=10. Arithmetic operators perform calculations on operands.
Relational or Comparative operators
| Operator | Meaning and example result |
|---|---|
| == | Equal: a==b gives False |
| > | Greater than: a > b gives True |
| < | Less than: a < b gives False |
| >= | Greater than or equal to: a >= b gives True |
| <= | Less than or equal to: a <= b gives False |
| != | Not equal to: a != b gives True |
For these relational examples, a=100 and b=35. A relational operator checks two operands. It returns True if the relationship holds and False otherwise.
Logical operators
| Operator | What it does |
|---|---|
| or | Returns True if at least one expression is True. |
| and | Returns True when both expressions are True. |
| not | Reverses True to False or False to True. |
With a = 97 and b = 35, a>b or a==b gives True. The expression a>b and a==b gives False. The expression not a>b gives False.
Assignment operators
| Operator | Effect |
|---|---|
| = | Assigns the right-side value to the left variable. |
| += | Adds and assigns the result back to the left operand. |
| -= | Subtracts and assigns the result back to the left operand. |
| *= | Multiplies and assigns the result back to the left operand. |
| /= | Divides and assigns the result back to the left operand. |
| %= | Finds the modulus and assigns the result back to the left operand. |
| **= | Performs an exponent calculation and assigns the result to the left operand. |
| //= | Performs floor division and assigns the result to the left operand. |
The statements a = 5 and b = 10 assign values to two variables. They can also be written as a,b=5,10.
Worked example
What values are displayed when the assignment-operator program starts with x=10?
Try it first, then show the solutionSolution
- x+=20 makes x equal to 30.
- x-=5 makes x equal to 25.
- x*=5 makes x equal to 125.
- x/=2 makes x equal to 62.5.
- x%=3 makes x equal to 2.5.
- x**=2 makes x equal to 6.25.
- x//=3 makes x equal to 2.0.
Answer: The displayed values are 10, 30, 25, 125, 62.5, 2.5, 6.25 and 2.0, in that order.
Conditional or Ternary Operator
Definition
- Ternary operator
- The ternary operator chooses a value based on whether a condition is true or false, using one line instead of a multiline if-else.
Variable Name = [on_true] if [Test expression] else [on_false]
Test expression is the condition. The result is [on_true] if it is true; otherwise, the result is [on_false].
For min= 49 if 49<50 else 50, min is 49. For min= 50 if 49>50 else 49, min is also 49.
Worked example
Find the minimum when a, b = 30, 20 and min = a if a < b else b.
Try it first, then show the solutionSolution
- Check whether a < b, which means checking whether 30 < 20.
- The condition is false, so choose b.
Answer: The Minimum of A and B is 20.
Remember: The ternary operator selects one of two values according to whether its test expression is true or false.
Python Delimiters
Definition
- Delimiter
- A delimiter is one or more characters that mark the boundary between separate parts of text or data.
Python uses delimiters in expressions, lists, dictionaries and strings. The delimiters shown here are ( ) [ ] { } , : . ‘ = ;.
Python Literals
Definition
- Literal
- A literal is raw data given to a variable or constant.
Types of literals
- Numeric literals
- String literals
- Boolean literals
Numeric literals contain digits and cannot be changed. They can be Integer, Float or Complex. Numeric examples include binary, decimal, octal and hexadecimal values.
Worked example
What values are printed by the numeric literal program?
Try it first, then show the solutionSolution
- The integer literals are a = 0b1010, b = 100, c = 0o310 and d = 0x12c.
- The float literals are float_1 = 10.5 and float_2 = 1.5e2.
- The complex literal is x = 1 + 3.14 j.
Answer: Integer Literals : 10 100 200 300; Float Literals : 10.5 150.0; x = (1+3.14j), with imaginary part 3.14 and real part 1.0.
A string literal is a sequence of characters surrounded by quotes. Python allows single, double and triple quotes. A single character in single or double quotes is also a string literal. Triple quotes can enclose a multiline string.
Worked example
What does the string literal program display?
Try it first, then show the solutionSolution
- strings = "This is Python"
- char = "C"
- The multiline string contains: This is a multiline string with more than one line code.
Answer: It displays This is Python, C, and the multiline string.
Definition
- Boolean literal
- A Boolean literal has one of two values: True or False.
Escape Sequences in Python Strings
The backslash, written as \, is a special character called the escape character. It can represent whitespace characters or quotes inside strings. For example, print ("It\'s rainning") displays It's rainning.
Common escape sequences
| Escape sequence | Meaning or example output |
|---|---|
| \\ | Backslash; print("\\test") displays \test. |
| \’ | Single-quote; print("Doesn\'t") displays Doesn't. |
| \” | Double-quote; print("\"Python\"") displays "Python". |
| \n | New line; separates text onto a new line. |
| \t | Tab; adds a tab between text. |
| \r | Carriage return. |
Python Data Types
Every data value in Python is an object, and each object or value has a type. Built-in data types include Number, String, Boolean, tuples, lists, sets and dictionaries.
Number data types
- Integer: can be decimal, octal or hexadecimal. Examples include 102, 0o102 and 0X102.
- Floating point: a sequence of decimal digits that includes a decimal point. Examples include 123.34 and 456.23.
- Exponent data: includes a decimal digit part, decimal point and exponent part followed by one or more digits. Examples include 12.E04 and 24.e04.
- Complex number: made up of two floating point values, one for the real part and one for the imaginary part.
Octal integers use 0 followed by the letter 'o'. Hexadecimal integers use 0X, with uppercase or lowercase X. The examples also show long decimal integers such as 34L and 523L.
Boolean and string data
| Data type | How it is written |
|---|---|
| Boolean | True or False, such as Bool_var1=True and Bool_var2=False. |
| String | Text enclosed in single quotes, double quotes or triple quotes. |
Remember: Remember: a literal is a value, while a data type tells you what kind of value it is.
Questions students ask
Short, direct answers to what students search for in this chapter.
What is the difference between Interactive mode and Script mode in Python?
In Interactive mode, you type code at the Python command prompt (>>>) and the interpreter displays results immediately. In Script mode, you write statements in a separate file with the extension .py, save the file, and execute it. Scripts can be edited and run again without retyping.
How do you create and run a Python script in IDLE?
Choose File → New File or press Ctrl + N to open a blank script editor. Type the Python statements and save with File → Save or Ctrl + S. Run the script by choosing Run → Run Module or pressing F5. The output appears in the IDLE window.
What does the input() function do in Python?
The input() function accepts data typed by the user at run time and stores it in a variable. A prompt string can tell the user what to enter. input() accepts all entered data as a string, so use int() when a number must be treated as integer data.
How is the print() function used in Python?
The print() function displays text, variables, or results on the screen. It evaluates an expression before printing it. A comma separates multiple items, so a program can display a message together with a variable or calculation result.
How do comments and indentation work in Python?
A single-line Python comment begins with #, and the interpreter ignores it. Multiline comments are enclosed in triple quotes, ''' '''. Python uses spaces or tabs for program blocks, and every statement in the same block must have the same amount of indentation.
What are the rules for naming identifiers in Python?
An identifier starts with an alphabet letter or underscore (_). It may contain digits, but it cannot be a Python keyword or contain punctuation such as %,$, @. Identifiers are case sensitive, so uppercase and lowercase letters are distinct.
Show 6 more questions
What are the types of operators in Python?
The operator categories covered here are Arithmetic, Relational or Comparative, Logical, Assignment and Conditional operators. Arithmetic operators calculate values; relational operators return True or False; logical operators work with relational expressions; assignment operators assign or update values.
How does the Python ternary operator work?
The ternary operator tests a condition on one line. Its syntax is Variable Name = [on_true] if [Test expression] else [on_false]. It chooses [on_true] when the test expression is true and [on_false] otherwise.
What are delimiters in Python?
Delimiters are one or more characters that mark boundaries between separate parts of text or data. Python uses them in expressions, lists, dictionaries and strings. Examples include parentheses, square brackets, braces, commas, colons, periods, equal signs and semicolons.
What are the types of literals in Python?
Python has three types of literals: Numeric, String and Boolean. Numeric literals include Integer, Float and Complex values. String literals are characters enclosed in quotes. Boolean literals have one of two values: True or False.
How do escape sequences work in Python strings?
An escape sequence begins with a backslash, which is Python's escape character. It can represent characters such as a tab, newline or carriage return, and can include quotes or a backslash in a string. For example, \n represents a newline and \t represents a tab.
What are the number data types in Python?
Python's built-in number data types are Integer, floating point and complex numbers. Integers can be decimal, octal or hexadecimal. Floating point data includes a decimal point, while exponent data includes an exponent part. A complex number has real and imaginary parts.
Book back answers
22 textbook exercises, solved and checked against the book. Questions we could not prove are left out.
Choose the best answer (1 Marks)
Who developed Python ?
- A) Ritche
- B) Guido Van Rossum
- C) Bill Gates
- D) Sunder Pitchai
Try it, then show the answerAnswer
B) Guido Van Rossum
The chapter identifies Guido Van Rossum as the creator of Python.
From the book: “Python is a general purpose programming language created by Guido Van Rossum”
The Python prompt indicates that Interpreter is ready to accept instruction.
- A) >>>
- B) <<<
- C) #
- D) <<
Try it, then show the answerAnswer
A) >>>
The Python prompt shown in the chapter is >>>.
From the book: “The prompt (>>>) indicates that Interpreter is ready to accept instructions.”
Which of the following shortcut is used to create new Python Program ?
- A) Ctrl + C
- B) Ctrl + F
- C) Ctrl + B
- D) Ctrl + N
Try it, then show the answerAnswer
D) Ctrl + N
The chapter says to choose File → New File or press Ctrl + N to create a script.
From the book: “Choose File → New File or press Ctrl + N in Python shell window.”
Which of the following character is used to give comments in Python Program ?
- A) #
- B) &
- C) @
- D) $
Try it, then show the answerAnswer
A) #
Python comments begin with the hash symbol.
From the book: “In Python, comments begin with hash symbol (#).”
Practice
Which mode displays a result immediately after code is entered at the prompt?
Exam questions
Practice questions with model answers. These are not from an official paper.
State one difference between Interactive mode and Script mode.2 marks
Interactive mode lets you type code at the Python prompt and displays results immediately. Script mode lets you write and store code in a separate .py file for execution.
What do input() and print() do?2 marks
input() accepts data from the user at run time and stores it in a variable. print() displays results on the screen.
What is a token? Name four token types.2 marks
A token is an elementary lexical component of a Python logical line. Four types are identifiers, keywords, operators, and delimiters.
Explain how a relational operator works.2 marks
A relational operator checks the relationship between two operands. It returns True when the relationship holds and False otherwise.
Watch out
- Do not assume input() turns typed numbers into numeric data; the lesson says it accepts data as a string.
- Do not confuse the = assignment operator with relational operators such as ==, which checks equality.
Still stuck on this lesson?
Get an AI answer grounded in your actual textbook — with the exact page reference.
Ask AI about this topic →