Operators and expressions in Python
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.
| What it does | Default | |
|---|---|---|
| sep | what is put between the values | a space |
| end | what follows the output | a new line |
A pupil recorded the three throw distances of one round as one line of numbers separated by spaces, such as “4 6 5”. A program cut the line into three parts and turned them into numbers before adding them, so the pupil typed once instead of answering three questions.
Data processors, analysts and programmers split a long line and work with each value separately.
Write three numbers on one line separated by spaces. On paper separate them into boxes and write the double of each.
1a = input().split(";") 2print(a) 3print(int(a[0]) + int(a[1]) + int(a[2]))
['12', '30', '8'] 50
1print("Ali", 14, "yosh", sep="-", end=".") 2 3a = input().split() 4x = int(a[0]) 5y = int(a[1]) 6print(x, y, x + y, sep=" | ")
Ali-14-yosh. 6 | 9 | 15
“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.