<jupyter_start><jupyter_text>Lesson 2: Basic data type, structure and arithmetics in python>  catalogue>1. [Data type](data_type)>2. [Data structure](data_structure)>3. [Arithmetics](arithmetics)>4. [Control flow](control_flow) 1. Data type 1. Integer:`int`> `int` means integer, like 7, 8, 9. We deal with intergers in our work for most of the time.<jupyter_code>from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

a = 3
type(a)
a = 3.3
int(a)<jupyter_output><empty_output><jupyter_text>2. Floating point (real number): `float`> `float` means a number with decimal, like 2.1, 3.8, 5.6 and so on.<jupyter_code>f = 3.3
type(f)
f = 3
float(f)<jupyter_output><empty_output><jupyter_text>3. Boolean: `bool`>* The 'bool()' method converts a value to Boolean (True or False), using the standard truth testing procedure.>* It's not mandatory to pass a value to bool(). If you do not pass a value, bool() returns False. In general use, bool() takes a single parameter value.>* Anything empty or zero will regard as False, including 0, 0.0, False, (), \[\], {}.<jupyter_code>b = 0
bool(b)
b = []
bool(b)
b = [0]
bool(b)<jupyter_output><empty_output><jupyter_text>4.  String `str`>* 'str' means string, a sequence of characters, like peking_university, PHBS and so on.>* Strings can be created by enclosing characters inside a single quote or double quotes, like '',"". Even triple quotes can be used in Python but generally used to represent multi-line strings and doc-strings.<jupyter_code>s = "Awesome to be in FML"
s<jupyter_output><empty_output><jupyter_text>Escape character in strings>some character has the specific meaning in string, if you want to present the original meaning, escape character is a good help.* \\' means single quote* \\" means double quote* \\\ means backslash* \n means new lineIf you want to print 'Xiao Ming says "I don't feel well today"', add excape character before double quota.<jupyter_code>s = " Xiao Ming says \"I don't feel well today\""
print(s)<jupyter_output>Xiao Ming says "I don't feel well today"<jupyter_text>String functionsString type is more complicate than interger, float or boolean.Python has a built-in string class named "str" with many handy features, which allow us to easily make modifications to strings in Python. Here are some of the most common string methods:| Function                  | Description      |   |:----------:|:-------:|| str.lower()   | Returns the lowercase or uppercase version of the string  |                                           | str.strip()  | Returns a string with whitespace removed from the start and end || str.find('other')  | Searches for the given other string within s, and returns the first index where it begins or -1 if not found || str.replace('old', 'new') | Returns a string where all occurrences of 'old' have been replaced by 'new'|| str.split('delimiter')    | Returns a list of substrings separated by the given delimiter. 'a,b,c'.split(',') -> ['a', 'b', 'c']. As a convenient special case, str.split (with no arguments) splits on all whitespace chars. 'a b c'.split() -> ['a','b','c'] || str.join(list)            | Joins the elements in the given list together using the string as the delimiter.The list elements will be joined by sequences. e.g. '---'.join(['a', 'b', 'c']) -> a---b---c    |<jupyter_code>s = "FML is here     "
s.lower()
s.strip()
s.find('is')
s.replace('here', 'great')
s.split('is')<jupyter_output><empty_output><jupyter_text>Format stringFormat string is a conveniet way to print standard string.> There are two way to perform format string* `%` as the placehoder>>* `%s` can replace string, `%f` can replace float, `%d` can replace interger.>>* Formatting integers and floating-point numbers can also specify whether to complement 0 and the number of integers and decimals. * `format` function is a more powerful way with more complex syntax.>>* "{0} {1}".format("hello", "world") can select position>>* `{:.2f}` `:` in the `{}` to adjust print format.<jupyter_code># %s
"Hi, my name is Liusheng"
"Hi, my name is Yangyang"
s = "Yangyang"

"Hi, my name is %s"%s

#%f
f = 3.1415926535
"My answer is %08.2f"%f
"My answer is %08.2f"%f


#%d
d = 123456
"This is %015d"%d

# format function
a = 1000000
"{:,}".format(a)
"{:.2e}".format(a)<jupyter_output><empty_output><jupyter_text>2. Data structure 1. List `list`>`list`is an ordered collection of elements that can be added and deleted at any time. \[ \] represent the list<jupyter_code>FML = ['tencent', 'big_data' ,'new_media']

type(FML)

#length
len(FML)

