2.1 Palatable Python_Basic Syntax#1_Number&Data type

mseokq23·2024년 12월 29일

Palatable Python

목록 보기
4/11
post-thumbnail

2.1 Number type

2.1.1 Integer type

a = 123
a= -123
a = 0

2.1.2 Real number

a = 12.34
b = -123.5
c = 3.4e10

You can use "e or E" for exponential representation

a= 1.23E10  # a is 1.23^10
b= 1.23e-10 # b is 1.23^-10

2.1.3 Octal number

a = 0o12
b = 0o34

2.1.4 Hexadecimal

a = 0x1A
b = 0xEF

2.1.5 Operator (+, -, *, /, **, %)

  • " +, -, *, / "
>>> a = 1
>>> b = 2
>>> a + b
3
>>> a - b
-1
>>> a * b
2
>>> a / b
0.5
  • " ** "
>>> a = 3
>>> b = 4
>>> a ** b
81
  • %
>>> 7 % 3
1
>>> 3 % 7
3
  • //
    Return share after division
>>> 7 // 4
1

2.1.6 compound operator

+=, -=, *=, /=, //=, %=, **=
>>> a =2
>>> a += 1 # same as " a = a + 1 "
>>> print(a)
3

2.2 Data type

2.2.1 String data type

"Hello World"

'Python is fun'

"""Life is too short, You need python"""

'''Life is too short, You need python'''

# 4 method that can make string data type
>>> food = 'Python\'s favorite food is perl'
>>> say = "\"Python is very easy.\" he says."

# using \' or \" , can print directly ' or "

>>> multiline = "Life is too short\nYou need python"     
>>> print(multiline)
Life is too short
You need python
코드	설명
\n	    문자열 안에서 줄을 바꿀 때 사용
\t	    문자열 사이에 탭 간격을 줄 때 사용
\\	    \를 그대로 표현할 때 사용
\'	    작은따옴표(')를 그대로 표현할 때 사용
\"	    큰따옴표(")를 그대로 표현할 때 사용
\r	    캐리지 리턴(줄 바꿈 문자, 커서를 현재 줄의 가장 앞으로 이동)
\f	    폼 피드(줄 바꿈 문자, 커서를 현재 줄의 다음 줄로 이동)
\a	    벨 소리(출력할 때 PC 스피커에서 '삑' 소리가 난다)
\b	    백 스페이스
\000	널 문자
>>> head = "Python"
>>> tail = " is fun!"
>>> head + tail
'Python is fun!'

>>> a = "python"
>>> a * 2
'pythonpython'
print("=" * 50)
print("My Program")
print("=" * 50)

## answer
==================================================
My Program
==================================================
>>> a = "Life is too short"
>>> len(a)
17  # Length of string

2.2.1.1 String Slicing


# String Indexing

>>> a = "Life is too short, You need Python"
>>> a[0]
'L'
>>> a[12]
's'
>>> a[-1]
'n'
>>> a[-2]
'o'
>>> a[-5]
'y'

>>> b = a[0] + a[1] + a[2] + a[3]
>>> b
'Life'

>>> a[0:4]
'Life'
>>> a[0:2]
'Li'
>>> a[5:7]
'is'
>>> a[12:17]
'short'
>>> a[:17]
'Life is too short'
>>> a[:]
'Life is too short, You need Python'
>>> a[19:-7]
'You need'

e.g.

>>> a = "20230331Rainy"
>>> year = a[:4]
>>> day = a[4:8]
>>> weather = a[8:]
>>> year
'2023'
>>> day
'0331'
>>> weather
'Rainy'

2.2.1.2 string formatting

>>> "I eat %d apples." % 3
'I eat 3 apples.'
>>> "I eat %s apples." % "five"
'I eat five apples.'
>>> number = 3
>>> "I eat %d apples." % number
'I eat 3 apples.'
>>> number = 10
>>> day = "three"
>>> "I ate %d apples. so I was sick for %s days." % (number, day)
'I ate 10 apples. so I was sick for three days.'
  • 문자열 포맷 코드
    %s 문자열(String)
    %c 문자 1개(character)
    %d 정수(Integer)
    %f 부동소수(floating-point)
    %o 8진수
    %x 16진수
    %% Literal % (문자 % 자체)

