This wiki has been archived and made read-only.
For up-to-date information about TkkrLab and it's projects please visit our main website at tkkrlab.nl.

PythonBasicTypes

From

Jump to: navigation, search

general

This is the first part of PythonMaterial.

Python can be started in interactive mode. Use 'exit()' or ^D to leave it again.

In interactive mode every line is expected to be an expression. There is a special variable '_' that holds the last calculation result.

2+3
8 * _
 
help(int)
 
import __builtin__
help(__builtin__)
 
exit()
  • The arrow keys up and down can be used to navigate through the history of entered lines.
  • The help function is used to show the documentation strings of all the methods and fields inside a class or module. You can use PgUp/PgDown inside it and use 'Q' to exit it again.
Assignment
1 Start python, enter the given expressions
2 Which version of python do you have currently?
3 What is the description of the help statement itself?

integer

This is a normal number. On 32 bit systems it can contain all numbers up to 9 digits both positive and negative. On 64 bit systems this maximum is 18 digits.

""" Show basic integer operations """
import sys
import math
 
print "Maximum integer value:", sys.maxint
print "Number of decimals:", math.log10(sys.maxint)
print "Size of integer:", sys.getsizeof(1)
print
print "Constants:", 12, 223991, 0b1111, 0x11, int("0xFF", 0), int("0b101", 0),
print int("1100", 2), int("777", 8)
 
print "Operators:", 1 + 2, 55 - 8, 22 * 2, (3 + 2) * 2,
print 4 / 3, 9 // 2, 273 % 100, 2 ** 8
print "Binary operators:", 260 & 255, ~10, 16 | 1, 5 ^ 6, 1 << 4,
print 1025 >> 1, -1 >> 16,
print bin(93), hex(93)
print "Functions:", int(73.11), abs(-10), pow(2, 2), divmod(5, 2)
print "List functions:", max(1, 11, 2), min(12, 4)
 
a = 1
a += 10
a *= 4
a -= 2
a %= 100
 
print "The answer:", a
print "Bit-length:", a.bit_length()
 
del a
# print a
  • The use of '//' is more correct because in python 3.0 the '/' operator will always return a float.
  • The '%' is the modulus operator. It returns the remainder after a division.
  • The '**' is the power operator.
  • '&' performs bitwise and, '|' bitwise or, '^' bitwise xor and '~' bitwise complement.
  • '<<' and '>>' perform bit shifts. '>>' will keep the negative sign intact.
  • In python 3.0 the print statement will become a normal function like: print("Results:", 12, 8)

More in depth overview: Python operators

Assignment
1 Run "python linebyline.py integer.py"
2 What is the divider and remainder of 21040 divided by 99
3 What is the bit length of 2012
4 Give the binary value of The answer
5 What value have bits 16 till 20 of the number -6814423232

long

This is the fall-back type when numbers get longer than an integer can hold. It is not a 64 bits number on 32 bit systems but can hold much larger numbers only restricted to the current memory and processor power.

Python will automatically switch an integer to long when it encounters numbers that are too high but not automatically back to int when they get smaller.

""" Show basic long operations """
import sys
bits = 32  # switch to 64 for the examples on a 64 bits version of python
 
print "Size of long:", sys.getsizeof(1L), sys.getsizeof(2 << 200)
print
print "Constants:", 12L
print "Still an int:", 1 << bits - 2, type(1 << bits - 2)
print "Exact too long:", 1 << bits - 1, isinstance(int(1 << bits - 1), long)
 
lower = (1 << bits - 1) - 1
print "Lower but still long:", lower, type(lower)
print "But can be cast back:", int(lower), isinstance(int(lower), int)
a = 1 << 99
b = -1
print "Bit length:", a.bit_length(), b.bit_length()
Assignment
1 What it the bit length of the number 1 with 30 zero's appended.
2 What is the bit length of 4 raised to exponent 4 and again raised to exponent 4
3 What is the overhead in bytes of a long type vs an integer

float

Python knowns one floating point type. But it is quite precise.

