본문 바로가기

Programming/Python

인프런 파이썬 공부2

#문자열포맷
#방법1
print("나는 %d살입니다." %20)
print("나는 %s을 좋아해요" %"파이썬")
print("Apple은 %c로 시작해요" % "A")

print("나는 %s색과 %s색을 좋아해요" %("파란", "빨간"))

#방법2
print("나는 {}살입니다." .format(20))
print("나는 {}색과  {}색을 좋아해요". format("파란", "빨간"))
print("나는 {0}색과 {1}색을 좋아해요".format("파란", "빨간"))
print("나는 {1}색과 {0}색을 좋아해요".format("파란", "빨간"))

#방법3
print("나는 {age}살이며, {color}색을 좋아해요".format(age=20, color="빨간"))

#방법4
age=20
color="빨간"
print(f"나는 {age}살이며, {color}색을 좋아해요")

ㅁ 

 

#탈출문자

#\n : 줄바꿈

print("백문이 불여일견\n 백견이 불여일타")

#\" \' : 문장 내에서 따옴표
print("저는 '나도코딩'입니다. ")
print('저는 "나도코딩"입니다. ')
print("저는 \"나도코딩\" 입니다.")

#\\ : 문장 내에서 \
print("c:\\useer\\")

#\r : 커서를 맨 앞으로 이동
print("Red Apple\rPine")

#\b : 백스페이스(한 글자 삭제)
print("Redd\b Apple")

#\t : 탭
print("Red\tApple")

ㅋ퀴즈

url = "http://naver.com"
my_str=url.replace("http://", "")
#print(my_str)
my_str=my_str[:my_str.index(".")] #my_str[0:5] -> 0~5직전까지 (0,1,2,3,4)
password = my_str[:3] + str(len(my_str)) + str(my_str.count("e")) + "!"
print("{0}의 비밀번호는 {1}입니다." .format(url, password))

리스트

#리스트[]
#지하철 칸별로 10, 20, 30명
subway=[20,30,10]
print(subway)

subway=["유재석", "하하", "조세호"]
print(subway)

#조세호는 몇번째에 타고 있나요
print(subway.index("조세호"))

#노홍철 다음 정류장에서 다음 칸에 탐
subway.append("노홍철")
print(subway)

#정형돈을 유재석 / 하하 사이에 태우기
subway.insert(1, "정형돈")
print(subway)

#지하철에 있는 사람을 한 명씩 뒤에서 꺼냄
print(subway.pop())
print(subway)

print(subway.pop())
print(subway)

print(subway.pop())
print(subway)

#같은 이름의 사람이 몇 명 있는지 확인
subway.append("유재석")
print(subway.count("유재석"))

#리스트 정렬하기
num_list=[5,3,1,6]
num_list.sort()
print(num_list)

#순서 뒤집기 가능
num_list.reverse()
print(num_list)

#모두지우기
num_list.clear()
print(num_list)

#다양한 자료형 함께 사용
mix_list=["조세호", 20, True]
print(mix_list)

#리스트 확장
num_list.extend(mix_list)
print(num_list)

#사전
cabinet={3:"유재석", 100:"김태호"}
print(cabinet[3])
print(cabinet[100])
print(cabinet.get(3))
# print(cabinet[5]) #정의 안되어 있어서 오류 나면서 종료됨
# print("jo") #위에 오류료 출력 안됨

# print(cabinet.get(5)) #none이라고 출력됨.
# print(cabinet.get(5, "사용 가능"))

cabinet={"A-3" : "유재석", "B-90": "김태호"}
print(cabinet["A-3"])
print(cabinet["B-90"])

#새손님
cabinet["A-3"] = "김종국"
cabinet["C-20"]="조세호"
print(cabinet)

#간 손님
del cabinet["A-3"]
print(cabinet)

#key들만 출력
print(cabinet.keys())

#value들만 출력
print(cabinet.values())

#key, value 쌍으로 출력
print(cabinet.items())

#목욕탕 폐점
cabinet.clear()
print(cabinet)

 