2.2.1.3 Use with format code and numbers

>>> "%10s" % "hi"
'        hi'

>>> "%-10sjane." % 'hi'
'hi        jane.'

>>> "%0.4f" % 3.42134234
'3.4213'

>>> "%10.4f" % 3.42134234
'    3.4213'

2.2.1.4 format function

>>> "I eat {0} apples".format(3)
'I eat 3 apples'

>>> "I eat {0} apples".format("five")
'I eat five apples'

>>> number = 3
>>> "I eat {0} apples".format(number)
'I eat 3 apples'

# Put more than one value

>>> number = 10
>>> day = "three"
>>> "I ate {0} apples. so I was sick for {1} days.".format(number, day)
'I ate 10 apples. so I was sick for three days.'

# Put it by name

>>> "I ate {number} apples. so I was sick for {day} days.".format(number=10, day=3)
'I ate 10 apples. so I was sick for 3 days.'

# Mix index and name

>>> "I ate {0} apples. so I was sick for {day} days.".format(10, day=3)
'I ate 10 apples. so I was sick for 3 days.'
>>> a = "hobby"
>>> a.count('b')
2

# The count function returned the number of characters b in the string.
>>> a = "Python is the best choice"
>>> a.find('b')
14
>>> a.find('k')
-1
>>> a = "Life is too short"
>>> a.index('t')
8
>>> a.index('k')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> a = "Life is too short"
>>> a.index('t')
8
>>> a.index('k')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> ",".join('abcd')
'a,b,c,d'
>>> a = "hi"
>>> a.upper()
'HI'
>>> a = "HI"
>>> a.lower()
'hi'
>>> a = " hi "
>>> a.lstrip()
'hi '
>>> a= " hi "
>>> a.rstrip()
' hi'
>>> a = " hi "
>>> a.strip()
'hi'
>>> a = "Life is too short"
>>> a.replace("Life", "Your leg")
'Your leg is too short'

>>> a = "Life is too short"
>>> a.split()
['Life', 'is', 'too', 'short']


>>> b = "a:b:c:d"
>>> b.split(':')
['a', 'b', 'c', 'd']

2.2.2 List data type

>>> a = []
>>> b = [1, 2, 3]
>>> c = ['Life', 'is', 'too', 'short']
>>> d = [1, 2, 'Life', 'is']
>>> e = [1, 2, ['Life', 'is']]
>>> a = [1, 2, 3]
>>> a
[1, 2, 3]

>>> a[0]
1

>>> a[0] + a[2]
4

>>> a[-1]
3
>>> a = [1, 2, 3, ['a', 'b', 'c']]

>>> a[0]
1
>>> a[-1]
['a', 'b', 'c']  # a[-1]은 마지막 요솟값 ['a', 'b', 'c'] 
>>> a[3]
['a', 'b', 'c']  # a[3]은 리스트 a의 네 번째 요소



>>> a[-1][0]
'a'              #  a[-1]이 ['a', 'b', 'c'] 리스트이며, 이 리스트에서 첫번째 요소 가져옴

>>> a[-1][1]
'b'
>>> a[-1][2]
'c'

# triple index

>>> a = [1, 2, ['a', 'b', ['Life', 'is']]]

>>> a[2][2][0]
'Life'

2.2.2.1 Add list

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a + b
[1, 2, 3, 4, 5, 6]

2.2.2.2 Repeat list

>>> a = [1, 2, 3]
>>> a * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

2.2.2.3 Get length list

>>> a = [1, 2, 3]
>>> len(a)
3

2.2.2.4 Edit list

>>> a = [1, 2, 3]
>>> a[2] = 4
>>> a
[1, 2, 4]

2.2.2.5 Delete list elements with del function

>>> a = [1, 2, 3]
>>> del a[1]
>>> a
[1, 3]

2.2.2.6 Add element to the list - append

>>> a = [1, 2, 3]
>>> a.append(4)
>>> a
[1, 2, 3, 4]

>>> a.append([5, 6])
>>> a
[1, 2, 3, 4, [5, 6]]

2.2.2.7 Sort List

