개발자로 가는길 :: '파이썬예제' 태그의 글 목록
반응형

파이썬예제에 해당하는 글
반응형
6

Python 인강 Day10 / Day 100

개발/파이썬|2023. 3. 16. 08:56
728x90
반응형

계산기

 

#Day 10 Calculator 

from replit import clear
from art import logo

def add(n1, n2):
  return n1 + n2

def subtract(n1, n2):
  return n1 - n2

def multiply(n1, n2):
  return n1 * n2

def divide(n1, n2):
  return n1 / n2

operations = {
  "+": add,
  "-": subtract,
  "*": multiply,
  "/": divide
}

def calculator():
  print(logo)

  num1 = float(input("What's the first number?: "))
  for symbol in operations:
    print(symbol)
  should_continue = True
 
  while should_continue:
    operation_symbol = input("Pick an operation: ")
    num2 = float(input("What's the next number?: "))
    calculation_function = operations[operation_symbol]
    answer = calculation_function(num1, num2)
    print(f"{num1} {operation_symbol} {num2} = {answer}")

    if input(f"Type 'y' to continue calculating with {answer}, or type 'n' to start a new calculation: ") == 'y':
      num1 = answer
    else:
      should_continue = False
      clear()
      calculator()

calculator()
728x90
반응형

댓글()

나도코딩 Python 자율학습단2기 2주차 -2

728x90
반응형

 

8장부터 시작

 

표준 입력받기 input()

 

abc  = input("입력해주세요") 
#입력값 abc 변수로 이동
#기본적으로 string 으로 저장
#형 변환시 
#예시)
abc = int(input("입력해주세요"))
#int 형태로 변수에 저장
 

 

표준 출력시 유용한 기능

print("파이썬","자바") #파이썬 자바
print("파이썬"+"자바") #파이썬자바
print("파이썬","자바",sep=" , ") #파이썬, 자바
print("파이썬","자바",sep=" , " , end=" ? ") #파이썬, 자바 ? / end 따로 지정하지 않으면 기본적으로 줄바꿈

import sys
print("파이썬","자바",file=sys.stdout) #표준출력 ( 로그남김 )
print("파이썬","자바",file=sys.stderr) #오류발생시 관련 내용 출력

#좌우 정렬
.ljust()  #좌정렬.   .rjust() #우정렬
ljust(8)  #8칸 확보 좌정렬
just(3)   #3칸 확보 우정렬

#빈칸 0으로 채우기 .zfill( )
zfill(3) #3자리수중 빈칸은 0으로 채움 
 

 

format()함수

#.format()함수
print("{0}".format(500)) #{0}위치에 500출력
print("{0: >10}".format(500)) #빈칸으로두기 , 오른쪽정렬 , 10칸확보
print("{0: >+10}".format(500)) #빈칸으로두기,오른쪽정렬,+기호붙이기,10칸확보 / 음수도 적용가능
print("{0:_<10}".format(500)) #빈칸을 _ 로 채우기 , 왼쪽정렬 , 공간 10칸 확보
print("{0:,}".format(5000)) #3자리마다 쉼표찍기
print("{0:,+}".format(500)) #+기호 붙이고 3자리마다 쉼표찍기 / 음수도 적용가능
print("{0: < +20,}".format(5000)) #좌로정렬 , 20칸확보 , + 기호 붙이기 , 3자리마다 쉼표찍기
print("{0.f}".format(5/3)) # 5/3 float형으로 표시
print("{0.f2}".format(5/3)) # 5/3 을 소수 2자리까지 표시
 

파일 입출력

#파일 열기
open("파일명" , "모드" , encoding="인코딩 형식")
#모드
r -> 읽기 / 파일내용 읽기
w ->쓰기 / 파일내용쓰기 / 같은이름의 파일이 있으면 해당 파일을 덮어써서 기존내용삭제
a ->이어쓰기 / 파일내용쓰기 / 같은이름의 파일이 있으면 기존 내용 끝에 이어씀

#예제
score_file = open("score.txt" , "w" , encoding="utf8" )
print('수학 : 0 ' , file=score_file) #score.txt 파일에 내용 쓰기
print('영어 : 50 ', file=score_file)  
score_file.close() #score.txt 파일 닫기

# write 모드는 자동줄바꿈이 없음 \n 추가
# read()  #파일 통째로 불러와 읽음
# readline() #한줄씩 읽어옴
#readlines() #줄단위로 나뉜 리스트 형태로 한꺼번에 읽어오기
 

 

8.7 실습문제 : 보고서 파일만들기

 

 

728x90
반응형

댓글()

나도코딩 Python 자율학습단 2기 2주차-1

728x90
반응형

 

본 내용은 네이버카페 코딩자율학습단 에도 동일한 내용이 업로드 됨을 알려드립니다.

 

7장 함수

 

-사용자 정의 함수

def 함수명():
    실행한 문장1
    실행할 문장2
    실행할 문장3
    . . . 
 

직접 함수를 정의하여 호출 할 수 있다.

 

