Programming/Python
[Python/Basic] 기본구문 (주석,변수,랜덤함수,타입변환,String,Boolean,연산자)
hoojiv
2021. 12. 28. 14:12
728x90
주석
# 한줄 주석
"""
여러줄
주석
"""
변수
# 타입변환
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
# 변수타입확인
x = 5
y = "John"
print(type(x)) # <class 'int'>
print(type(y)) # <class 'str'>
# 값할당
x = y = z = "Orange"
print(x) # Orange
print(y) # Orange
print(z) # Orange
# 여러값할당
x, y, z = "Orange", "Banana", "Cherry"
print(x) # Orange
print(y) # Banana
print(z) # Cherry
# 리스트할당
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x) # apple
print(y) # banana
print(z) # cherry
Text Type | str | print("Hello World") | Hello World |
Numeric Type | int | print(20) | 20 |
float | print(20.5) print(35e3) |
20.5 35000.0 |
|
complex | print(3+5j) | (3+5j) | |
Sequence Type | list | print(["apple", "banana", "cherry"]) | ['apple', 'banana', 'cherry'] |
tuple | print(("apple", "banana", "cherry")) | ('apple', 'banana', 'cherry') | |
range | print(range(6)) | range(0, 6) | |
Mapping Type | dict | print({"name" : "John", "age" : 36}) | {'name': 'John', 'age': 36} |
Set Type | set | print({"apple", "banana", "cherry"}) | {'cherry', 'banana', 'apple'} |
frozenset | print(frozenset({"apple", "banana", "cherry"})) | frozenset({'apple', 'cherry', 'banana'}) | |
Boolean Type | bool | print(True) | True |
Binary Type | bytes | print(b"Hello") | b'Hello' |
bytearray | print(bytearray(5)) | bytearray(b'\x00\x00\x00\x00\x00') | |
memoryview | print(memoryview(bytes(5))) | <memory at 0x00A78FA0> |
랜덤함수
import random
print(random.randrange(1, 10))
타입변환
# int로 변환
x = int(1) # 1
y = int(2.8) # 2
z = int("3") # 3
# float로 변환
x = float(1) # 1.0
y = float(2.8) # 2.8
z = float("3") # 3.0
w = float("4.2")# 4.2
# string으로 변환
x = str("s1") # s1
y = str(2) # 2
z = str(3.0) # 3.0
String
# 다중문자열
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
# 문자열 배열
a = "Hello, World!"
print(a[0]) # H
print(a[1]) # e
print(a[2]) # l
print(a[3]) # l
print(a[4]) # o
# 문자열 for문
for x in "banana":
print(x)
b
a
n
a
n
a
# 문자열 길이
a = "Hello, World!"
print(len(a)) #13
# 문자열 체크
# 특정 문자열의 포함여부를 확인할 수 있다.
txt = "The best things in life are free!"
if "life" in txt:
print("Yes, 'life' is present.")
else:
print("No, 'life' is not present")
# 문자열 자르기
b = "Hello, World!"
print(b[2:5]) # llo 문자열2~5번째
print(b[:2]) # He 문자열~2번째
print(b[4:]) # o, World! 문자열4~번째
print(b[-5:-2]) # orl 문자열 뒤에서 -5~-2번째(뒤는 0이 아닌 -1부터 시작)
# 문자열 수정
a = " Hello, World! "
print(a.upper()) # HELLO, WORLD! 대문자로 변경
print(a.lower()) # hello, world! 소문자로 변경
print(a.strip()) # Hello, World! 문자열 앞뒤 공백제거
print(a.replace("Hello", "Hi")) # Hi, World! 문자열 치환
print(a.split(",")) # [' Hello', ' World! '] 문자열 분리
# 문자열 Format
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price)) # I want to pay 49.95 dollars for 3 pieces of item 567
문자열 함수
https://www.w3schools.com/python/python_strings_methods.asp
Python - String Methods
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
Boolean
# bool() - 값여부를 체크한다
# 모든 데이터 타입에 대해 True를 리턴하지만
# 빈값, (), [], "", 0, None, False와 같은 값에는 False를 리턴한다.
print(bool("abc")) # True
print(bool(123)) # True
print(bool(["apple", "cherry", "banana"])) # True
print(bool(0)) # False
print(bool("")) # False
print(bool(())) # False
# isinstance() - 변수가 특정 타입인지 체크한다.
x = 200
print(isinstance(x, int)) # True
print(isinstance(x, str)) # False
연산자
# 지수연산
2 ** 5 # 32(2*2*2*2*2)
# 절사연산
15 // 2 # 7(15/2 = 7.5 결과에서 .5를 버림)
# in, not in : 리스트에서의 포함여부 체크
x = ["apple", "banana"]
print("apple" in x) # True
print("orange" in x) # False
print("orange" not in x) # True
* w3schools.com에서 공부하면서 모르는 내용에 대해 작성함
728x90
LIST