""" Show basic float operations. """
import sys
import math
print "Min and max float value:", sys.float_info.min, sys.float_info.max
print "Precision in decimals:", sys.float_info.dig
print "Size of float:", sys.getsizeof(1.2)
print
print "Constants:", 12.1, 2.1e-4
print "Operators:", 2.0 / 16
print "Functions:", abs(-10.2), pow(2, .5), int(10.51), int(-2.1)
f = 2.3
r = f.as_integer_ratio()  # see also rational PythonAdvancedTypes
print "Exact calculation:", r, float(r[0]) / r[1]
print "List functions:", max(1.2, 7.3, -1.0)
g = 5.0
print "Integer tests:", f.is_integer(), g.is_integer()
print "Rounding", round(1.2336), round(1.2336, 3), math.ceil(-1.4),
print math.floor(-1.4)
print "Hash", hash(2.1)
Assignment
1 What will be the yearly interest of 1000 with 3% monthly interest
2 Enter in python '14.35 // 3' and '14.35 % 3' is the answer what you expected?
3 What are the distinctions between int() and floor()

boolean

""" Show basic boolean operations """
import sys
print "Size of boolean:", sys.getsizeof(True)
print
print "Constants:", True, False, bool("True")
print "Operators:", True and True, True or False, not False
print "Check operators:", 2 < 3.1, 3 > 1, 3 <= 3, 22 == 33, 3.1 != 3.100001
print "Exact match:", 2.1 is 2.1, '22' is "22", 22 is not "22", 33 is not 33L
print "If as operator:", 2 if True else 3
print "True values:", 1 if 2 else 0, 1 if "d" else 0
print "False values:", 1 if 0 else 0, 1 if "" else 0
print "A bit strange:", True == 1, True == 2
  • With the 'is' operator both the value and the type should be the same.
  • Other types can be used in places when booleans are expected. Both 0 and "" will be counted as false.
Assignment
1 Show entrance fee for adults of 20, babies free, children between 5 and 12 or seniors above 65 for 10.
2 Show true when two values are within 5% range of each other.
3 What is strange about 'True == 2' versus '1 if 2 else 0' but why is it that? Hint: help(bool)

none

""" Show None type """
import sys
 
print "Size of none:", sys.getsizeof(None)
print "Constants", None
print "Is False", 1 if None else 0
  • This is equivalent to not defined or unknown value in a variable.

string

#!/usr/bin/python
# -*- coding: utf8 -*-
""" Show basic string operations """
import sys
 
print "Size of string:", sys.getsizeof("0123456789")
print
print "Constants:", "string's", "\"quoted\"", '"', """
multi line
strings. Even with " and ' tokens.
""",
print "This line \
contains no new lines.",
print r"Raw strings ignore the '\' token"  # handy for regular expressions
print "Operators:", "one" + "two", "A" * 5, chr(64), ord('F'), ord(u'€')
 
print "Functions:", len("abcdefg"), "abc".capitalize(), "abcdëf".upper(),
print u"abcdëf".upper(), "ACdE".lower(), "AbbA".swapcase()
 
print "Search:", "aabaabaab".count("ab", 1, 12), "abba".find("bb"),
print "abccd".endswith("ccd"), "abcd".startswith("abc"),
print "aabab".replace("ab", "cd"), "abcdefabc".rfind("ab"),
 
try:
    print "abbba".index("aba")
except ValueError:
    print False
print "Tests:",  "abccd".endswith("ccd"), "AbcD".isalpha(), "abbA".islower(),
print " \t".isspace()
print "Join:", ", ".join(["a", "bc", "d", "e"])
 
print "Split:", "ab,cd,ef".rpartition(","), "a,b,c,d,e".rsplit(",", 2)
print "Strip:", "abcafab".rstrip("fab"), "abcdefa".strip("af"), " 23 ".strip()
  • The u in front of a string indicates that it contains the slightly different unicode strings.
  • A couple of functions like 'count', 'find', 'index', 'endswith', 'startswith' can work on a substring from the second argument 'start' till the optional third argument 'end'.
  • The functions starting with the extra 'r' or 'l' work from the 'right' or 'left' side of the string.
  • Strip functions normally strip spaces and tabs but can be used to strip all kind of tokens.
Assignment
1 Write code that shows from a string in variable 's', the length, the uppercase value, the ascii code of the first character.
2 Try it with s = 'Tkkrlab' or 'something' or 'ø' or u'ëeíùçśṫũîṣọḍḋōö'
3 Show the string 's' without leading spaces, tabs or comma's. And the string 'good' if it contains the word 'tkkrlab' somewhere and 'very good' it if contains 'tkkrlab' more than once.