>>> a = [1, 4, 3, 2]
>>> a.sort()
>>> a
[1, 2, 3, 4]
>>> a = ['a', 'c', 'b']
>>> a.sort()
>>> a
['a', 'b', 'c']

2.2.2.8 Reverse List

>>> a = ['a', 'c', 'b']
>>> a.reverse()
>>> a
['b', 'c', 'a']

2.2.2.9 Return Index(location)

>>> a = [1, 2, 3]
>>> a.index(3)
2
>>> a.index(1)
0

# error occurs cuz, the value 0 does not exist in the list a.

>>> a.index(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 0 is not in list

2.2.2.10 Insert element in List

insert(a, b) is a function that inserts b into the a-th position of the list. Remember, Python counts numbers from zero

>>> a = [1, 2, 3]
>>> a.insert(0, 4)
>>> a
[4, 1, 2, 3]


>>> a.insert(3, 5)
>>> a
[4, 1, 2, 5, 3]

2.2.2.11 Remove List element

remove(x) is a function that deletes the first x in the list

>>> a = [1, 2, 3, 1, 2, 3]
>>> a.remove(3)
>>> a
[1, 2, 1, 2, 3]
>>> a.remove(3)
>>> a
[1, 2, 1, 2]

2.2.2.12 Pulling out list elements - pop

>>> a = [1, 2, 3]
>>> a.pop()
3
>>> a
[1, 2]
>>> a = [1, 2, 3]
>>> a.pop(1)
2
>>> a
[1, 3]

2.2.2.13 Number of elements x included in the list - count

examines how many x are in the list and returns the number of x

>>> a = [1, 2, 3, 1]
>>> a.count(1)
2

2.2.2.14 Extend List

In extension(x), x can only come with a list, and x is added to the original a list.

>>> a = [1, 2, 3]
>>> a.extend([4, 5])
>>> a
[1, 2, 3, 4, 5]
>>> b = [6, 7]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6, 7]

2.2.3 Tuple data type

"Tuple" is almost similar to "list" except for a few points,
and the differences from the list are as follows.

  • The list is surrounded by [], and the tuple is surrounded by ().

  • Lists can generate, delete, and modify element values,
    but element values in tuples cannot be changed.

The biggest difference between tuples and lists is whether the element values can be changed

Why Use Tuples :
it is used when you want the element value to be "fixed" at all times while the program is running.
elif: just use "List"

2.2.3.1 Attempt to delete & change a tuple element value

# Attempt to delete

