In [ ]:
%autosave 0

Python 2nd step: Variables and Data type

In case of C or other compile langueage, variables need to be declared with data type. In Python, Object have data type, variables just refer Object. Following sequence is valid in Python.


In [ ]:
x = 1
print('x =', x, type(x))
x = 'abc'
print('x =', x, type(x))

In the following example, the data of the Object which x refered did not change but x refered new Object.


In [ ]:
x = 1
print('x =', x, 'object id:', id(x))
y = x
x += 1
print('x =', x, 'object id:', id(x))
print('y =', y, 'object id:', id(y))

Basic Data type

Plese refer Python3 reference for detail.

  • Boolean
  • Integer
  • Float
  • None
  • String

Except above, Python support Complex ( $i: i^2 = -1$ ) as well. ( j is used intead of i )


In [ ]:
def void_vundc():
    return None

x = void_vundc()
print(type(x))

In [ ]:
x = 0+1j
print(x**2)

Boolean

True and False are reserved word for Boolean value. Not only Boolean but also other type such as Integer,String or List can be used for True/False check of if and while.


In [ ]:
x = True
print(x, type(x))
x = False
print(x, type(x))
x = (1 == 1)
print('1==1:', x, type(x))
x = (1 > 2)
print('1>2:', x, type(x))

In [ ]:
# Evaluate this cell before foloowing cell

def check_true(b):
    if b:
         print(b,"is treated as true")
    else:
         print(b,"is treated as false")

In [ ]:
check_true(0)
check_true(1)
check_true(0.0)
check_true(0.1)
check_true(-2)
check_true('')
check_true(' ')
check_true([])
check_true([0])

In [ ]:
check_true(0)
check_true(1)
check_true(0.0)
check_true(0.1)
check_true(-2)
check_true('')
check_true(' ')
check_true([])
check_true([0])

Boolean operators

and,or,not are the reserved words and used as boolean operators. (same as && || ! of C) These are not bitwise operation but logical operation.


In [ ]:
print (True and True, True and False, False and True, False and False)
print (True or True, True or False, False or True, False or False)
print (not True, not False)
print("\nBitwise operation: 1('0001'b) & 2('0010'b)")
x = 0b01 & 0b10
print(x, type(x))
check_true(0b01 & 0b10)
print('\nLogical operation: 1 and 2')
x = 0 and 2
print(x, type(x))
check_true(0b01 and 0b10)
print('\nLogical operation: 1 or 2')
check_true(0b01 or 0b10)

and operation: 1 and 2 -> 1 is evaluated (true) - 2 is evaluated (true) -> true 0 and 2 -> 0 is evaluated (false) --------------------------> false

or operation 1 or 2 -> 1 is evaluated (true) ----------------------------> true 0 or 2 -> 0 is evaluated (false) -> 2 is evaluated (true) -> true

Value comparisons

Same as C. >, >=, <, <=, ==, != can be used to compare 2 objects. The objects do not need to have the same type (some combination such as Integer and String are not allowed). These operator can be used other than numeric value, such as String.

Identity comparisons

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. Object identity is determined using the id() function. x is not y yields the inverse truth value. is operator shall not be used to compare the value of 2 objects. == shall be used instead.


In [ ]:
x = 'abc'
y = 'abc'
print("\nResult of 'x is y':", x is y, "  Result of 'x == y':", x == y)
print('x:', x, 'y:',y, '\nid(x):', id(x), 'id(y):', id(y))

x += 'd'
y += 'd'
print("\nResult of 'x is y':", x is y, "  Result of 'x == y':", x == y)
print('x:', x, 'y:',y, '\nid(x):', id(x), 'id(y):', id(y))

Membership test

The operators in and not in test for membership. x in s evaluates to true if x is a member of s, and false otherwise. x not in s returns the negation of x in s . All built-in sequences and set types support this as well as dictionary. (i.e. String, List, Tupple ... support this)


In [ ]:
s = 'abc'  # s is a String
print('x' in s)
print('b' in s)
print('ab' in s)
print('ac' in s)
print()

t = [1, 2, 3, 4, [5,6]]  # t is a List
print('number of elements of t:',len(t))
print(5 in t)
print(5 in t[4])  # t[0]: 1, t[1]: 2, ... t[4]: [5,6]
print(3 in t)
print()

u = ('a', 'b', 3, 0.1)   # u is a Tupple
print(0.1 in u)
print('c' not in u)

Integer

0, 100, -10000, 0b1001, 0o664, 0x01a0 etc. The size of integer is Unlimited in Python. (most computer langueage does not support unlimited integer)

int() function can be used to convert from float or string to integer. Fractional part (digits below 0) of float value is discared when it is converted to integer.


In [ ]:
x = 1.9999
print('x:', x, 'int(x):', int(x))
print()
print('2^1000 = ', 2 ** 1000)

Float

0.1, 10e3 etc. The result of the operation of integer and float is float. float() function can be used to convert from integer or string to float.

Numeric operation

