Using Python as a Calculator |
use the console |
Numbers |
MDAS - multiplication, division, addition, subtraction division always returns a floating point number to do floor division and get an integer result use the // operator to calculate the remainder use the % operator >>> 17 / 3 5.666666666666667 >>> 17 // 3 # floor division discards the fractional part 5 >>> 17 % 3 # the % operator returns the remainder of the division 2use the ** operator to calculate powers >>> 5 ** 2 # 5 squared 25 >>> 2 ** 7 # 2 to the power of 7 128full support for floating pointmath operators with mixed type operands convert the integer operand to floating point >>> 4 * 3.75 - 1 14.0in interactive mode, the last printed expression is assigned to the read-only variable _ >>> tax = 12.5 / 100 >>> price = 100.50 >>> price * tax 12.5625 >>> price + _ 113.0625 >>> round(_, 2) 113.06 |
Text |
string represented by type str can use single or double quotes to quote a quote escape character is used >>> 'doesn\'t' # use \' to escape the single quote... "doesn't" >>> "doesn't" # ...or use double quotes instead "doesn't" >>> '"Yes," they said.' '"Yes," they said.' >>> "\"Yes,\" they said." '"Yes," they said.' >>> '"Isn\'t," they said.' '"Isn\'t," they said.'use print() function for readable output >>> s = 'First line.\nSecond line.' # \n means newline >>> s # without print(), special characters are included in the string 'First line.\nSecond line.' >>> print(s) # with print(), special characters are interpreted, so \n produces new line First line. Second line.can print raw strings without escape chars using r before the string >>> print('C:\some\name') # here \n means newline! C:\some ame >>> print(r'C:\some\name') # note the r before the quote C:\some\namea raw string may not end in an odd number of \ characters string literals can span multiple lines one way is to use triple-quotes: """...""" or '''...''' end of lines are automatically included in the string prevent end of line by adding a \ at the end of the line >>> print("""\ ...Usage: thingy [OPTIONS] ... -h Display this usage message ... -H hostname Hostname to connect to ...""") Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect tostrings can be concatenated with the + operator, and repeated with * >>> # 3 times 'un', followed by 'ium' >>> 3 * 'un' + 'ium' 'unununium'two or more string literals next to each other are automatically concatenated >>> 'Py' 'thon' 'Python'useful when breaking long strings >>> text = ('Put several strings within parentheses ' ... 'to have them joined together.') >>> text 'Put several strings within parentheses to have them joined together.'only works with two literals though, not with variables or expressions concatenate variables or a variable and a literal, use + >>> prefix + 'thon' 'Python'strings can be indexed >>> word = 'Python' >>> word[0] # character in position 0 'P' >>> word[5] # character in position 5 'n'indices can be negative count starts from the right negative indices start at -1 >>> word[-1] # last character 'n' >>> word[-2] # second-last character 'o' >>> word[-6] # note case is maintained 'P'slicing for substrings can be done >>> word[0:2] # characters from position 0 (included) to 2 (excluded) 'Py' >>> word[2:5] # characters from position 2 (included) to 5 (excluded) 'tho'slicing has defaults
>>> word[:2] + word[2:] 'Python' >>> word[:4] + word[4:] 'Python'for non-negative indices the length of a slice is the difference of the indices, if both are within bounds the length of word[1:3] is 2 using an index that is too large will result in an error >>> word[42] # the word only has 6 characters Traceback (most recent call last): File "out of range slicing indexes are handled gracefully >>> word[4:42] 'on' >>> word[42:] ''Python strings are immutable need to create a new string to accommodate desired changes >>> 'J' + word[1:] 'Jython' >>> word[:2] + 'py' 'Pypy'additional information
|
Lists |
list of comma-separated values between square brackets usually items are all of the same type lists can be indexed and sliced support operations like concatenation are mutable use list.append to add new items to end of list simple assignments in Python never copies data - pointers slice operations return a new list - shallow copy lists can contain lists |
First Steps Towards Programming |
>>> # Fibonacci series: >>> # the sum of two elements defines the next >>> a, b = 0, 1 >>> while a < 10: ... print(a) ... a, b = b, a+b ... 0 1 1 2 3 5 8first line shows a multiple assignment body of the loop is indented indentation is Python's way of grouping statements each line within a basic block must be indented by the same amount the print() function writes the value of the argument(s) it is given strings are printed without quotes and a space is inserted between items >>> i = 256*256 >>> print('The value of i is', i) The value of i is 65536the keyword argument end can be used to avoid the newline after the output >>> a, b = 0, 1 >>> while a < 1000: ... print(a, end=',') ... a, b = b, a+b ... 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987, |