# Index
FML[0]
FML[1]
FML[2]
FML[-1]
FML[-2]
FML[-3]<jupyter_output><empty_output><jupyter_text>List function>List is an ordered sequence of items. It is one of the most used data structure in Python and is pretty flexible. All the items in a list do not need to be of the same type.| Methods   | Description                                                                  ||-----------|------------------------------------------------------------------------------|| append()  | Adds an element at the end of the list                                       || count()   | Returns the number of elements with the specified value                      || extend()  | Add the elements of a list (or any iterable), to the end of the current list || index()   | Returns the index of the first element with the specified value              || insert()  | Adds an element at the specified position                                    || pop()     | Removes the element at the specified position                                || remove()  | Removes the first item with the specified value                              || reverse() | Reverses the order of the list                                               || sort()    | Sorts the list                                                               |<jupyter_code>FML = ['tencent', 'big_data' ,'new_media']

#append
FML.append(666)
FML
#count
FML.count(666)
#extend
FML.extend([1,2,3])
FML
FML + [4]
#index
FML.index(3)
#insert
FML.insert(0,'OK')
FML
#remove
FML.remove(2)
FML
#reverse
FML.reverse()
FML<jupyter_output><empty_output><jupyter_text>List slice>slice is a build-in data type in python. It's pretty handy to select data from list, tuple, array, matrix and other order data struction.* Syntax: sliceable_data[start:stop:step]* The start is default to 0, end is default to the length. For step - the amount by which the index increases, defaults to 1. If it's negative, you're slicing over the iterable in reverse.<jupyter_code>#creat a slice
s = slice(1,4,1)
type(s)

r=[1,2,3,4,5,6]

#use the silce
r[s]

#other use of slice
r[::2]
r[::-2]
r[2::2]
r[:2:]<jupyter_output><empty_output><jupyter_text>2. tuple `tuple`>* `tuple`is an ordered collection of elements, but it can not modify after initialization .() represent the tuple>* tuple is more safe than list, but some function in list is not available in tuple such as replace, pop, insert.>* under some circumstance, you can only use tuple， instand of list.<jupyter_code>FML = ('tencent', 'big_data' ,'new_media')

len(FML)
max(FML)
min(FML)<jupyter_output><empty_output><jupyter_text>3. Dictionatry `dic`>* A dictionary is a collection which is disordered, changeable and indexed, like d = {key1 : value1, key2 : value2}{} represent the `dic`<jupyter_code>FML = {"group_1":"big_data", "group_2":"tencent", "group_3":"new_media"}
type(FML)

#index
FML["group_1"]<jupyter_output><empty_output><jupyter_text>Dictionary function| Methods    | Description                                               ||------------|-----------------------------------------------------------|| fromkeys() | creates dictionary from given sequence                    || get()      | Returns value of the key, default=None                               || items()    | Returns view of dictionary's (key, value) pair            || keys()     | Returns view object of all keys                           || contains(key) | Return bool value by checking whether the key is in dict  || pop()      | Returns & removes element having given key                || values()   | Returns view of all values in dictionary                  || update()   | Updates the Dictionary                                    |<jupyter_code># from keys and values
group_key = ["group_%s"%s for s in range(1,4)]
group_key

FML = dict.fromkeys(group_key, "big_data")
FML

#get
FML["group_1"]
FML.get("group_1")

#items()
FML.items()

#keys()
FML.keys()

#values()
FML.values()

#pop()
FML.pop("group_1")
FML

