본문 바로가기

컴퓨터 언어/python

Python 1. Python Syntax

python 2버전과 3버전의 차이점

python 2: print "1+1"

python 3: print (1+1)


1. string 문자집합

문자집합으로 " " / ' ' 가 단위

"와 '를 혼용해 쓸 수 없음

 

# -*- coding: utf-8 -*- 

print "Hello"+"선영" #2버전에서는 불가하므로 위처럼 처리

 

2버전에서는 한글과 혼용 불가

SyntaxError: Non-ASCII character '\xec'

https://pante.blog/371

 

 

2. variables  변수

message="Hello"
number=5
print message+str(number) #형변환

 

3. 산수

% : 나머지

//: 몫

**: 승

 

# 효율성을 위한 산수 법칙

money_in_wallet = 40
sandwich_price = 7.50
sales_tax = .08 * sandwich_price

sandwich_price += sales_tax
#sandwich_price=sandwich_price+sales_tax
money_in_wallet -= sandwich_price

a = a+b -> a += b

 

 

4. Numbers

Int : 정수. 

float : 실수를 저장하는 방식

 

# 과학적 표기법

float4 = 1.5e2 #150.0

1.5e2 = 1.5*(10^2)

1.5e-3= 1.5*(10^-3)

 

5. Two Types of Division

 

quotient = 6/2

# 값이 3으로 출력

 

quotient = 7/2

# 값이 3으로나옴. 3.5임에도

앞의 값이 int이므로 규칙에 따라 int로 나온 것

 

이것은 6과 2가 둘 다 int타입이기 때문에 결과값도 int로 출력하는 파이썬 컴파일러의 성질 때문 ,

그래서 강제로 형 변환을 해주어야합니다.

 

quotient1 = 7./2

quotient2 = 7/2.

quotient3 = 7./2.

quotient4= float(7)/2

# 모두  3.5

 

quotient = float(7/2) 이렇게 하면 #3.0 나옴

 

6. Multi-line Strings

“”“라는 string 표기법

address_string = """136 Whowho RdApt 
7Whosville,
WZ 44494""“

과 같이 여러가지 줄에 걸쳐서 표기를 하고 싶을 때에 사용

 

만약에 변수가 없는 상태에서 “”“ 표기법을 사용한다면, 여러가지 줄에 걸친 주석처리가 된다.

“”“
주
석
입
니
다
“”“

 

7. Boolean

True, or false 참이냐 거짓이냐라는 조건을 저장하는 형식

우리는 후에 if, if else 조건이 참이면 문장을 실행하고 아니면 넘어가는 방식에 활용

a = True
b = False

print type(a)	#<type 'bool'>
print int(a)	#1. true를 형변환시키면 1
print int(b)	#2. false를 형변환시키면 2

if (3): #0이면 false고 그 외 모든 수는 true로 받아드리게 된다
	print "asd"	#asd 출력

파이썬에서 True를 int타입으로 바꾸면 1/ False를 인트 타입으로 바꾸면 0

 

 

8. ValueError

파이썬에서는 다른 언어와 달리 변수 뒤에 따라 붙는 숫자를 보고서 형을 결정!

 

a=7 (int)

a=7.(float)

a="7"(string)

 

데이터 타입을 변환하고 싶을 때에는...

age = 13
print "I am " + str(age) + " years old!“

#I am 13 years old!

 

반대로 str을 int로 저장하고 싶을 때에는...

number1 = "100"
number2 = "10"

string_addition = number1 + number2 
#string_addition now has a value of "10010"

int_addition = int(number1) + int(number2)
#int_addition has a value of 110

 

더보기

 product를 선언해서 두 수를 곱하고

 

big_string = "The product was " + proudct의 값으로 str값으로 저장해봅시다.

 

float_1 = 0.25

float_2 = 40.0

 

product = float_1 * float_2

 

big_string = "The product was " + str(product)

 

product = float_1 * float_2

big_string = "The product was " + str(product) 

 

'컴퓨터 언어 > python' 카테고리의 다른 글

파이썬 기초1  (0) 2020.07.15
Python 5: List + Dictinaray + for루프  (0) 2020.07.14
Python 4. 파이썬 함수  (0) 2020.07.14
Python 3. Conditionals ana Control Flow  (0) 2020.07.14
Python 2. String & Console out  (0) 2020.07.14