>>> t1 = (1, 2, 'a', 'b')
>>> del t1[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion

# Attempt to change 

>>> t1 = (1, 2, 'a', 'b')
>>> t1[0] = 'c'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

2.2.3.2 Handing tuple (Same as List)

"Tuple" is exactly the same as "List" except that it cannot change the element values

2.2.3.3 Indexing

>>> t1 = (1, 2, 'a', 'b')
>>> t1[0]
1
>>> t1[3]
'b'

2.2.3.4 Slicing

>>> t1 = (1, 2, 'a', 'b')
>>> t1[1:]
(2, 'a', 'b')

2.2.3.5 Adding

>>> t1 = (1, 2, 'a', 'b')
>>> t2 = (3, 4)
>>> t3 = t1 + t2
>>> t3
(1, 2, 'a', 'b', 3, 4)

2.2.3.6 Multiplication

>>> t2 = (3, 4)
>>> t3 = t2 * 3
>>> t3
(3, 4, 3, 4, 3, 4)

2.2.3.7 Length

>>> t1 = (1, 2, 'a', 'b')
>>> len(t1)
4

Tuples don't have built-in functions such as "sort, insert, remove, and pop"
because element values cannot be changed.

2.2.4 Dictionary data type

Anyone can represent the information that person has in the same way as "name" = "Hong Gil-dong", "birthday" = "months and days", etc.

In Python, there is a "Dictionary data type" that can represent this correspondence.

2.2.4.1 What is Dictionary data type

Just as the words "people" and "baseball" correspond to the words "사람" and "야구," in korean
the dictionary is a data type that has Key and Value as a pair.
For example, if Key is "baseball," Value will be "야구."

The dictionary does not obtain sequential element values sequentially like "lists or tuples", but obtains the value through the Key.

This is the biggest feature of the dictionary.

It is not that all the contents of the dictionary are searched sequentially to find the meaning of the word baseball, but only where the word baseball exists.

simple example

>>> dic = {'name': 'pey', 'phone': '010-9999-1234', 'birth': '1118'} #ex.1

>>> a = {1: 'hi'}                                                    #ex.2

>>> a = {'a': [1, 2, 3]}                                             #ex.3, value can be List

2.2.4.2 Add/delete dictionary pairs

To add dictionary pairs

>>> a = {1: 'a'}
>>> a[2] = 'b'
>>> a
{1: 'a', 2: 'b'}

>>> a['name'] = 'pey'
>>> a
{1: 'a', 2: 'b', 'name': 'pey'}

>>> a[3] = [1, 2, 3]
>>> a
{1: 'a', 2: 'b', 'name': 'pey', 3: [1, 2, 3]}

2.2.4.3 How to use the dictionary

Get Value with Key in the Dictionary

>>> grade = {'pey': 10, 'julliet': 99}
>>> grade['pey']
10
>>> grade['julliet']
99
>>> a = {1:'a', 2:'b'}
>>> a[1]
'a'
>>> a[2]
'b'

>>> a = {'a': 1, 'b': 2}
>>> a['a']
1
>>> a['b']
2
>>> dic = {'name':'pey', 'phone':'010-9999-1234', 'birth': '1118'}
>>> dic['name']
'pey'
>>> dic['phone']
'010-9999-1234'
>>> dic['birth']
'1118'
  • Precautions for creating Dictionaries(1)

Noted that in the dictionary, a key is a unique value, so if you set a duplicate key value, all but one will be ignored. As shown in the following example, if there are two identical keys, the 1: 'a' pair will be ignored.

>>> a = {1:'a', 1:'b'}
>>> a
{1: 'b'}
  • Precautions for creating Dictionaries(2)

Another thing to be aware of is that a list cannot be written in a key. However, a tuple can be used as a key. Whether or not a key in a dictionary can be used as a key depends on whether the key is a mutable value or an immutable value.
A list cannot be used as a key because its "value can change".
If the list is set to a key as in the following example, an error occurs that the list cannot be used as a key value.

>> a = {[1,2] : 'hi'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

However, Value can be any value, whether it is a value that changes or does not change.

2.2.4.4 Dictionary functions

  • Key list
>>> a = {'name': 'pey', 'phone': '010-9999-1234', 'birth': '1118'}
>>> a.keys()  => change to"list(a.keys())"
dict_keys(['name', 'phone', 'birth'])

a.keys() returns the dict_keys object by collecting only the keys of dictionary a.

There is little difference from using the list, but "append, insert, pop, remove, and sort functions unique to the list" cannot be performed.

>>> for k in a.keys():
...    print(k)
...
name
phone
birth # just for example
  • Convert dict_keys object to list
>>> list(a.keys())
['name', 'phone', 'birth']
  • Make Value list
>>> a.values()
dict_values(['pey', '010-9999-1234', '1118'])
  • Get Key, Value pairs
>>> a.items()
dict_items([('name', 'pey'), ('phone', '010-9999-1234'), ('birth', '1118')])
  • Delete "Key: Value pair" - clear
>>> a.clear()
>>> a
{}
  • Get Value with Key - get
>>> a = {'name': 'pey', 'phone': '010-9999-1234', 'birth': '1118'}
>>> a.get('name')
'pey'
>>> a.get('phone')
'010-9999-1234'
  • Investigate if the key is in the dictionary - in
>>> a = {'name':'pey', 'phone':'010-9999-1234', 'birth': '1118'}
>>> 'name' in a
True
>>> 'email' in a
False

The string 'name' is one of the keys in the a dictionary. Therefore, calling 'name' in a returns true. Conversely, 'email' returns false because it is a key that does not exist in the a dictionary.

2.2.5 Set data type

2.2.5.1 What is Set data type

"Set" is a data type created to facilitate the processing of what is associated with "Set".

2.2.5.2 How to make Set (with "set" keyword)

>>> s1 = set([1, 2, 3])
>>> s1
{1, 2, 3}
>>> s2 = set("Hello")
>>> s2
{'e', 'H', 'l', 'o'}
  • Two Features of Set:
  1. Do not allow duplication.
  2. Unordered.

Lists and tuples can obtain element values through indexing because they are ordered, but set data types are unordered and cannot obtain element values through indexing. This is similar to the dictionary. The dictionary is also an unordered data type, so indexing is not supported.

2.2.5.3 Obtain Intersection, Sum of set, Difference of set

The really useful use of Set data types is to find intersection, sum, and difference.

Make values from 1 to 6 for s1 and values from 4 to 9 for s2.

>>> s1 = set([1, 2, 3, 4, 5, 6])
>>> s2 = set([4, 5, 6, 7, 8, 9])
  • Intersection
>>> s1 & s2
{4, 5, 6}

>>> s1.intersection(s2) #do it with this, same
{4, 5, 6}
  • Sum
>>> s1 | s2
{1, 2, 3, 4, 5, 6, 7, 8, 9}

>>> s1.union(s2)
{1, 2, 3, 4, 5, 6, 7, 8, 9}
  • Difference
>>> s1 - s2
{1, 2, 3}
>>> s2 - s1
{8, 9, 7}

>>> s1.difference(s2)
{1, 2, 3}
>>> s2.difference(s1)
{8, 9, 7}

2.2.5.4 Set data type function

  • add
>>> s1 = set([1, 2, 3])
>>> s1.add(4)
>>> s1
{1, 2, 3, 4}

  • update
>>> s1 = set([1, 2, 3])
>>> s1.update([4, 5, 6])
>>> s1
{1, 2, 3, 4, 5, 6}
  • remove
>>> s1 = set([1, 2, 3])
>>> s1.remove(2)
>>> s1
{1, 3}

2.2.6 Bool data type

Bool data type is a data type that represents true and false.
The Bool data type can only have two values.

  • TRUE
  • False

2.2.6.1 How to use?

>>> a = True
>>> b = False


>>> type(a)  # for check data type.
<class 'bool'>
>>> type(b)
<class 'bool'>

Bool type is used as return value for conditional statements

>>> 1 == 1
True

>>> 2 > 1
True

>>> 2 < 1
False

2.2.6.2 Data type truth and false

아 ㅁ로마ㅓ라ㅓㅁ

2.2.6.3 Bool calculation

>>> bool('python')
True


>>> bool('')
False

>>> bool([1, 2, 3])
True
>>> bool([])
False
>>> bool(0)
False
>>> bool(3)
True

2.2.7 Variable

>>> a = 1
>>> b = "python"
>>> c = [1, 2, 3]
a = [1, 2, 3]

If a = [1, 2, 3] as in the above code, list data (object) with [1, 2, 3] values is automatically generated in memory, and variable a points to the address of the memory where the [1, 2, 3] list is stored.

  • Address of memory indicated by variable a
>>> a = [1, 2, 3]
>>> id(a)
4303029896

2.2.7.1 copy Variable


>>> a = [1, 2, 3]
>>> b = a

>>> id(a)
4303029896
>>> id(b)
4303029896

>>> a is b  # a is same as b?
True

>>> a[1] = 4
>>> a
[1, 4, 3]
>>> b
[1, 4, 3]

2.2.7.1 copy Variable (1) [:]

>>> a = [1, 2, 3]
>>> b = a[:]
>>> a[1] = 4
>>> a
[1, 4, 3]
>>> b
[1, 2, 3]

2.2.7.1 copy Variable (2) copy module


>>> from copy import copy
>>> a = [1, 2, 3]
>>> b = copy(a)

>>> b is a
False   # Value copied but not the same object

2.2.7.1 Many ways to create variables

>>> a, b = ('python', 'life') # substitute values for tuple a and b as follows.

>>> (a, b) = 'python', 'life' # same above

>>> [a, b] = ['python', 'life'] # list var

>>> a = b = 'python'      # Substitute the same value for multi variables
>>> a = 3
>>> b = 5
>>> a, b = b, a   # simple way to change two Var value
>>> a
5
>>> b
3

2.3 test

Data type is the basis of Python, so it's better to keep it in mind

0개의 댓글