파이썬 코딩 연습하기
https://www.w3schools.com/python/python_syntax.asp
Python Syntax
Python Syntax Execute Python Syntax As we learned in the previous page, Python syntax can be executed by writing directly in the Command Line: >>> print("Hello, World!") Hello, World! Or by creating a python file on the server, using the .py file extension
www.w3schools.com
파이썬 튜토리얼 -> 코딩 연습
PRINT 연습
1. Hello, world! 출력
print("Hello, world!)
2. 5>2이면 Five is greater than two! 출력
if 5>2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!") <- 에러. 들여쓰기가 필요함
3. 동일한 코드 블록에서 동일한 수의 공백을 사용해야함.
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!") <- 들여쓰기 오류
4. 변수 할당
x = 5
y = "Hello, World!"
5. 주석처리 ( # 이용 )
#This is a comment.
print("Hello, World!")
6. 여러 줄의 주석처리
'''
This is a comment
written in
more that just one line
'''
"""
This is a comment
written in
more that just one line
"""
- python은 ' ' , " " 구분 x
7. 타입 지정
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
print(x)
print(y)
print(z)
- 엄격하게 제한되지는 않는다. int="3"을 해도 에러 x
아래 코드도 같은 결과.
x: str = 3
y: int = 3
z: float = 3
print(x)
print(y)
print(z)
- 하지만 완벽히 문법을 따르는지를 확인하고자 할 때는 "mypy a.py" 사용
cmd창 실행 -> cmd에 notepad a.py입력 -> 노트패드에 no: int = "1" print(no) 입력 후 저장
-> cmd에 python a.py 입력 ( 정상 출력 ) -> cmd에 mypy a.py입력 ( 에러 )
8. 타입 확인
x = 5
y = "John"
print(type(x))
print(type(y))
출력결과
<class 'int'>
<class 'str'>
변수 설정
9. 대소문자 구분 O, ' ' 와 " " 구분 X
x = "John"
# is the same as
x = 'John'
10. 변수명 설정
가능
myvar / my_var / _my_var / myVar / MYVAR / myvar2
불가능
2myvar / my-var / my var
11. 여러 변수에 각각 값 할당하기
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
12. 여러 변수에 같은 값 할당하기
x = y = z = "Orange"
print(x)
print(y)
print(z)
13. 배열로 된 값을 개별 변수에 입력 ( = Unpack )
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
14. 문자열 결합
x = "awesome"
print("Python is " + x)
x = "Python is "
y = "awesome"
z = x + y
print(z)
15. 숫자 변수 연산
x = 5
y = 10
print(x + y)
16. 숫자와 문자는 결합 불가 ( 에러 )
x = 5
y = "John"
print(x + y) # Error
17. global 변수 ( 함수 밖에 있는 변수 )
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Jupyter에서 함수 사용하는 법
1) 주피터에서 txt파일 생성 ( 파일명 = mymodule )
x = 'asome'
def myfunc():
print("Python is " + x)
2) 주피터에서 python파일 생성 ( 함수 불러오기 )
import mymodule
mymodule.myfunc()
함수와 글로벌 변수
18. 함수 이용하기
x = "awesome" # <- global 변수
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
19. 글로벌변수 ( 위치상 )
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
20. 함수 내부에서 글로벌변수 만들기
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
-> fantastic 출력
TYPE
21. 타입 설명
Text Type: | str |
Numeric Types: | int, float, complex |
Sequence Types: | list, tuple, range |
Mapping Type: | dict |
Set Types: | set, frozenset |
Boolean Type: | bool |
Binary Types: | bytes, bytearray, memoryview |
22. 타입 확인
x = 5
print(type(x))
23. 타입 예제
x = "Hello World" | str |
x = 20 | int |
x = 20.5 | float |
x = 1j | complex |
x = ["apple", "banana", "cherry"] | list |
x = ("apple", "banana", "cherry") | tuple |
x = range(6) | range |
x = {"name" : "John", "age" : 36} | dict |
x = {"apple", "banana", "cherry"} | set |
x = frozenset({"apple", "banana", "cherry"}) | frozenset |
x = True | bool |
x = b"Hello" | bytes |
x = bytearray(5) | bytearray |
x = memoryview(bytes(5)) | memoryview |
24. 타입 예제
# Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
x = 1 # int
y = 35656222554887711 # int
z = -3255522 # int
x = 1.10 # Floats
y = 1.0 # Floats
z = -35.59 # Floats
x = 35e3 # Floats
y = 12E4 # Floats
z = -87.7e100 # Floats
x = 3+5j # Complex
y = 5j # Complex
z = -5j # Complex
25. 타입 변환
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
26. Random Number
import random
print(random.randrange(1, 10)) # 1에서 10사이 정수 랜덤 출력
random.seed(10)
print(random.random()) # 0부터 1사이 랜덤 넘버 출력
27. 타입 변경
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
28.
a = "Hello, World!"
print(a[1])
for x in "banana":
print(x)
29. Length
a = "Hello, World!"
print(len(a)) # 13출력
30. in, not in
txt = "The best things in life are free!"
print("free" in txt) # TRUE 출력
txt = "The best things in life are free!"
print("expensive" not in txt) # TRUE 출력
31. 특정 문자 변경
b = "Hello, World!"
print(b[:5]) # Hello 출력
b = "Hello, World!"
print(b[2:]) # llo, World! 출력
b = "Hello, World!"
print(b[2:]) # orl 출력
32. 특정 문자 추출
a = "Hello, World!"
print(a.upper()) # HELLO, WORLD! 출력
a = "Hello, World!"
print(a.lower()) # hello, world 출력
a = " Hello, World! "
print(a.strip()) # Hello, World! 출력
a = "Hello, World!"
print(a.replace("H", "J")) # Jello, World! 출력
a = "Hello, World!"
b = a.split(",")
print(b) # ['Hello', 'World!'] 출력
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age)) # My name is John, and I am 36 출력
age = 36
txt = "My name is John, I am " + age
print(txt) # Error
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
#I want 3 pieces of item 567 for 49.95 dollars. 출력
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 출력
교재 참고
위키독스
온라인 책을 제작 공유하는 플랫폼 서비스
wikidocs.net
33. Escape함수
txt = "We are the so-called "Vikings" from the north." # Error
txt = "We are the so-called \"Vikings\" from the north."
# We are the so-called "Vikings" from the north. 출력
코드설명
코드 | 설명 |
\n | 문자열 안에서 줄을 바꿀 때 사용 |
\t | 문자열 사이에 탭 간격을 줄 때 사용 |
\\ | 문자 \를 그대로 표현할 때 사용 |
\' | 작은따옴표(')를 그대로 표현할 때 사용 |
\" | 큰따옴표(")를 그대로 표현할 때 사용 |
\r | 캐리지 리턴(줄 바꿈 문자, 현재 커서를 가장 앞으로 이동) |
\f | 폼 피드(줄 바꿈 문자, 현재 커서를 다음 줄로 이동) |
\a | 벨 소리(출력할 때 PC 스피커에서 '삑' 소리가 난다) |
\b | 백 스페이스 |
\000 | 널 문자 |
34. Boolean
print(10>9) # True 출력
print(10==9) # False 출력
print(10<9) # False 출력
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a") # b is not greater than a
print(bool("Hello")) # True
print(bool(15)) # True
bool("abc") # True
bool(123) # True
bool(["apple", "cherry", "banana"]) # True
bool(False) # False 출력
bool(None) # False 출력
bool(0) # False 출력
bool("") # False 출력
bool(()) # False 출력
bool([]) # False 출력
bool({}) # False 출력
class myclass():
def __len__(self):
return 0
myobj = myclass()
print(bool(myobj)) # False 출력
'인공지능 > PYTHON' 카테고리의 다른 글
Python - generator (0) | 2021.06.17 |
---|---|
Python 300제 - 분기문 (0) | 2021.06.17 |
atom 설치 (0) | 2021.06.17 |
파이썬 300제 (1) (0) | 2021.06.16 |
Anaconda 다운로드 (0) | 2021.06.16 |