5. Getting Started with Python
About this chapter
Big idea: Python lets you write clear steps. The interpreter runs those steps one line at a time.
This is an original lesson that follows the Class 11 Computer Science syllabus. Read the key words first. Cover a worked answer and try the steps yourself before you look. For a program, say what it will print before you read the real output.
- Run Python at a prompt and from a saved .py file.
- Apply identifier rules and keep keywords as reserved words.
- Use variables as names that point to objects.
- Name built-in types and say which ones can change.
- Build expressions with operators and follow precedence.
- Use print() and input(), then convert types when needed.
- Tell syntax errors, runtime errors, and logical errors apart.
Guido van Rossum began Python in December 1989. He wanted a scripting language that was easy to read and still able to talk to the system. He named it after a comedy group so the work would stay light. Python 1.0 appeared in 1994. Python 2.0 arrived in 2000. Python 3.0 launched in 2008 with a cleaner design and Unicode strings. A global community still maintains it. Students use it because the first programs stay short and the errors are readable.
5.1 Introduction to Python
A program is a list of steps for a computer. Python makes those steps easy to read.
A computer needs instructions. An ordered list of instructions is a program.
The language of those instructions is a programming language.
The processor runs machine language. That is only 0 and 1.
People do not write bits by hand. A high-level language uses words close to English.
Python is a high-level language. The text you type is source code.
The machine cannot read source code as-is. A translator is needed.
Python uses an interpreter. It translates and runs one line at a time.
How to read the figure. Start at the top. You write a line. The interpreter reads it. Then it translates. Then the machine runs it. Then the next line starts. A syntax error stops this chain.
The interpreter does not wait for the whole file before the first line can fail.
- Program: an ordered set of instructions for a computer.
- Source code: the high-level text a person writes.
- Interpreter: a translator that runs code line by line.
- Python shell: the window that shows the >>> prompt.
- High-level: It hides bit-level machine detail.
- Interpreted: Each statement can run at once.
- Free and open source: You may study and share it.
- Portable: The same .py file can run on many systems.
- Case-sensitive:
Scoreandscoreare different names. - Indented blocks: Spaces at the left group code.
- Standard library: Ready tools for maths, text, and files.
You can run Python in two modes.
Interactive mode uses the >>> prompt. You type one statement. You press Enter. The result appears at once. Closing the window drops that work.
Script mode uses a text file. You save it with a .py name. The interpreter reads the file from top to bottom. You can edit it and run it again.
How to read the figure. The left column is the prompt. It is fast. It is not saved. The right column is a file. Use a file when the program must last.
| Feature | Interactive mode | Script mode |
|---|---|---|
| Prompt | Shows >>> | Runs the file |
| When it runs | Each line at once | Whole file in order |
| Saved? | No | Yes, as .py |
| Best for | Quick tests | A full program |
How to read the table. Match the job to a column. One formula: left. A quiz for later: right.
Student A wants to test one maths line. Student B needs a quiz program for tomorrow. Which mode should each use?
Goal. Pick a mode for each job.
Rule. Use interactive mode for a short test. Use script mode for saved, multi-step work.
Steps. Student A has one expression. Interactive mode fits.
Steps. Student B must save, edit, and rerun. Script mode fits.
Result: Student A: interactive mode. Student B: script mode.
Here is a tiny script. Read it before you look at the printout.
print("Welcome to Python!")
print("Learning to code is fun.")
steps = 3 + 4
print("Steps completed:", steps)Welcome to Python!
Learning to code is fun.
Steps completed: 7Trace that program line by line. What prints, and what is stored?
Goal. Predict each printed line and the value of steps.
Rule. A print call writes text. Assignment stores a value. + adds numbers.
Line 1. print shows Welcome to Python!
Line 2. print shows Learning to code is fun.
Line 3. 3 + 4 is computed. steps is bound to 7.
Line 4. print shows Steps completed: then 7.
Check. Four actions. Two greetings, one store, one report.
Result: Three lines of text. The last number is 7.
Cover the answers. Try each item on paper first.
5.2 Python keywords
Keywords are reserved words. Python already gave them a job.
Every language has fixed words. In Python those words are keywords.
A keyword sets grammar. It starts a loop, a test, or a definition.
You cannot use a keyword as a variable name. Python stops with a syntax error.
- Keyword: a reserved word with a fixed meaning in Python.
- Reserved word: a word kept for the language, not for your names.
Python is case-sensitive. Most keywords are all lower-case. Examples: if, while, def, class, import.
Exactly three keywords start with a capital: True, False, and None.
Wrong capitals change the meaning. IF is not if. true is not True.
| Group | Keywords | Job |
|---|---|---|
| Truth and empty | True, False, None | Yes, no, and no value |
| Decisions | if, elif, else | Pick a branch |
| Loops | for, while, break, continue | Repeat or leave a loop |
| Functions | def, return, lambda | Make and leave a function |
| Modules | import, from, as | Load extra tools |
| Logic and tests | and, or, not, is, in | Combine tests |
How to read the table. The middle column is the reserved spelling. Copy it exactly.
The keyword module can list them. keyword.iskeyword() tests one word.
import keyword
test_words = ["for", "while", "count", "True", "true", "score"]
for word in test_words:
print(word, "is a keyword:", keyword.iskeyword(word))for is a keyword: True
while is a keyword: True
count is a keyword: False
True is a keyword: True
true is a keyword: False
score is a keyword: FalseHow to read the output. for, while, and True print True. count, true, and score print False.
true with a small t is not a keyword.
Student A wants three names: pass, Pass, and total_marks. Which names are legal?
Goal. Mark each name legal or illegal.
Rule. A keyword cannot be a variable. Keywords are case-sensitive.
Steps. pass in lower case is a keyword. Illegal.
Steps. Pass starts with a capital. It is not the keyword pass. Legal.
Steps. total_marks is not a keyword. Legal.
Result: Illegal: pass. Legal: Pass and total_marks.
Pause here. Answer before you scroll to the answers.
5.3 Identifiers
An identifier is a name you choose. It labels a variable, a function, or another item.
You must name things in a program. Any name you create is an identifier.
Python has strict name rules. A broken name stops the program before it runs.
- Identifier: a name you create for a variable, function, or similar item.
- Underscore: the _ character. It may start a name or join words.
- Snake case: lower-case words joined by underscores.
- Allowed: letters a–z and A–Z, digits 0–9, and
_. - First character: a letter or
_. Never start with a digit. - No spaces or marks: no hyphen, hash, or percent.
- No keywords: the name must not be a reserved word.
- Case matters:
score,Score, andSCOREare three names. - Length: any length is allowed. Short, clear names are better.
| Name | Status | Why |
|---|---|---|
| student_score | Valid | Letters and one underscore |
| _bonus | Valid | May start with _ |
| item2 | Valid | A digit after the first character |
| 2nd_place | Invalid | Starts with a digit |
| item-cost | Invalid | A hyphen is subtraction |
| total score | Invalid | A space is not allowed |
| class | Invalid | class is a keyword |
How to read the table. Valid names sit in the first three rows. The rest fail one rule each.
Python style uses snake_case. Example: bus_speed or total_items.
student_score = 95
total_items = 12
_bonus = 5
final_result = student_score + _bonus
print("Items:", total_items)
print("Final result:", final_result)Items: 12
Final result: 100How to read the output. Items is 12. Final result is 100. The names follow the rules.
Classify each name: room#3, _speed, 4runners, student_name, def.
Goal. Mark valid or invalid.
Rule. Use the identifier rules. Check the first character, extra marks, and keywords.
Steps. room#3 has #. Invalid.
Steps. _speed starts with _ and uses letters. Valid.
Steps. 4runners starts with a digit. Invalid.
Steps. student_name uses letters and _. Valid.
Steps. def is a keyword. Invalid.
Result: Valid: _speed, student_name. Invalid: room#3, 4runners, def.
Write a short answer. Then check the notes below.
5.4 Variables
A variable is a name that points to an object in memory.
A program must remember data. In Python, data lives as an object.
A variable is a label. It is a name tag, not a fixed empty box.
You create the link with assignment. The operator is =.
Right side first. Python computes the right side. Then it binds the left-hand name.
How to read the figure. The arrow goes down. Compute. Store. Name. Never think the name is filled before the right side exists.
How to read the figure. The left box is only a name. The right box is the object. The arrow is the reference.
- Variable: a name that references an object in memory.
- Assignment: binding a name to an object with =.
- Dynamic typing: the type comes from the object, not from a declared name.
- Rebinding: pointing the same name at a different object.
Python uses dynamic typing. You do not declare “this name is an integer”.
The name takes the type of the current object. Later you may bind a string to that name.
a = b = c = 0 gives three names to integer 0.
x, y = 10, 20 pairs x with 10 and y with 20.
Swap is then short: x, y = y, x. Python packs the right side first. Then it unpacks.
num_boxes = 5
print("Initial boxes:", num_boxes)
num_boxes = num_boxes + 3
print("After adding:", num_boxes)
x, y = 10, 20
print("Before swap: x =", x, "y =", y)
x, y = y, x
print("After swap: x =", x, "y =", y)Initial boxes: 5
After adding: 8
Before swap: x = 10 y = 20
After swap: x = 20 y = 10Trace this program. Report each printed line.
Goal. Predict output in order.
Rule. Assignment binds. print shows the current object. Swap unpacks the right side first.
Line 1. num_boxes points to 5.
Line 2. Prints Initial boxes: 5.
Line 3. 5 + 3 is 8. The name is rebound.
Line 4. Prints After adding: 8.
Lines 6–7. x is 10, y is 20. Prints Before swap: x = 10 y = 20.
Line 8. Right side is (20, 10). Then x is 20 and y is 10.
Line 9. Prints After swap: x = 20 y = 10.
Result: 5, then 8, then 10 with 20, then 20 with 10.
Rebinding one name does not rewrite the old object for other names.
A program runs p = 4, then q = p + 3, then p = 10. What are p and q at the end?
Goal. Find the final values of p and q.
Rule. Each assignment binds a name. q keeps its own object.
Steps. p points to 4.
Steps. q gets 4 + 3 = 7.
Steps. p is rebound to 10. q is unchanged.
Result: p is 10. q is 7.
Say the result out loud. Then read the answers.
5.5 Comments
A comment is a note for people. The computer skips it.
You will read code more often than you write it. A comment explains intent.
The interpreter ignores comments. They do not print. They do not slow the run.
- Comment: text in the file that Python does not execute.
- Inline comment: a short note on the same line as code.
- Docstring: a triple-quoted string that documents a module or function.
- Single line: starts with
#. The rest of that line is skipped. - Inline: after a statement, such as
tax = 0.05 # rate. - Several lines: many
#lines, or a triple-quoted string at the top of a module or function.
| Style | Example | Use |
|---|---|---|
| Single line | # Convert hours | Explain the next block |
| Inline | radius = 7 # metres | Name a unit or constant |
| Docstring | """Hours to minutes.""" | Document a whole part |
How to read the table. Pick a style by size. One fact: inline. A whole file: docstring.
Good comments say why. Bad comments repeat the code. # add 1 above count += 1 wastes space.
# Program to convert hours into total minutes
hours = 3 # number of hours to convert
minutes_per_hour = 60 # conversion factor
# Multiply hours by minutes per hour
total_minutes = hours * minutes_per_hour
print("Hours:", hours)
print("Total minutes:", total_minutes)Hours: 3
Total minutes: 180How to read the output. Hours is 3. Total minutes is 180. Every # line was ignored.
A hash inside quotes is not a comment. It is character data.
Look at print("Code # 1") # print the item code. Which # starts a comment?
Goal. Split string text from comment text.
Rule. Inside quotes, # is data. Outside quotes, # starts a comment.
Steps. "Code # 1" is a string. That # is printed.
Steps. The later # starts the inline comment.
Steps. print the item code is skipped.
Result: Only # print the item code is a comment. Code # 1 is printed.
Cover the answers. Try each item on paper first.
5.6 Everything is an object
Every value in Python is an object. An object has identity, type, and value.
A whole number is an object. A word is an object. A list is an object. A function is an object too.
Each object has three properties.
- Identity: a unique integer for that object. Read it with
id(). - Type: the kind of data, such as int or str. Read it with
type(). - Value: the content, such as 42 or
"apple".
How to read the figure again. Identity is the address. Type is the class. Value is 25. The name only points.
- Object: a stored entity with data and operations.
- Identity: the unique id() integer while the object lives.
- Type: the class that decides allowed operations.
- Value: the data stored in the object.
type(42) is <class 'int'>. type("cat") is <class 'str'>.
id() stays the same for that object while it lives. Two names for one object share the same id.
num1 = 300
num2 = num1
print("num1 type:", type(num1))
print("Same object id:", id(num1) == id(num2))
num1 = num1 + 1
print("After changing num1:")
print("Same object id now:", id(num1) == id(num2))
print("num1 value:", num1)
print("num2 value:", num2)num1 type: <class 'int'>
Same object id: True
After changing num1:
Same object id now: False
num1 value: 301
num2 value: 300How to read the output. At first both names share one object, so Same object id is True. After num1 = num1 + 1, a new int is made. num1 is 301. num2 is still 300.
Equal values are not always the same object.
list_a = [10, 20] and list_b = [10, 20]. Is list_a == list_b true? Is list_a is list_b true?
Goal. Separate value equality from identity.
Rule. == tests value. is tests the same object.
Steps. Both lists hold 10 then 20. == is True.
Steps. Python made two list objects. Each has its own id.
Steps. is is False.
Result: == is True. is is False.
Pause here. Answer before you scroll to the answers.
5.7 Python data types
A data type names the kind of value. It also names the allowed operations.
Every value has a data type. The type decides what you may do.
You can multiply two numbers. You cannot divide a sentence by a number.
Python groups types into numbers, sequences, sets, mappings, and None.
- Data type: the class of value an object holds.
- Mutable: contents may change in place.
- Immutable: contents cannot change after creation.
- Sequence: an ordered collection with integer positions.
- Mapping: a collection looked up by a key.
- Numbers:
int,float,complex,bool. - Sequences:
str,list,tuple. Order matters. - Sets:
set. Each value appears once. - None: only
None, typeNoneType. It means “no value”. - Mapping:
dict. Look up a value by a key.
How to read the figure. Left types stay as they are. Right types can grow, shrink, or replace an item and keep the same id.
| Data type | Example | Mutable? | Use |
|---|---|---|---|
| int | 42, -15 | No | Whole numbers |
| float | 3.14, -0.5 | No | Numbers with a fraction |
| bool | True, False | No | Yes or no |
| str | "hello" | No | Text |
| list | [10, 20, 30] | Yes | An ordered list that will change |
| tuple | (10, 20, 30) | No | A fixed ordered group |
| set | {10, 20, 30} | Yes | Unique values |
| dict | {'a': 1} | Yes | A key to a value |
| None | None | No | Missing data |
How to read the table. Scan Mutable? first. Then pick a type that matches the job.
- Use a list when the collection will change.
- Use a tuple when the group must stay fixed, such as a point
(x, y). - Use a set when duplicates must disappear.
- Use a dict when you look up by a name or key.
scores_list = [85, 90, 95]
print("Original list:", scores_list)
scores_list[1] = 92
print("Updated list: ", scores_list)
text_greeting = "Hello"
print("String greeting:", text_greeting)
print("New string formed:", "h" + text_greeting[1:])
point_tuple = (10, 20)
print("Tuple coordinate:", point_tuple)
student_record = {"id": "S101", "grade": 11}
student_record["grade"] = 12
print("Updated dictionary:", student_record)
colors = {"red", "green", "blue", "red"}
print("Unique set elements:", sorted(colors))Original list: [85, 90, 95]
Updated list: [85, 92, 95]
String greeting: Hello
New string formed: hello
Tuple coordinate: (10, 20)
Updated dictionary: {'id': 'S101', 'grade': 12}
Unique set elements: ['blue', 'green', 'red']How to read the output. The list index 1 changes 90 to 92. The string is not edited in place; a new string is built. The tuple stays (10, 20). The dict grade becomes 12. The set drops the extra red.
==s[0] = "b" on a string raises TypeError.== Strings are immutable.
A record stores a name, a roll number, a list of sports, and a fixed admission year. Pick a type for each.
Goal. Match each field to a type.
Rule. Text is str. A changing list is list. A fixed whole number is int.
Steps. Name: str.
Steps. Roll number: int (or str if it must keep leading zeros).
Steps. Sports that come and go: list.
Steps. Admission year: int. It does not change.
Result: str, int, list, int.
Write a short answer. Then check the notes below.
5.8 Operators
An operator is a symbol that computes or compares. The values it uses are operands.
In 17 + 5, + is the operator. 17 and 5 are operands.
Python has arithmetic, relational, assignment, logical, identity, and membership operators.
- Operator: a symbol that computes or compares.
- Operand: a value the operator uses.
- Floor division: division that rounds down to the next lower integer.
- Modulus: the remainder after integer division.
- Short-circuit: stop a logical test as soon as the result is known.
| Operator | Name | Example | Result |
|---|---|---|---|
| + | Addition | 17 + 5 | 22 |
| - | Subtraction | 17 - 5 | 12 |
| * | Multiplication | 17 * 5 | 85 |
| / | True division | 17 / 5 | 3.4 (always float) |
| // | Floor division | 17 // 5 | 3 (rounds down) |
| % | Modulus | 17 % 5 | 2 |
** | Power | 5 ** 3 | 125 |
How to read the table. / keeps a decimal. // drops toward minus infinity. % is the leftover.
- True division / always returns a float. 8 / 2 prints 4.0.
- Floor division rounds down. 17 // 5 is 3. -17 // 5 is -4.
Relational operators give True or False. They are ==, !=, >, <, >=, <=.
Augmented assignment folds maths into =. count += 4 means count = count + 4. Also -=, =, /=, //=, %=, *=.
Logical operators: and needs both True. or needs one True. not flips truth.
Python uses short-circuit evaluation. False and expr stops. True or expr stops.
isis True when both names point to the same object.is notis the reverse.inis True when an item sits in a sequence.not inis the reverse.
a, b = 17, 5
print("True division: ", a / b)
print("Floor division:", a // b)
print("Modulus: ", a % b)
print("Power: ", b ** 3)
count = 10
count += 4
print("After += 4: ", count)
count //= 3
print("After //= 3: ", count)
x, y = 15, 20
print("x < y and y > 10:", x < y and y > 10)
print("x == y or x < 20:", x == y or x < 20)
print("not (x > y): ", not (x > y))
list1 = [1, 2]
list2 = [1, 2]
print("list1 == list2: ", list1 == list2)
print("list1 is list2: ", list1 is list2)True division: 3.4
Floor division: 3
Modulus: 2
Power: 125
After += 4: 14
After //= 3: 4
x < y and y > 10: True
x == y or x < 20: True
not (x > y): True
list1 == list2: True
list1 is list2: FalseHow to read the output. Division lines match the table. count becomes 14, then 4. The and/or/not lines are True. The two lists are equal in value, not in identity.
Evaluate 25 // 4, 25 % 4, and -25 // 4.
Goal. Find three integer results.
Rule. // rounds down. % is the remainder. Remainder fits n = (n // d) * d + (n % d).
Steps. 25 / 4 is 6.25. Floor is 6.
Steps. Remainder: 25 − (6 × 4) = 1.
Steps. -25 / 4 is -6.25. The next lower integer is -7.
Result: 6, 1, and -7.
Say the result out loud. Then read the answers.
5.9 Expressions and operator precedence
An expression mixes values and operators. It computes one value. Precedence decides the order.
An expression is a legal mix of values, names, and operators. It has one result.
15 is an expression. 3 * 4 + 2 is an expression too.
Operator precedence says which operator runs first. Higher rank runs sooner.
- Expression: operands and operators that compute one value.
- Operator precedence: the rank that picks the first operator.
- Associativity: left-to-right or right-to-left among equal ranks.
| Rank | Operators | Associativity |
|---|---|---|
| 1 (highest) | Parentheses: () | Left to right |
| 2 | Power: ** | Right to left |
| 3 | Unary +x, -x | Right to left |
| 4 | *, /, //, % | Left to right |
| 5 | + and - | Left to right |
| 6 | ==, !=, <, <=, >, >= | Left to right |
| 7 | is, in | Left to right |
| 8 | not | Right to left |
| 9 | and | Left to right |
| 10 | or | Left to right |
| 11 (lowest) | = , +=, -=, … | Right to left |
How to read the table. Start at rank 1. Do those operators first. Then move down. Equal rank uses the last column.
Most binary operators go left to right. ** is the exception. It goes right to left.
So 2 3 2 is 2 (3 2) = 512. Grouped the other way, (2 3) 2 = 64.
When you are unsure, add parentheses. They show your plan. They also override rank.
result = 8 + 6 * 2 ** 3 // 4 - 5
print("Computed result:", result)
chain1 = 20 // 4 // 2
print("Left-to-right //:", chain1)
power_chain = 2 ** 3 ** 2
print("Right-to-left **:", power_chain)Computed result: 15
Left-to-right //: 2
Right-to-left **: 512How to read the output. First result is 15. Floor chain is 2. Power chain is 512.
Parentheses are the safest rank. Use them in exam work if the order is not obvious.
Evaluate 10 + 4 3 * 2 // 6 - 7 with every step.
Goal. Find the single integer result.
Rule. Use the rank table. Power first. Then * and // left to right. Then + and - left to right.
Step 1. Power: 3 ** 2 = 9. Now 10 + 4 * 9 // 6 - 7.
Step 2. Multiply: 4 * 9 = 36. Now 10 + 36 // 6 - 7.
Step 3. Floor divide: 36 // 6 = 6. Now 10 + 6 - 7.
Step 4. Add: 10 + 6 = 16. Now 16 - 7.
Step 5. Subtract: 16 - 7 = 9.
Result: The expression equals 9.
Predict the three printed numbers from the program above, without looking back.
Goal. Name the three print results.
Rule. Same rank table. // is left to right. ** is right to left.
First. 2 ** 3 = 8, then 6 * 8 = 48, then 48 // 4 = 12, then 8 + 12 - 5 = 15.
Second. (20 // 4) // 2 = 5 // 2 = 2.
Third. 3 2 = 9, then 2 9 = 512.
Result: 15, then 2, then 512.
Cover the answers. Try each item on paper first.
5.10 Statements
A statement is a full instruction. The interpreter can run it as an action.
An expression yields a value. A statement does a job.
x = 5 is an assignment statement. print("Hello") is a call statement.
You cannot assign an assignment. a = (b = 5) is invalid in Python.
- Statement: a complete instruction Python can run.
- Simple statement: one logical line.
- Compound statement: a header with a colon, then an indented body.
- Indentation: leading spaces that mark a block.
A simple statement fits on one line. Assignment, print(...), import, and pass are simple.
A compound statement has a header that ends with :. The next lines are indented. That group is a suite. if, for, and def are compound.
How to read the figure. Colon. Then spaces. Then a later line with fewer spaces ends the block. Braces are not used.
You may put simple statements on one line with ;. Example: x = 1; y = 2. Clear separate lines are better.
A long statement may wrap inside parentheses. A backslash at the line end also continues a line.
score = 82
message = "Pass"
if score >= 50:
status = "Qualified"
print("Status:", status)
total_points = (
10 + 20 +
30 + 40
)
print("Total points:", total_points)Status: Qualified
Total points: 100How to read the output. The if suite runs because 82 >= 50. Status is Qualified. Total points is 100. message is stored but never printed.
Spaces are grammar in Python, not decoration.
Why is x = 5 a statement, while x + 5 is an expression?
Goal. Name each kind.
Rule. An expression computes a value. A statement performs an action.
Steps. x + 5 computes a number. Expression.
Steps. x = 5 binds a name. It is not a value you can print as the assignment itself. Statement.
Result: x + 5 is an expression. x = 5 is a statement.
Pause here. Answer before you scroll to the answers.
5.11 Input and output
input() reads from the user. print() writes to the screen.
A useful program talks to a person. Data in is standard input. Text out is standard output.
How to read the figure. Top is input. Middle is process. Bottom is output. Skip convert in the middle and the types clash.
- Standard input: data typed in, usually from the keyboard.
- Standard output: the text the program prints.
- sep: the string print() puts between items.
- end: the string print() puts after the last item.
print() turns values into text and shows them. Comma items get a space by default. A newline follows.
- sep: the gap between items.
sep="-"puts a hyphen between them. - end: the ending.
end=" "keeps the next print on the same line.
input() waits. The user types. Enter ends the line. You may pass a prompt: name = input("Enter name: ").
input() always returns a string. Type 25 and you still get "25".
Need a number? Convert with int() or float() first.
print("Shelfmark", "Learning", "Python", sep="-")
print("Line", 1, sep=" : ", end=" *** ")
print("Line", 2, sep=" : ")
# Simulating user input conversion
user_text = "15" # simulated string from input()
quantity = int(user_text)
unit_cost = 4
total_cost = quantity * unit_cost
print("Quantity:", quantity)
print("Total cost:", total_cost)Shelfmark-Learning-Python
Line : 1 *** Line : 2
Quantity: 15
Total cost: 60How to read the output. First line uses hyphens. Line 1 stays on the same row as Line 2 because end is not a plain newline. Quantity is 15. Total cost is 60.
"15" * 3 is 151515, not 45. Convert before you do arithmetic.
n = input("Enter number: ") gets 5. Then print(n * 3) runs. What prints, and why?
Goal. Predict the printed text.
Rule. input() returns str. str times int repeats the text.
Steps. n is the string "5", not the integer 5.
Steps. "5" * 3 is "555".
Check. int(n) * 3 would be 15.
Result: 555 prints. Use int(n) * 3 to get 15.
Write a short answer. Then check the notes below.
5.12 Type conversion
Type conversion changes a value from one type to another so an operation can run.
Data often arrives as text. Maths needs a number. Changing the type is type conversion.
- Type conversion: changing a value from one type to another.
- Implicit conversion: Python changes the type by itself.
- Explicit conversion: you call a function such as int().
- Type casting: another name for explicit conversion.
- Truthy and falsy: values that count as True or False in a test.
Implicit conversion happens when number types mix. Python promotes to the wider type so data is not lost.
In 8 + 2.5, integer 8 becomes 8.0. The sum is 10.5, type float.
Python will not mix str and int with +. "Score: " + 95 is TypeError. Call str(95) first.
Explicit conversion is a function you call.
| Function | Becomes | Example | Result |
|---|---|---|---|
| int(x) | Integer | int(7.9) | 7 (fraction dropped) |
| int(x) | Integer | int("45") | 45 |
| float(x) | Float | float(12) | 12.0 |
| float(x) | Float | float("3.14") | 3.14 |
| str(x) | String | str(250) | "250" |
| bool(x) | Boolean | bool(0) | False |
| bool(x) | Boolean | bool(15) | True |
| list(x) | List | list("cat") | ['c', 'a', 't'] |
| tuple(x) | Tuple | tuple([1, 2]) | (1, 2) |
How to read the table. int() on a float chops toward zero. int() on "3.14" is not in the table on purpose. That call fails.
Some values are falsy: 0, 0.0, "", [], (), {}, None. bool() is False. Other values are truthy.
int_val = 8
float_val = 2.5
combined = int_val + float_val
print("Combined value:", combined)
print("Combined type: ", type(combined))
num_str = "120"
converted_int = int(num_str)
print("Converted int + 5:", converted_int + 5)
float_str = "14.75"
converted_float = float(float_str)
print("Float value: ", converted_float)
print("Truncated int: ", int(converted_float))
print("bool(0): ", bool(0))
print("bool(''): ", bool(""))
print("bool([]): ", bool([]))
print("bool(42): ", bool(42))
print("bool('cat'):", bool("cat"))Combined value: 10.5
Combined type: <class 'float'>
Converted int + 5: 125
Float value: 14.75
Truncated int: 14
bool(0): False
bool(''): False
bool([]): False
bool(42): True
bool('cat'): TrueHow to read the output. Combined is 10.5 and class float. "120" becomes 120, then 125. 14.75 truncates to 14. Empty values are False. 42 and cat are True.
What happens with int("3.14")? How can you reach the integer 3 safely?
Goal. Name the error, then a safe path.
Rule. int() on a string needs a whole-number digit string. A point is not allowed.
Steps. int("3.14") raises ValueError.
Steps. float("3.14") gives 3.14.
Steps. int(3.14) truncates to 3.
Steps. Together: int(float("3.14")).
Result: ValueError from int("3.14"). Use int(float("3.14")) to get 3.
Say the result out loud. Then read the answers.
5.13 Debugging and types of errors
Debugging means find the fault, name it, and fix it.
A fault in a program is a bug. Finding and removing it is debugging.
Python faults fall into three groups.
How to read the figure. Top: the file is not legal. Middle: a line crashes while running. Bottom: the program finishes, but the number is wrong.
- Bug: a fault that crashes a program or gives a wrong answer.
- Debugging: finding, naming, and fixing bugs.
- Syntax error: broken Python grammar.
- Runtime error: a crash on a legal line while it runs.
- Logical error: wrong reasoning; the program still finishes.
- Traceback: the report with file, line, and error name.
- Syntax errors: missing colon, bad brackets, or a mistyped keyword. Python stops before any line runs.
- Runtime errors: the grammar is fine. An impossible act happens, such as
10 / 0(ZeroDivisionError) or a missing name (NameError). - Logical errors: no crash. The formula or the steps are wrong.
| Type | When | Does it run? | Example |
|---|---|---|---|
| Syntax | Before run | No | if x == 5 (no colon) |
| Runtime | On a line | Stops there | 10 / 0 |
| Logical | Never by Python | Yes, to the end | avg = a + b / 2 |
How to read the table. Ask two questions. Did it start? Did it finish with the right answer? That pair names the type.
How to read the figure. After Check, either stop or loop back through Fix to Write.
- Read the traceback from the bottom. The last line names the error.
- Open the given line. If it looks fine, check the line above.
- Print mid values. See what a name actually holds.
- Trace a tiny example on paper. Use numbers you can check by hand.
numerator = 50
denominator = 0
try:
quotient = numerator / denominator
except ZeroDivisionError as err:
print("Caught runtime error:", type(err).__name__)
num_a = 10
num_b = 20
# Buggy formula (logical error): division before addition
buggy_avg = num_a + num_b / 2
print("Buggy average: ", buggy_avg)
# Corrected formula using parentheses
correct_avg = (num_a + num_b) / 2
print("Correct average:", correct_avg)Caught runtime error: ZeroDivisionError
Buggy average: 20.0
Correct average: 15.0How to read the output. The try block catches ZeroDivisionError. That is runtime. Buggy average is 20 because / beats +. Correct average is 15. That gap is a logical error.
A quiet wrong answer is still a bug.
A student writes print("Total score =", score with no closing parenthesis. What error type is that?
Goal. Name the error type.
Rule. Broken grammar that Python sees before running is a syntax error.
Steps. The ( after print has no matching ).
Steps. That breaks the grammar.
Steps. No line runs.
Result: Syntax error. The parenthesis is not closed.
Cover the answers. Try each item on paper first.
Summary
- Python is high-level and interpreted. Blocks are made with indentation.
- Interactive mode uses >>>. Script mode runs a saved .py file.
- Keywords are reserved. You cannot use them as names.
- Identifiers start with a letter or _. They hold no spaces or extra marks.
- A variable is a name that points to an object. = binds. Types can change.
- Comments start with #. Python skips them.
- Every object has id(), type(), and a value.
- Types include numbers, str, list, tuple, set, dict, and None.
- list, dict, and set can change in place. int, str, and tuple cannot.
- Operators do arithmetic, tests, assignment, logic, identity, and membership.
- An expression has one value. ** groups from the right.
- A statement does an action. A compound header ends with a colon.
- print() writes with sep and end. input() always returns a string.
- Conversion may be implicit between numbers, or explicit with int() and friends.
- Syntax stops before run. Runtime crashes on a line. Logic finishes with a wrong answer.
Exercises
These questions are new. Show your thinking. For programs, write your answer before you run the code.
5.1 Which names are invalid, and why: total_cost, 2nd_score, class, item-count, _temp, score%?
5.2 What is the output of this Python program?
x = 12
y = 25
x, y = y, x + 5
print(x, y)5.3 Which type fits each item: a) days in a week, b) a student name, c) exam passed or not, d) a book price, e) a fixed (latitude, longitude) pair?
5.4 Evaluate 29 // 4, 29 % 4, -29 // 4, and -29 % 4.
5.5 Predict the output of this Python program.
print(2 ** 2 ** 3)
print((2 ** 2) ** 3)5.6 Trace the value of val after this program runs. What is printed?
val = 20
val += 6
val //= 4
val **= 2
print(val)5.7 What does (15 > 10) and not (7 == 8) evaluate to?
5.8 What happens with False and (100 / 0 > 1) and with True or (100 / 0 > 1)?
5.9 Why does nums = [1, 2, 3]; nums[0] = 9 work, while text = "cat"; text[0] = "r" raises TypeError?
5.10 What is printed by this program?
a = [5, 10]
b = [5, 10]
print(a == b)
print(a is b)5.11 What is the exact output of this print call?
print("Bus", "Train", sep=" -> ", end=" ***\n")5.12 Predict the output of this print call.
print(int(7.85), int("50"), float("12.5"), bool([]), bool(10))5.13 Name the error type: a) missing closing quote in "hello, b) divide by zero, c) rectangle area as length + width.
5.14 Write an expression that is True when t is between 20 and 30 inclusive.
5.15 What is the value of "py" * 3 + "3"?
5.16 Find simple interest for P = 2000, R = 5, T = 3 using SI = (P R T) / 100.
Answers
- 5.1: Invalid: 2nd_score (digit first), class (keyword), item-count (hyphen), score% (percent). Valid: total_cost, _temp.
- 5.2: prints 25 17. The right side is packed first as (25, 17), then unpacked into x and y.
- 5.3: a) int, b) str, c) bool, d) float, e) tuple.
- 5.4: 29 // 4 = 7, 29 % 4 = 1, -29 // 4 = -8, -29 % 4 = 3.
- 5.5: prints 256, then 64. Powers group from the right unless parentheses force the left group.
- 5.6: prints 36. val becomes 26, then 6, then 36.
- 5.7: True. 15 > 10 is True. 7 == 8 is False, so not False is True. True and True is True.
- 5.8: Both are safe. Short-circuit: False and stops at False. True or stops at True. The divide never runs.
- 5.9: A list is mutable, so an item can change in place. A string is immutable, so an item cannot change.
- 5.10: prints True, then False. The lists have the same values, but they are two objects.
- 5.11: prints Bus -> Train *** on one line.
- 5.12: prints 7 50 12.5 False True.
- 5.13: a) syntax, b) runtime (ZeroDivisionError), c) logic (wrong formula).
- 5.14: 20 <= t <= 30 (or t >= 20 and t <= 30).
- 5.15: pypypy3. "py" repeats three times, then "3" is joined.
- 5.16: 300. True division makes a float: (2000 5 3) / 100 = 30000 / 100 = 300.