상세 컨텐츠

본문 제목

실습으로 익히는 파이썬 기본문법 pt.1

CODING/Python

by 뚜뚜 DDUDDU 2022. 5. 27. 20:18

본문

파이썬 기초문법 - 멋사강의

import random
import time

for x in range(30): //반복문
while True: // 무한반복
print(random.choice(["감자","밀떡","후추"]))
print("이 문장도 반복되나?")
print("이 문장도 반복되나?")
// 들여쓰기 여부에 따라 for문에 포함되는지 안되는지 결정
파이썬에선 띄어쓰기 강력하게 체크함(몇칸인진 중요X 보통2칸)
time.sleep(1) // 1초간격으로 쉬겠다.
break // 반복을 정지시킨다.

//이름짓기
lunch = random.choice(["된장찌갸","김치찌개"])
lunch = "냉장고" // 변수선언

information = {"고향":"수원","취미":"영화관람"} //딕셔너리
print(information.get("취미")) //취미를 얻어오는 코드

information["특기"] = "피아노" // 배열에 키/값 추가
information["사는곳"] = "서울" // 배열에 키/값 추가
del information["좋아하는 음식"] // 배열에 키/값 제거
del information["좋아하는 음식"] // 정보묶음의 개수(length)
information.clear() // 객체내용 전체삭제

배열관련 메소드
foods.append("김밥") // 배열에 더하는 것
del foods[1] // 배열에 빼는 것

foods = ["된장찌개", "피자", "제육볶음"]
for x in range(3):
print(foods[x])

// 위와 동일 --> foods 전체를 print 가능(객체도)
for x in foods:
print(x)

information = {"고향":"수원", "취미":"영화관람", "좋아하는 음식":"국수"}
for x, y in information.items():
print(x)
print(y)
// x는 키, y는 값을 지정함

// 배열내 데이터 중복여부 체크 --> 집합개념을 이용
// 순서가 없으며, 중복은 없음
foods = ["된장찌개", "피자", "제육볶음"]
foods_set1 = set(foods) //집합 정의
foods_set2 = set(["된장찌개", "피자", "제육볶음"]) //집합 정의

menu1 = set(["된장찌개", "피자", "제육볶음"])
menu2 = set(["된장찌개", "떡국", "김밥"])
menu3 = menu1 | menu2 //합집합
menu3 = menu1 & menu2 //교집합
menu3 = menu1 - menu2 //차집합
print(menu3)

import random

food = random.choice(["된장찌개","피자","제육볶음"])

if(food == "제육볶음"):
print("곱배기 주세요")
else:
print("그냥 주세요")
print("종료")

/////////////////////////////////////////////////////////
후에 터미널에서
python codelion.py --> 불러오기

////
실습
////

lunch = ["된장찌개", "피자", "제육볶음", "짜장면"]
while True:
print(lunch)
item = input("음식을 추가 해주세요 : ")
if(item == "q"):
break
else:
lunch.append(item)
print(lunch)
set_lunch = set(lunch)

//음식 입력해서 빼기
set_lunch = set(["된장찌개", "피자", "제육볶음", "짜장면"])
item = "짜장면"
print(set_lunch - set([item]))
set_lunch = set_lunch - set([item])
print(set_lunch)

// 실습 본경 정답
import random
import time

lunch = ["된장찌개", "피자", "제육볶음", "짜장면"]

while True:
print(lunch)
item = input("음식을 추가 해주세요 : ")
if(item == "q"):
break
else:
lunch.append(item)
print(lunch)

set_lunch = set(lunch)
while True:
print(set_lunch)
item = input("음식을 삭제해주세요 : ")
if(item == "q"):
break
else:
set_lunch = set_lunch - set([item]) //set([item])은 일단 배열로 바꾼담에 집합으로 바꾼다.

print(set_lunch, "중에서 선택합니다.")
print("5")
time.sleep(1)
print("4")
time.sleep(1)
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
print(random.choice(list(set_lunch))) // 집합상태의 set_lunch를 리스트로 감싸고 이를 다시 random.choice로 하나를 선택한다.

//////////////////////////
함수
def 함수이름():
들여쓰기 필수
들여쓰기 필수

def make_blueberry_smoothie():
print("1. 블루베리 20g을 넣는다.")
print("2. 우유 300ml를 넣는다.")
print("3. 얼음을 넣는다.")
print("4. 믹서기에 간다.")

def make_simple_latte():
print("1. 커피를 넣는다.")
print("2. 우유를 넣는다.")
print("3. 신나게 섞는다.")

make_blueberry_smoothie() //콜론 절대 넣으면 안됨!

// 방법1
total_dictionary = {}

while True:
question = input("질문을 입력해주세요 : ")
if question == "q":
break
else:
total_dictionary[question] = ""

for i in total_dictionary:
print(i)
answer = input("답변을 입력해주세요 : ")
total_dictionary[i] = answer
print(total_dictionary)

// 방법2
total_list = []

while True:
question = input("질문을 입력해주세요 : ")
if question == "q":
break
else:
total_list.append({"질문" : question, "답변" : ""})

for i in total_list:
print(i["질문"])
answer = input("답변을 입력해주세요 : ")
i["답변"] = answer
print(total_list)

 

관련글 더보기

댓글 영역