#튜플 변경 x

menu=("도까스", "치즈까스")
print(menu[0])
print(menu[1])

#menu.add("생선까스") 튜플 추가같은 변경 안됨

(name, age, hobby)=("김종국", 20 ,"코딩")
print(name, age, hobby)
#집합(set)
#중복 안됨, 순서 없음
my_set={1,2,3,3,3}
print(my_set)

java={"유재석", "김태호", "양세형"}
python=set(["유재석", "박명수"])

#교집합 (java와 python을 모두 할 수 있는 개발자)
print(java & python)
print(java.intersection(python))

#합집합 (java할 수 있거나 python 할 수 있는 개발자)
print(java | python)
print(java.union(python))

#차집합 (java 할 수 있지만 python은 할 줄 모르는 개발자)
print(java-python)
print(java.difference(python))

#python 할 줄 아는 사람이 늘어남
python.add("김태호")
print(python)

#java 잊음
java.remove("김태호")
print(java)

 

#자료구조 변경
#커피숍
menu={"커피", "우유", "주스"}
print(menu, type(menu)) # {}

meny=list(menu)
print(menu,type(menu)) #[]

menu=tuple(menu)
print(menu, type(menu)) #()

menu=set(menu)
print(menu, type(menu)) #{}
# from random import *
# lst=[1,2,3,4,5]
# print(lst)
# shuffle(lst) #무작위로 순서 바꿈
# print(lst)
# print(sample(lst, 1)) #1개를 뽑겟다

from random import *
user=range(1, 21)
# print(type(user))
user=list(user)
# print(type(user))

print(user)
shuffle(user)
print(user)

winners=sample(user, 4) #4명 중에서 1명은 치킨, 3명은 커피

print("당첨자 발표")
print("치킨 당첨자 : {0}".format(winners[0]))
print("커피 당첨자 : {0}".format(winners[1:]))
print("축하합니당")

 

 

#if
weather=input("오늘 날씨 어때요? ")
if weather =='비' or weather=='눈':
	print("우산을 챙기세요")
elif weather =='미세먼지' :
	print("마스크를 챙기세요")
else:
	print("준비물 필요 없어요 ")

temp=int(input("기온은 어때요?"))
if 30 <=temp:
	print("너무 더워요, 나가지 마세요")
elif 10<=temp and temp<30:
	print("괜찮은 날씨에요")
elif 0<=temp < 10:
	print("외투를 챙기세요")
else :
	print("너무 추워요 나가지마세요 ")

 

 

#for
#반복문

# for Warning_no in [0,1,2,3,4] :
# 	print("대기번호 : {0}".format(Warning_no))

# for no in range(1, 6) :  #1~5
# 	print("대기번호 : {0}".format(no))

store =["아이언맨", "토르", "아이엠 그루트"]
for customer in store:
	print("{0}, 커피가 준비되었습니다.".format(customer))

 

 

while

customoer="토르"
index = 5

while index>=1:
	print("{0}, 커피가 준비되었습니다. {1}번 남았어요.".format(customoer, index))
	index-=1
	if index == 0:
		print("커피 폐기되었습니다. ")

customer="아이언맨"
index=1
while True:
		print("{0}, 커피가 준비되었습니다. 호출 {1}회.".format(customer, index))
		index += 1

#조건 맞을 때까지 반복하는 반복문
customer="토르"
person ="Unknown"

while person != customer: 
	print("{0},커피가 준비되었습니다.".format(customer))
	person=input("이름 뭐양?")

 

 

#continue ,break
no_book=[7] #책 안가져옴
absent=[2, 5] #결석
for student in range(1, 11):
	if student in absent:
		continue
	elif student in no_book:
		print("오늘 수업 여기까지. {0}, 교무실로 따라와".format(student))
		break
	print("{0}, 책 읽어봐".format(student))
#한줄 for

students=[1,2,3,4,5]
print(students)
students=[i+100 for i in students]
print(students)