함수명을 지을때는 이름을 보고 어떤 동작을 하는지 유추할 수 있게 해야 한다.

 

 

-전달값과 반환값

def 함수명(전달값1,전달값2....)
    실행할 문장1
    실행할 문장2
    . . .
    return 반환값1
 

7.5 실습문제 : 표준체중 구하기

 

#7.5 표준 체중 구하기

#표준 체중 구하는 프로그램 작성
#남자 : 키(m) x 키(m) x 22  , 여자 : 키(m) x 키(m) x 21
#1. 함수명 std_weight / 전달값 키(height) 성별(gender)
#2. 실행결과 소수점 이하 둘째 자리까지

def std_weight(height,gender):
    if gender == "남자" :
        result_man = height*height*22
        print(f"키 {height*100}cm {gender}의 표준 체중은{round(result_man,2)}kg 입니다.")
    else:
        result_female = height*height*21
        print(f"키 {height*100}cm {gender}의 표준 체중은{round(result_female,2)}kg 입니다.")
        

std_weight(1.72,"여자")
 

 

.

 

7장 셀프체크

#7장 셀프체크
#미세먼지 수치를 입력받아 대기질 상태를 출력
#1. get_air_quality 라는 이름의 함수
#2. 이 함수는 전달값으로 미세먼지 수치를 입력받는다.
#4. 0~30 좋음 , 31~80 보통 , 81~150 나쁨 , 151이상 매우나쁨

def get_air_quality(figure):
    if figure<=30 :
        return "좋음"
    elif figure <= 80:
        return "보통"
    elif figure <=150:
        return "나쁨"
    else:
        return "매우나쁨"
    

print(get_air_quality(15))
print(get_air_quality(85))

 
 

오히려 앞에 장들보다 이해하기 쉽고 재밌는 단원이었습니다.

 

728x90
반응형

댓글()

Python 인강 day 8 / day 100

개발/파이썬|2023. 3. 13. 08:03
728x90
반응형

카이사르 암호화 / 복호화

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

def caesar(start_text, shift_amount, cipher_direction):
  end_text = ""
  if cipher_direction == "decode":
    shift_amount *= -1
  for char in start_text:
    #TODO-3: What happens if the user enters a number/symbol/space?
    #Can you fix the code to keep the number/symbol/space when the text is encoded/decoded?
    #e.g. start_text = "meet me at 3"
    #end_text = "•••• •• •• 3"
    if char in alphabet:
      position = alphabet.index(char)
      new_position = position + shift_amount
      end_text += alphabet[new_position]
    else:
      end_text += char
  print(f"Here's the {cipher_direction}d result: {end_text}")

#TODO-1: Import and print the logo from art.py when the program starts.
from art import logo
print(logo)

#TODO-4: Can you figure out a way to ask the user if they want to restart the cipher program?
#e.g. Type 'yes' if you want to go again. Otherwise type 'no'.
#If they type 'yes' then ask them for the direction/text/shift again and call the caesar() function again?
#Hint: Try creating a while loop that continues to execute the program if the user types 'yes'.
should_end = False
while not should_end:

  direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
  text = input("Type your message:\n").lower()
  shift = int(input("Type the shift number:\n"))
  #TODO-2: What if the user enters a shift that is greater than the number of letters in the alphabet?
  #Try running the program and entering a shift number of 45.
  #Add some code so that the program continues to work even if the user enters a shift number greater than 26. 
  #Hint: Think about how you can use the modulus (%).
  shift = shift % 26

  caesar(start_text=text, shift_amount=shift, cipher_direction=direction)

  restart = input("Type 'yes' if you want to go again. Otherwise type 'no'.\n")
  if restart == "no":
    should_end = True
    print("Goodbye")

이게 코딩이 문제가 아니라 강의가 영어인데 연습문제의 번역이 음.. 별로라 문제자체를 이해하고 시작하기 힘들다

어찌어찌 끝까지 하긴 했는데 아침부터 두시간을 진을 뺐다..ㅠ

728x90
반응형

댓글()

나도코딩 Python 자율학습단2기 1주차 - 5

728x90
반응형

본 자율학습 내용은 네이버 카페 코딩 자율학습단 에도 동일하게 업로드됨을 알려드립니다

 

6. 제어문

 

초반 공부에 첫번째 난관인것같아요 조건문..ㅋ

 

if문

#조건이 하나일때 if 문

 if 조건 : #true일때
     실행할 명령

#조건이 여러개일때 elif 문

  if 조건:
     실행할명령
  elif 조건:
     실행할명령
  elif 조건:
     실행할명령


#모든 조건에 맞지 않을때 else 문

 if 조건:
    실행할 명령
else: #조건이 맞지 않을때
    실행할 명령
 

 

-사용자로부터 값을 입력받을땐 input() 함수를 사용

변수명 = input(" 값을 입력해 주세요 >>" ) 

실행시 커맨드 창에 값을 입력할수 있다 / 입력한 값은 지정한 변수명에 저장

 

