# 03Python Syntax - Basic Data Type

#### Preface

Variables are designed to enable computers to remember a certain state of things like people. The value of variables is used to store the state of things. It is obvious that the state of things can be divided into different kinds (such as people's age, height, position, salary, and so on), so variable values should also have different types. Here is a step-by-step introduction to several basic data types commonly used in Pyhton.

#### What is data

1. Data is a number, that is, the result we get by observation, experimentation, or calculation
2. Data can be text, images, sounds, etc. (e.g. n=1, 1 is the data we want to store)

#### Why does data differ between different types

1. Data is used to represent states, different states should have different types of data to record

#### python basic data types

1. Numbers (int integer, float floating point, complex) are mainly used for operations
2. String (str simple small amount of stored data)
3. List (list ordered data [1,'2', True,[1,2,3], {'a': 1}])
4. Dictionary (dict highly correlated data {'name':'xiaoyu','age': 25,'interest': ['java','python']})
5. set
6. tuple

#### 1. Number type

##### Integer int
• Role: Plastic number correlation used to represent age, grade, number of people, phone number, etc.
• Definition
```age = 20  #Age
level = 100  #Grade
pcs = 35  #Number
phone = 13912345678#Telephone
```
##### float floating point
• Role: Numeric correlation with decimal points for salary, height, weight, etc.
• Definition
```salary = 13.0  #Pay (K)
hight = 1.78  #Height (M)
weight = 67.5  #Weight (KG)
```

complex

##### Use of numeric types
• Assignment operation
```num = 99         #Define Numbers
num = num + 1  #Apply numbers over and over again
print(level)       #100
```
• Mathematical operations
```print(10 + 5.5)   #15.5
print(5.5 + 5.5)  #11
print(1.2 + 5.5)  #6.7
```
• Compare Size
```num = 98          #Definition
print(num == 98)  #True
print(num < 100)  #True
print(num > 100)  #Flase
```

#### 2. String type str

• Role: Used to represent descriptive text information such as name, description, address, etc.
• Definition
```In single quotation marks / Double Quotes / In triple Quotes,Consisting of a string of characters
name = 'shawn'
sex = "man"
from = "Chian"
site = "ShangHai"

Nesting requires quotation marks to be distinguished
msg = "I am from 'Chins JiangXi'"

Multiple lines can be written within three quotation marks(Three Single / Three double)
info = """
Info 1
Information 2
.....
"""

info1 = '''
Info 11
Information 12
.....
'''
```
##### Use of strings
1. StringBuilder
```#"+" Plus Stitching
x = "aaa"
y = "bbb"
print(x + y)  #"aaabbb"

#"*" Multiplication Sign Stitching
x = "dd"
print(x * 3)  #"dddddd"
#ps: Character stitching is not recommended because it is extremely inefficient
```
1. String and variable name
```Quoted" "Is the variable value
"xxx"  #String type

Unquoted variable names
xxx    #Variable name language binds variable values before it can be used

To the left of the equal sign must be the variable name
aaa = "xxx"
"aaa" = "xxx"  #Report syntax error, variable name cannot have quotation marks
```
1. Comparison between strings
```#String comparisons are compared one-to-one, according to the ASCLL code table
#Returns the decimal corresponding to the letter through the "ord()" function
print(ord("a"))  #97
print(ord("b"))  #98
print(ord("d"))  #100
print(ord("z"))  #122

#Compare, one by one, starting with the first letter
print("a" > "b")     #False
print("adz" < "z")   #True
print("bbb" > "bz")  #False
```

#### 3. List list

• Role: Store multiple values in index/order
• Features: generally store values of the same nature
• Definition
```stay"[ ]"Separate multiple values of any type with commas, Also called element
myList = [111,2.2,"das",["sada",3123,2.5,[454,"cadc"]]]
hobbies = ['pingpong','read','run']
names = ["aaa","bbb","ccc"]
salaries = [12.5,15.5,16.5,17,17.5,...]
```
• Use
Lists use index values, indexes correspond to data locations, forward indexes start at 0, reverse indexes start at -1

1. Value

```Remove student name forward"bbb"
print(names[1])

Reverse student name"bbb"
print(names[-2])
```

2. Nested Value

```take out"454"
l = [111,2.2,"das",["sada",3123,2.5,[454,"cadc"]]]
print(l[-1][3][0])

Detailed steps
l[-1]        #["sada",3123,2.5,[454,"cadc"]]
l[-1][3]     #[454, "cadc"]
l[-1][3][0]  #454
```

#### 4. Dictionary dict

• Role: Store multiple values by attribute name, Key: value combination
• Features: Generally used to store values of different nature: a person's characteristics, etc.
• Definition
```stay"{ }"Separate multiple entries with commas "key : value"
among"value"Can be of any type, and"key"Typically a string type
shawn_info = {"name":"shawn","age":22,"sex":"man","hight":1.73}

Or write it like this
shawn_info = {
"name":"shawn",
"age":22,
"sex":"man",
"hight":1.73
}
```
• Use
1. Value
```take out"shawn"Gender
shawn_info = {"name":"shawn","age":22,"sex":"man","hight":1.73}
print(shanw_info["sex"])  #man
```

2. Nested Value

```Dictionary Set Dictionary,Of course, you can also set a list
dic = {
"shawn": {"age": 15, "sex": "man"},
"egon": {"age": 18, "sex": "woman"},
"song": {"age": 18, "sex": "man"},
"hai": {"age": 18, "sex": "man"}
}

print(dic["song"]["age"])  #18
print(dic["hai"]["sex"])   #man
print(dic["egon"]["age"])  #18
```

#### 5. tuple

• Tuples are similar to lists, except that elements of tuple s cannot be modified.
• Tuples are written in parentheses (), with elements separated by commas.
• Element types in tuples can also be different.
• Tuples are similar to strings and can be indexed, with subscript indexes starting at 0 and -1 at the end. It can also be intercepted.
• In fact, you can think of a string as a special tuple.
• Constructing tuples with 0 or 1 elements is special, so there are some extra grammar rules:
```tup1 = ()     # Empty tuple
tup2 = (20,)  # An element that needs to be followed by a comma
```

Be careful
1. Like strings, elements of tuples cannot be modified.
2. Tuples can also be indexed and sliced in the same way.
3. Note the special grammar rules for constructing tuples with 0 or 1 elements.
4. Tuples can also be stitched using the + operator

#### 6. Collection set

• A set is a sequence of unordered, non-repeating elements.
• The basic functions are to test membership and delete duplicate elements.
• You can use curly braces {} or the set() function to create a collection, note that creating an empty collection must use set() instead of {} because {} is used to create an empty dictionary.
Example
```#!/usr/bin/python3
student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}
print(student)  # Output set, duplicate elements are automatically removed

# Member Test
if ('Rose' in student):
print('Rose In a collection')
else:
print('Rose Not in collection')

# Set can perform set operations
a = set('abracadabra')
b = set('alacazam')

print(a)
print(b)
print(a - b)  # The difference between a and b
print(b - a)  # The difference between b and a
print(a | b)  # Union of a and b
print(a & b)  # Intersection of a and b
print(a ^ b)  # Elements that do not exist in a and b

# Output Results
{'Jim', 'Mary', 'Rose', 'Tom', 'Jack'}
Rose In a collection
{'d', 'c', 'r', 'a', 'b'}
{'l', 'c', 'm', 'a', 'z'}
{'d', 'b', 'r'}
{'l', 'm', 'z'}
{'l', 'd', 'c', 'r', 'm', 'a', 'b', 'z'}
{'c', 'a'}
{'l', 'd', 'r', 'm', 'b', 'z'}
```

#### 7. Boolean type bool

• Role: Boolean types have only two types of values: True and False, which are often used as conditions, or 1 for true and 0 for false.
• Definition

1. Displayed Boolean Values

```x = True
y = False
print(type(x))   #bool
print(10 > 9)    #True
print(10 == 9)   #True
print(10 < 9)    #False

x = None
print(x is None)  #True
```

2. Implicit Boolean Values

```# All types of values can be used as implicit Boolean values
# The Boolean values of "0", "empty", "None" are "False", and the rest are "True".
print(bool(0))    #False
print(bool(""))   #False empty string
print(bool([]))   #False Empty List
print(bool({}))   #False Empty Dictionary
print(bool(None)) #False
print(bool(1))    #True
```

Keywords: Python py

Added by winkhere on Mon, 07 Feb 2022 19:29:47 +0200