Lessons 30–31 · 2 lessons · M. R. Fayziyeva, D. M. Sayfurov, N. S. Xaytullayeva. Informatics and Information Technologies, Grade 9. “Nashriyot uyi Tasvir”, Tashkent, 2020
31
Operators and expressions in Python
Textbook: pp. 68–69
GoalTakes several values from one line with input().split(), converts them to numbers, and sets the look of the output with the sep and end arguments of print().
New words
split(): cuts a string into parts by a separator; the default separator is a space · split()sep: the argument of print() that sets what is put between the printed values (a space by default) · sepend: the argument of print() that sets what is put after the output (a new line by default) · endlist: an ordered set of values in square brackets; its parts are taken with an index, the first has index 0 · ro‘yxat
Explanation
input() gives one line of text as a string; split() cuts it into parts by a separator and the result is a list. If no separator is given a space is used: "6 9" becomes ["6", "9"], and split(";") separates by a semicolon. The parts of the list are strings too, so before calculating they must be converted to numbers with int(): a[0] is the first part and a[1] the second. In print(), sep sets what is put between the values (a space by default) and end sets what follows the output (a new line by default). For example sep="-" separates the values with a dash and end="" continues the next print() on the same line. These settings make the output neat and fit the demands of the task.
Worked examples
Splitting: a = input().split(";") ⏎ print(a) ⏎ print(int(a[0]) + int(a[1]) + int(a[2])) If 12;30;8 is typed, the first line shows the list ['12', '30', '8'] and the second the sum 50.
Look of the output: print("Ali", 14, "yosh", sep="-", end=".") The result is Ali-14-yosh. – the values are separated with dashes, and a dot comes at the end. Two numbers typed with a space: a = input().split() ⏎ x = int(a[0]) ⏎ y = int(a[1]) ⏎ print(x, y, x + y, sep=" | ") If 6 9 is typed, 6 | 9 | 15 is printed.
Class activity
“Set the output”: the group runs print(1, 2, 3) with 4 different values of sep and end (sep="", sep=", ", sep="\n", end="!") and records each result in a table.
Practice
1
Two numbers are typed on one line with a space. Write a program that prints their product.
a = input().split() ⏎ print(int(a[0]) * int(a[1]))
2
What does print(1, 2, 3, sep="") print?
123
3
Into how many parts does "olma nok anor".split() cut the string?
3
4
Why do print("a", end="") and the print("b") after it show "ab" on one line?
end="" cancels the move to a new line, so the next output continues on the same line.