입력한 값은 기본적으로 string 형태로 저장되기 때문에 필요시 형변환하여 사용 // exam = int(input("값을 입력해주세요>>"))

 

 

 

반복문 for문 , while 문

-for문

for 변수 in 반복대상 :
    실행할명령

#실행순서 : 반복대상의 값 -> 변수 -> 실행할 명령  / 반복대상의 값이 끝날때까지 반복

동작 for 변수 in 반복대상  #한줄로 표현 가능 (리스트 컴프리헨션) 

-while문

while 조건:
    실행할명령

#조건이 끝날때까지 반복
 

 

6.3 실습문제 : 택시 승객 수 구하기

 

총탑승객 을 구할땐 for 문 바깥에 0의 값을 갖는 변수를 만들어 매칭이 되었을때 result 값이 +1 씩 되게 구성 했습니다.

완성! result 라는 변수가 처음엔 for문 안으로 들어가야 할줄 알고 넣었는데 계속 0명으로 표시가 되길래 디버깅을 돌리니 루프가 돌때마다 초기화 되길래 바깥으로 빼니 정상적으로 동작했습니다.

 

셀프체크

오늘 공부 여기까지! 모두 고생하셨습니다

 

728x90
반응형

댓글()

3/7 Python 인강 Day 5 / Day 100

개발/파이썬|2023. 3. 7. 23:25
728x90
반응형

이것저것 하다가 시간이 늦어져서 너무 피곤하지만..

그래도 해야지..

 

for문 시작했는데 대충 어떻게 실행될지는 알고 있지만서도 이해가 잘 안되었는데

지겹도록 반복하다 보니 오늘따라 아! 하고 느껴지는것이 조금 있었다.

 

# Day5 Exam2 
# 입력값 중 가장 높은 값 찾기

student_score = input("점수를 입력해주세요 (띄어쓰기로 구분) >> ").split()   #split 으로 띄어쓰기 구분해서 잘라줌
for i in range(0, len(student_score)):                             
    student_score[i] = int(student_score[i])                        #student_score 의 0부터~len만큼 반복하여
                                                                    #int값의 리스트를 작성

highest_score = 0
for score in student_score:
    if score > highest_score:                                       #조건이 True면 highest_score에 값 저장
        highest_score = score                                       #fals면 저장하지 않고 반복문으로 돌아감
    
print(f"최고점수는 {highest_score}점 입니다")

 

마지막 프로젝트는 내기준으론 좀 어려웠다..라기 보다 random 모듈에 있는 다른 기능을 안가르쳐줬는데

choice 와 shuffle 이 들어갔다. 모르는건 구글링 해보라는 뜻 같다

 

# Day5 Exam3
# 1~100까지의 모든 짝수의 합 (for range 문 이용)

result = 0
for i in range(2,101,2):
    result += i
print(f"모든 짝수의 합은 {result}")

result2 = 0
for j in range(1,101):
    if j%2 == 0:
        result2 += j
print(f"모든 짝수의 합은 {result2}")


# Day5 Exam4
# FizzBuzz 게임
# 3으로 나눌수있는 숫자일땐 Fizz , 5로 나눌수 있는 숫자일땐 Buzz 출력 , 3 5모두 나눌수있음 FizzBuzz
# (미국 아동용 게임이라고 한다 우리나라 369 비슷한 ㅋ)

for number in range(1,100):
    if number%3==0:
        print("Fizz")
    elif number%5==0:
        print("Buzz")
    elif number%5==0 and number%3==0:
        print("FizzBuzz")
    else:
        print(number)
        
        # Day5 Fianl Project
# 패스워드 만들기 아래는 미리 만들어져있던 리스트
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']

print("Welcome to the PyPassword Generator!")
nr_letters = int(input("How many letters would you like in your password?\n")) 
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))

#Eazy Level
# password = ""

# for char in range(1, nr_letters + 1):
#   password += random.choice(letters)

# for char in range(1, nr_symbols + 1):
#   password += random.choice(symbols)

# for char in range(1, nr_numbers + 1):
#   password += random.choice(numbers)
# print(password)

#Hard Level
password_list = []          #최종 만들어질 패스워드의 리스트

for char in range(1, nr_letters + 1):
  password_list.append(random.choice(letters))  #letter에서 랜덤으로 초이스된 문자열을 리스트에 가장 뒤에 추가  (입력받은값까지) 

for char in range(1, nr_symbols + 1):           
  password_list += random.choice(symbols)       #마찬가지

for char in range(1, nr_numbers + 1):
  password_list += random.choice(numbers)       #마찬가지

print(password_list)
random.shuffle(password_list)                   #만들어진 리스트 섞어줌
print(password_list)                            #최종

password = ""
for char in password_list:
  password += char

print(f"Your password is: {password}")

 

오늘 공부 마무리

 

오늘은 시간이 좀 늦었다 피곤해서 눈앞이 좀 흐리다..ㅠ 굿나잇

728x90
반응형

댓글()