티스토리 뷰

Python

Python 기초

carrot62 2020. 8. 15. 20:27
  • print("hello world")
  • if
if 5 > 2:
  print("Five is greater than two!")
  • 변수 선언
    • 특별히 타입을 지정해줄 필요가 없다
x = 5
y = "Hello, World!"

print(x)
print(y)

x, y, z = "Orange", "Banana", "Cherry"
#변수 값 할당을 이렇게 할 수도 있다
print(x)
print(y)
print(z)

변수이름 규칙

  • 주석: #
    • 블록 단위로 주석 처리하고 싶다면: """ """
"""
This is a comment
written in
more than just one line
"""
  •  + 연산자
x = "awesome"
print("Python is " + x)
 #출력: Python is awesome
  • Global variables(전역 변수): 함수 밖에 선언된 변수, 함수 밖과 안에서 global scope으로 사용될 수 있다
  • Local variables(지역 변수): 함수 내에 선언 되어, 함수 안에서만 쓰일 수 있는 변수
    • 다만 함수에서 변수를 선언할 때 global 이라는 keyword을 붙이면, 전역 변수로 쓰일 수 있게 된다
  • 함수 선언
x = "awesome"

def myfunc():
  x = "fantastic"
  print("Python is " + x)

myfunc()

print("Python is " + x)
#출력:
"""
Python is fantastic
Python is awesome
"""
  • Python data types: 파이썬에서는 변수를 선언해서 값을 할당해주면 그에 맞은 data type을 알아서 지정한다. Data type을 지정하고 싶다면 다음과 같이 직접 할 수도 있다
x = str("Hello World")

각 data type별 사용 방법

  • type(): 변수의 타입을 리턴해주는 함수

Python Numbers

  • int
  • float

Float can also be scientific numbers with an "e" to indicate the power of 10.

위 변수 x의 출력 값

  • complex
  • type conversion
    • complex 타입은 다른 타입으로 변환할 수 없다
  • random(): import 해서 사용할 수 있는 built-in module 이다
import random

print(random.randrange(1, 10))

Casting

a = int(2.8) # will be 2
b = int("3") # will be 3
c = float(1) # will be 1.0
d = str(2)   # will be '2'

Strings are arrays

[  ] 괄호를 이용해 인덱스 별로 string에 접근할 수 있다(참고로 인덱스는 0번째 자리부터 시작한다)

Slicing

b = "Hello, World!"
print(b[2:5])
# 출력: llo

음수를 사용하면 문자열 끝에서 세기 시작한다 (예. b[-5:-2])

  • len()
  • strip()
  • lower()
        사용) 문자열 변수 a가 있다고 하면, a.lower()
  • upper()
  • replace()
  • split()
        사용 예) a.split(",")  #split하고 싶은 문자를 정의해주기
  • in 또는 not in
txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x) 

#출력: True
  • 문자열과 숫자를 합치고 싶다면ㅣ format()을 사용하면 된다
    • format으로 정의한 변수가 들어갈 자리에 {} 괄호(which will act as a placeholder)를 넣어주면 된다

사용 방법:

#이렇게 하면 에러 난다
#TypeError: can only concatenate str (not "int") to str
age = 36
txt = "My name is John, I am " + age
print(txt)

format을 사용해서 하면:

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

여러개의 placeholder를 사용할 경우에 index로 정의해줄 수도 있다(생략도 가능)

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
  • escape character \

  • Built in string methods
    출처: W3Schools

etc...

https://www.w3schools.com/python/python_strings.asp

 

Python Strings

Python Strings String Literals String literals in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is the same as "hello". You can display a string literal with the print() function: Assign String to a Variable Ass

www.w3schools.com

Python Booleans

  • bool()

  • isinstance() : 어느 특정 데이터 타입인지 호가인하기 위해 사용하는 하는 함수

연산자

  • **: ~제곱
        사용 예) print( 2 ** 5)  #결과 32
  • // : rounds to the nearest whole number (그냥 / 로 하면 첫번째 소숫점 자리까지 나타내서 보여준다)

논리 연산자

  • and
  • or
  • not
        C언어에서는 !를 사용했다면, 파이썬에는 not 문자를 그대로 사용하는 것 같다

Identity operators

  • is
  • is not
x = ["apple", "banana"]

print("pineapple" not in x)

# returns True because a sequence with the value "pineapple" is not in the list

이진 연산자

 

참고: https://www.w3schools.com/python/python_variables.asp

 

Python Variables

Python Variables Creating Variables Variables are containers for storing data values. Unlike other programming languages, Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Variables do not need

www.w3schools.com

 

질문:

  1. 파이썬에서는 데이터 타입을 알아서 지정해주는데, 직접 데이터 타입을 지정할 수 있는 거는 언제 사용할 수 있는건가요(Casting)? 굳이 왜 있을까요?
  2. Complex 타입은 언제 쓰이는 데이터 타입일까요?
  3. 다음 연산자들의 의미는?

'Python' 카테고리의 다른 글

Python Collections(Arrays)  (0) 2020.08.18
파이썬 설치(IDLE 설치하는 방법)  (0) 2020.08.15