#updata
FML_now = {"group_2":"tencent", "group_3":"new_media"}
FML.update(FML_now)
FML<jupyter_output><empty_output><jupyter_text>3. Arithmatic Basic rules| Operator          | Description                                                                                                         | Example                                                ||-------------------|---------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------|| `+` Addition        | Adds values on either side of the operator.                                                                         | a + b = 30                                             || `-` Subtraction     | Subtracts right hand operand from left hand operand.                                                                | a – b = -10                                            || `*` Multiplication  | Multiplies values on either side of the operator                                                                    | a * b = 200                                            || `/` Division        | Divides left hand operand by right hand operand                                                                     | b / a = 2                                              || `%` Modulus         | Divides left hand operand by right hand operand and returns remainder                                               | b % a = 0                                              || `**` Exponent       | Performs exponential (power) calculation on operators                                                               | a**3 =1000, a=10                                       || `//` Floor Division | The division of operands where the result is the quotient in which the digits after the decimal point are removed.  | 9//2 = 4, 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0 | **please figure out**  $$\frac{\sqrt{123\times14}+\frac{432}{234}}{3^4-25\%4}$$<jupyter_code>#put your answer here<jupyter_output><empty_output><jupyter_text>4. Control flow  Logic operators>The logical operators in Python (and, or, not) are often used in the if, if…else, and if…elif statements. They enable you to make multiple comparisons inside a single statement, such as to determine whether a value is within a certain range.| Operators | What it means                 | What it looks like  ||-----------|-------------------------------|---------|| and       |True if both are true          | x and y || or        |True if at least one is true   | x or y  || not       |True only if false             | not x   |  Comparison operators>In programming, comparison operators are used to compare values and evaluate down to a single Boolean value of either True or False. The following are the common comparison operators:| Operators| Meaning                  ||----------|--------------------------|| `==`     | Equal to                 || `!=`     | Not equal to             || `<`      | Less than                || `>`      | Greater than             || `<=`     | Less than or equal to    || `>=`     | Greater than or equal to |<jupyter_code>(6 > 5) and (2 < 4)
(8 == 8) or (6 != 6)
not(3 <= 1)<jupyter_output><empty_output><jupyter_text>Control flowsA control flow is a block of programming that analyses variables and chooses a direction in which to go based on given parameters. In python, all codes and statements are faithfully executed in exact top-down order. But what if you want to change the flow?>* `If-elif-else`>* `for` loop>* `while` loop>* `break-continue`>* `try-except`<jupyter_code>#if-elif-else
name = input("please input your group name")
if name == "big_data":
    print("group_1")
elif name == "tencent":
    print("group_2")
elif name == "new_media":
    print("group_3")
else:
    print("wrong name")
# for loop
FML = {"group_1":"big_data", "group_2":"tencent", "group_3":"new_media"}
for k,v in FML.items():
    print(k,v)
#while loop
total,i = 0,0
while i < 100:
    total += i
    i += 1
total<jupyter_output><empty_output><jupyter_text>Difference between for loops and while loops1. While Loops allow you put a condition in it, like `while i= 10). you can also substitute in a boolean(true/false) for 10 as well as many other types of variables.2. For Loops allow you to run through the loop many times you'd like it to run through the problem such as `for i in range(0,100)`, this will continually increase i until that condition returns false(>100), you can replace 10 with other numbers and variables, like `for name in name_list`, means that you want to loop the whole name_list to run through the problem. And it will quit once the condition is no longer being met.3. Generally speaking, if you want to use loop to do conditional comparison, `while` loops is work for you, if you want to loop every elements of a whole list, `for` is better.<jupyter_code>#break-continue
i = 1
while i < 9:
    print(i)
    if i == 5:
        break
    i = i + 1

i = 10
while i < 19:
    i = i + 1
    if i == 15:
        continue
    print(i)<jupyter_output>1
2
3
4
5
11
12
13
14
16
17
18
19<jupyter_text>The `try` statement works as follows.1. the `try`statement between the try and except (keywords) is executed.2. If no exception occurs, the except clause is skipped and execution of the try statement is finished.3. If an exception occurs during execution of the try clause, and its type matches the exception named after the except keyword, the except clause will be executed, **and the execution continues after the try statement.**4. If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops.<jupyter_code>list_1 = [14,2,"a",3,4.2]

for i in list_1:
    try:
        print(int(i))
    except Exception as e:
        print(e)

a = [1,2,3,"1","3","a",4,6,2,"2.3",6.4]
for i in a:
    try:
        print(int(i))
    except Exception as e:
        print(e)<jupyter_output>1
2
3
1
3
invalid literal for int() with base 10: 'a'
4
6
2
invalid literal for int() with base 10: '2.3'
6
{'fraction_non_alphanumeric': 0.13555872175859962, 'fraction_numerical': 0.019336454304905354, 'mean_word_length': 2.3838383838383836, 'pattern_counts': {'":': 11, '<': 77, '<?xml version=': 0, '>': 113, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 53, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '18', 'dir': 'jupyter-structured-clean-dedup', 'id': '107172', 'license': 'MIT', 'n_tokens_mistral': 4298, 'n_tokens_neox': 4089, 'n_words': 1685, 'path': 'Lesson_2.ipynb', 'repo_name': 'silenceon/FML_lesson_1', 'size': '14739'}