+,-,*,/,//,%,** are numerical operators of Python. It's almost same as C, except devide (/ and //), and power (**). / always returns float, // returns integer (which will be converted to float, if one of the argument is float). The behavior of // is similar to C, but not same for negative result.


In [ ]:
x = 3.1415
x += 0.1
print(x)
print(round(x, 6))

In [ ]:
x = 1+1
print('1+1:', x, type(x))
x = 1-3
print('1-3:', x, type(x))
x = 4/2  # / returns float
print('4/2:', x, type(x))
x = 5//2 # // returns integer if both of arguments are integer
print('5//2:', x, type(x))
x = 5//(-2)  # Python returns floor(x) for the result of negative division of //
print('5/-2:', x, type(x))
x = 5//(-2)
print('5//(-2)', x, type(x))
x = 5//2.0   # result is converted to float if one of the auguments is float
print('5//2.0:', x, type(x))
x = 2*8
print('2*8:', x, type(x))
x = 5%2
print('5%2 (Modulo):', x, type(x))
x = 2**8
print('2**8 (exponents):', x, type(x))
x = 2**(1/2)
print('2**(1/2) (square root):', x, type(x))

None

This type has a single value. There is a single object with this value. This object is accessed through the built-in name None. It is used to signify the absence of a value in many situations, e.g., it is returned from functions that doesn't explicitly return anything. Its truth value is false.


In [ ]:
x = None
print(x == True, x == False)    # None is not True or False
if x:
    print ('None is evaluated as True')
else:
    print ('None is evaluated as False')

def do_nothing():
    return

y = do_nothing()
print('y:', y, 'id(x):', id(x), 'id(y):', id(y))   # Only 1 object of None exists

if y:
    print('y is treated as True')
else:
    print('y is treated as False')
    
if y == False:
    print('y == False')
else:
    print('y != False')
    
if y == True:
    print('y == True')
else:
    print('y != True')

String

String can be made using single quate ('), double quate("), triple single quate or double quate. str() function converts numeric value to string.
The biggest difference of String between C and Python is that the String is immutable(not changeable) in Python, and String of Python has its own method.


In [ ]:
x = 'string'
print(x, type(x))
x = "it's string too"
print(x, type(x))

print('double quatation(") can be written without escape in single quatation(\')')
# escape sequence \' and \" is also possible
x = 'a\'b\"c'
for c in x:
    print (c, end = ' ')
print()

x = '''Triple quatation is OK too'''
print(x, type(x))
# Triple quatation is usually used to make multiple line string
x = '''
1st line,
2nd line,
3rd line
'''
print(x, type(x))

docstring

The first string in the module or function is called docstring. It is strongly recommended to write docstring. Indent of the quatation need to be alligned. docstring is shown on help().


In [ ]:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
    
'''
    This is a module docstring
    This program displays number from 1 to 10 horizontally
'''
    
def show_num(first,last):
    """
    first: Start number
    last:  End Number - 1
    Return: None
    """
    for i in range(first,last):
        print (i, end = ' ')
    print()

# help(module_name)  shows the help of the nodule (python script)
help(show_num)

In [ ]:
import math

# help(math)

help(math.cos)

Concatenation and Repetation

+ operator returns concatenated(merged) string, * operator returns repeated string.


In [ ]:
x = 'abc' + 'xyz'
print(x, type(x))
x = 3 * '123'
print(x, type(x))

Indexed reference and Slice

Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:
In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring:


In [ ]:
# Index
word = 'python'
print(word[0], word[1], word[2])
print(word[-1], word[-2], word[-6])

# Slice
print(word[0:2])  # from word[0] 'p' to BEFORE word[2] => 'py'
print(word[2:5])  # from word[2] 't' to BEFORE word[5] => 'tho'
print(word[:2])   # from word[0] to BEFORE word[2]
print(word[2:])   # from word[2] to the end
print(word[:])    # all
print(word[::2])  # from top to last, step=2

for c in word[::-1]:  # from last to top (all string, step: -1)
    print(c, end = '')
print()

print(word[::-1])

Length

The built-in function len() returns the length of a string:


In [ ]:
x = 'abc'
print(x, '\nlen(x):', len(x))
x = 'Hello world! ' * 10
print(x, '\nlen(x):', len(x))

Method

String has many method. See https://docs.python.org/3.5/library/stdtypes.html#string-methods for detail. (this document is in NFS directory. library.pdf)

help(str) shows overview.


In [ ]:
s = 'a b c'
x = s.split()
print(x)

In [ ]:
help(str)

In [ ]:
s = 'test string'
print(s, s.capitalize())
print("Number of 't' in", s, s.count('t'))
print("Location of 'str' in", s, s.find('str'))
print("Location of 'stx' in", s, s.find('stx'))
print(s, 'islower ?', s.islower())
print('Convert to upper case:', s.upper())
x = s.split()
print('Spit to List:', x, type(x))

print("{0} + {1} = {2}".format(2, 3, 2+3))  # {0}: first parameter ...

In [ ]:
# Hands on
# find some methods in the help(str) and try them