W3school_pythontutorial(1)
W3school에서 python 내실 다지기 목록
- W3school_pythontutorial(1) Syntax ~ Strings
- W3school_pythontutorial(2)-String_Methods
- W3school_pythontutorial(3)-Lists
- W3school_pythontutorial(4) Booleans ~ Arrays
- W3school_pythontutorial(5)-Tuples
W3school_pythontutorial(1)
내실 다지기 : w3school 사이트에서 python tutorial을 처음부터 끝까지 하는 목표로 시작하는 포스팅으로 제공해주는 목차 순서대로 진행한다. 간단한 내용은 제공해준 예제만 실행해본다. 활용해볼 예제는 추가로 간단한 예제를 만들어 실행하는 코드까지 작성하며 내실을 다진다.
- 주제
Introduction
Getting Started
print("Hello, World")
Hello, World
Syntax
# indentation 들여쓰기
if 5 > 2:
print("Five is greater than two!")
Five is greater than two!
x = 5
y = "Hello, World!"
Comments
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Hello, World!
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Hello, World!
Variables
x = 5
y = "John"
print(x)
print(y)
5
John
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Sally
#casting
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))
print(type(y))
<class 'int'>
<class 'str'>
x = "John"
# is the same as
x = 'John'
a = 4
A = "Sally"
#A will not overwrite a
Variable Names
-
다중 단어에 대한 팁 3가지
- Camel Case
myVariableName = "John"
- Pascal Case
MyVariableName = "John"
- Snake Case
my_variable_name = "John"
- Camel Case
Assign Multiple Values
# 여러 변수에 여러 값
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Orange
Banana
Cherry
# 여러 변수에 하나의 값
x = y = z = "Orange"
print(x)
print(y)
print(z)
Orange
Orange
Orange
# 집합 풀기
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
apple
banana
cherry
Output Variables
x = "Python is awesome"
print(x)
Python is awesome
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Python is awesome
# 텍스트 합
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Python is awesome
# 숫자 합(텍스트, 숫자 혼합은 안됨)
x = 5
y = 10
print(x + y)
15
Global Variables
x = "awesome" # 전역 변수
def myfunc():
print("Python is " + x)
myfunc()
Python is awesome
x = "awesome" # 전역변수
def myfunc():
x = "fantastic" # 지역변수
print("Python is " + x)
myfunc()
print("Python is " + x)
Python is fantastic
Python is awesome
# 함수 내에서 전역변수 생성
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Python is fantastic
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Python is fantastic
Variable Exercises
# 1
carname = "Volve"
# 2
x=50
# 3
x=5
y=10
print(x+y)
15
# 4
x = 5
y = 10
z = x + y
print(z)
15
# 5 변수명 수정
# 2my-first_name = "John"
myfirst_name = "John"
# 6
x = y = z = "Orange"
# 7
def myfunc():
global x
x = "fantastic"
myfunc()
Data Types
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
None Type : NoneType
x = 5
print(type(x))
<class 'int'>
- Example Data Type
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
x = None # NoneType
Numbers
int
float
complex
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))
<class 'int'>
<class 'float'>
<class 'complex'>
# int
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
<class 'int'>
<class 'int'>
<class 'int'>
# float
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
<class 'float'>
<class 'float'>
<class 'float'>
# E 지수
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
<class 'float'>
<class 'float'>
<class 'float'>
# complex
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
<class 'complex'>
<class 'complex'>
<class 'complex'>
### type conversion
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)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
1.0
2
(1+0j)
<class 'float'>
<class 'int'>
<class 'complex'>
Random Number
import random
print(random.randrange(1,10))
7
Casting
Python Casting = 형변환
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
print(x,y,z)
1 2 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
print(x,y,z,w)
1.0 2.8 3.0 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'
print(x,y,z)
s1 2 3.0
Strings
print("Hello")
print('Hello')
Hello
Hello
a = "Hello"
print(a)
Hello
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
# string array
a = "Hello, World!"
print(a[1])
e
# looping Through a String
for x in "banana":
print(x)
b
a
n
a
n
a
# string length
a = "Hello, World!"
print(len(a))
13
# check string
txt = "The best things in life are free!"
print("free" in txt)
True
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
Yes, 'free' is present.
# check if not
txt = "The best things in life are free!"
print("expensive" not in txt)
True
txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
No, 'expensive' is NOT present.
Slicing Strings
b = "Hello, World!"
print(b[2:5])
llo
b = "Hello, World!"
print(b[:5])
Hello
b = "Hello, World!"
print(b[2:])
llo, World!
b = "Hello, World!"
print(b[-5:-2])
orl
Modify Strings
# upper case
a = "Hello, World!"
print(a.upper())
HELLO, WORLD!
# lower case
a = "Hello, World!"
print(a.lower())
hello, world!
# Remove Whitespace
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
Hello, World!
# Replace String
a = "Hello, World!"
print(a.replace("H", "J"))
Jello, World!
# split string
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
['Hello', ' World!']
String Concatenation
a = "Hello"
b = "World"
c = a + b
print(c)
HelloWorld
a = "Hello"
b = "World"
c = a + " " + b
print(c)
Hello World
Format - Strings
개인적으로 python3 부터 String format 부분은 f-string을 사용하여 하는게 가독성도 좋고 이해하기 좋다. “”, ‘’ 문자열 앞에 f를 붙여주고 문자열 내에 {} 사이에 변수 이름을 적어주면 된다. ( 인덱싱으로도 표시할 수 있다. )
String1 = "가"
String2 = "나"
String3 = "다"
Int1 = 1
Int2 = 2
Int3 = 3
print(f"한국어의 시작은 {String1}, {String2}, {String3} ... , 숫자의 시작은 {Int1}, {Int2}, {Int3} ...")
한국어의 시작은 가, 나, 다 ... , 숫자의 시작은 1, 2, 3 ...
Escape Characters
Code Result
\’ Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value
# " ' 를 문자열 안에 포함시키는 방법
txt = "We are the so-called \"Vikings\" from the north."
print(txt)
We are the so-called "Vikings" from the north.
String Methods
Python - String Methods 내실 다지기 이므로 모든 함수를 실행해본다.
- 함수가 많아 W3school_pythontutorial(2)-String_Methods 에서 다룬다.
String Exercises
Python - String Exercises 매우 간단한 문제로 함수를 아는지 정도이므로 한번 풀어보는 것도 함수 용어 익히는 정도로 좋다.