
a = 123
a= -123
a = 0
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
a = 0o12
b = 0o34
a = 0x1A
b = 0xEF
>>> 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
>>> 7 // 4
1
+=, -=, *=, /=, //=, %=, **=
>>> a =2
>>> a += 1 # same as " a = a + 1 "
>>> print(a)
3
"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
# 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'
>>> "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 % (문자 % 자체)
>>> "%10s" % "hi"
' hi'
>>> "%-10sjane." % 'hi'
'hi jane.'
>>> "%0.4f" % 3.42134234
'3.4213'
>>> "%10.4f" % 3.42134234
' 3.4213'
>>> "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']
>>> 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'
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a + b
[1, 2, 3, 4, 5, 6]
>>> a = [1, 2, 3]
>>> a * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> a = [1, 2, 3]
>>> len(a)
3
>>> a = [1, 2, 3]
>>> a[2] = 4
>>> a
[1, 2, 4]
>>> a = [1, 2, 3]
>>> del a[1]
>>> a
[1, 3]
>>> a = [1, 2, 3]
>>> a.append(4)
>>> a
[1, 2, 3, 4]
>>> a.append([5, 6])
>>> a
[1, 2, 3, 4, [5, 6]]
>>> a = [1, 4, 3, 2]
>>> a.sort()
>>> a
[1, 2, 3, 4]
>>> a = ['a', 'c', 'b']
>>> a.sort()
>>> a
['a', 'b', 'c']
>>> a = ['a', 'c', 'b']
>>> a.reverse()
>>> a
['b', 'c', 'a']
>>> 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
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]
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]
>>> a = [1, 2, 3]
>>> a.pop()
3
>>> a
[1, 2]
>>> a = [1, 2, 3]
>>> a.pop(1)
2
>>> a
[1, 3]
examines how many x are in the list and returns the number of x
>>> a = [1, 2, 3, 1]
>>> a.count(1)
2
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]
"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"
# 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
"Tuple" is exactly the same as "List" except that it cannot change the element values
>>> t1 = (1, 2, 'a', 'b')
>>> t1[0]
1
>>> t1[3]
'b'
>>> t1 = (1, 2, 'a', 'b')
>>> t1[1:]
(2, 'a', 'b')
>>> t1 = (1, 2, 'a', 'b')
>>> t2 = (3, 4)
>>> t3 = t1 + t2
>>> t3
(1, 2, 'a', 'b', 3, 4)
>>> t2 = (3, 4)
>>> t3 = t2 * 3
>>> t3
(3, 4, 3, 4, 3, 4)
>>> 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.
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.
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
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]}
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'
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'}
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.
>>> 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
>>> list(a.keys())
['name', 'phone', 'birth']
>>> a.values()
dict_values(['pey', '010-9999-1234', '1118'])
>>> a.items()
dict_items([('name', 'pey'), ('phone', '010-9999-1234'), ('birth', '1118')])
>>> a.clear()
>>> a
{}
>>> a = {'name': 'pey', 'phone': '010-9999-1234', 'birth': '1118'}
>>> a.get('name')
'pey'
>>> a.get('phone')
'010-9999-1234'
>>> 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.
"Set" is a data type created to facilitate the processing of what is associated with "Set".
>>> s1 = set([1, 2, 3])
>>> s1
{1, 2, 3}
>>> s2 = set("Hello")
>>> s2
{'e', 'H', 'l', 'o'}
- Two Features of Set:
- Do not allow duplication.
- 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.
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])
>>> s1 & s2
{4, 5, 6}
>>> s1.intersection(s2) #do it with this, same
{4, 5, 6}
>>> s1 | s2
{1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> s1.union(s2)
{1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> s1 - s2
{1, 2, 3}
>>> s2 - s1
{8, 9, 7}
>>> s1.difference(s2)
{1, 2, 3}
>>> s2.difference(s1)
{8, 9, 7}
>>> s1 = set([1, 2, 3])
>>> s1.add(4)
>>> s1
{1, 2, 3, 4}
>>> s1 = set([1, 2, 3])
>>> s1.update([4, 5, 6])
>>> s1
{1, 2, 3, 4, 5, 6}
>>> s1 = set([1, 2, 3])
>>> s1.remove(2)
>>> s1
{1, 3}
Bool data type is a data type that represents true and false.
The Bool data type can only have two values.
>>> 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
아 ㅁ로마ㅓ라ㅓㅁ
>>> bool('python')
True
>>> bool('')
False
>>> bool([1, 2, 3])
True
>>> bool([])
False
>>> bool(0)
False
>>> bool(3)
True
>>> 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.
>>> a = [1, 2, 3]
>>> id(a)
4303029896
>>> 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]
>>> a = [1, 2, 3]
>>> b = a[:]
>>> a[1] = 4
>>> a
[1, 4, 3]
>>> b
[1, 2, 3]
>>> from copy import copy
>>> a = [1, 2, 3]
>>> b = copy(a)
>>> b is a
False # Value copied but not the same object
>>> 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
Data type is the basis of Python, so it's better to keep it in mind