#학생 이름을 길이로 변환
students=["Iron man", "Thor", "I am groot"]
students=[ len(i) for i in students]
print(students)

#학생 이름을 대문자로 변환
students=["Iron man", "Thor", "I am groot"]
students=[i.upper() for i in students]
print(students)

 

 

 

 

from random import *
cnt = 0
for i in range(1, 51): #1~50 50명의 승객 중에서
	time = randrange(5, 51) #시간은 5~50분 소요되는데
	if 5 <= time <= 15: #그중 5~15분이면 cnt증가와 몇번째 손님인지와 시간을 출력
		print("[0] {0}번째 손님 (소요시간 :{1}분".format(i, time))
		cnt +=1
	else : #조건 만족하지 않은 손님.
		print("[] {0}번째 손님 (소요시간:{1})".format(i, time))

print("총 탑승 승객 : {0}분".format(cnt))

 

 

def open_account():
	print("새로운 계좌 생성됨")

def deposit(balance ,money):
	print("입금이 왼료되었습니다. 잔액은 {0}입니다".format(balance+money))
	return balance+money

def withderaw(balance, money):
	if balance >=money:
		print("출금 완료 잔액은 {0}원입니다. ".format(balance-money))
		return balance-money
	else :
		print("출금 실패 잔액 {0} 원입니다.".format(balance))
		return balance

def withderaw_night(balance, money):
	commission=100
	return commission, balance-money-commission #리턴이 두개도 가능하네

balance=0
balance=deposit(balance, 1000)
# balance=withderaw(balance, 2000)
# balance=withderaw(balance, 500)
commission, balance = withderaw_night(balance, 500)
print("수수료 {0}원이며, 잔액은 {1}원입니다.".format(commission, balance))

#입금이 왼료되었습니다. 잔액은 1000입니다
#수수료 100원이며, 잔액은 400원입니다.

 

 

def profile(name, age, main_lang):
	print("이름 : {0} .. 나이 {1} .... 주 사용 언어 {2}".format(name, age, main_lang))

profile("유재석", 20, "파이썬")
profile("김태호", 25, "자바")

def profile(name, age=17, main_lang="자바"): #기본값으로 주기
	print("이름 : {0} .. 나이 {1} .... 주 사용 언어 {2}".format(name, age, main_lang))


profile("김태호") #기본값 줬기 때문에 이름만 입력해도 자동으로 age 와 main_lang나옴

 

 

def profile(name, age, main_lang):
	print(name, age, main_lang)

profile(name="유재석", main_lang="파이썬", age=20)
#순서 바뀌어도 잘 할 수 있음
#지역변수 와 전역변수

gun =10
def checkpoint(soliers) :
	global gun #전역 공간에 있는 gun사용
	gun = gun -soliers
	print("[함수 내] 남은 총 : {0}".format(gun))

def checkpoint_ret(gun, soliers):
	gun=gun-soliers
	print("[함수 내] 남은 총 : {0}".format(gun))
	return gun

print("전체 총 : {0}".format(gun))
gun = checkpoint_ret(gun, 2)
print("남은 총 :{0}".format(gun))

 

 

 

#내가 푼 답
height=175
gender=1

def std_weight(height, gender):
	if gender==1:
		return height*0.01*height*0.01*22
	elif gender==2:
		return height*0.01*height*0.01*21

print("키 {0}cm 남자의 표준 체중은 {1}kg 입니다.".format(height, round(std_weight(height, gender),2)))



소수점 둘째 짜리 까지 나타내고 싶으면 round(~, 2)

# def std_weight(height, gender):
# 	if gender=="남자":
# 		return height*height*22
# 	else:
# 		return height*height*21
# height = 175
# gender="남자"
# weight=std_weight(height/100, gender)
# print("키 {0}cm {1}의 표준 체중은 {2}kg 입니다.".format(height, gender, weight))

#표준 입출력
print("python", "Java", sep=" vs ")
#python vs Java

print("python", "Java", sep=" vs " , end="?")
#문장의 끝 부분을 ?로 바꿔줌.