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

파이썬연습문제에 해당하는 글
반응형
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 인강 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
반응형

댓글()

3/9 Python 인강 Day 7 / Day 100

개발/파이썬|2023. 3. 9. 21:31
728x90
반응형

오늘은 프로젝트였는데 

내기준에선 좀 어려웠다.

나중에 솔루션 코드를 보고 이해하긴 했는데 처음부터 끝까지 혼자하기엔 좀 근성이 부족했던것 같다.

 

행맨게임 프로젝트

#Day7 Project 
#HANGMAN 게임 만들기

import random

stages = ['''
  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
  |   |
      |
      |
=========
''', '''
  +---+
  |   |
  O   |
      |
      |
      |
=========
''', '''
  +---+
  |   |
      |
      |
      |
      |
=========
''']

end_of_game = False
word_list = ["ardvark", "baboon", "camel"]  #정답 리스트
chosen_word = random.choice(word_list)      #정답중 한개를 랜덤으로 선택
word_length = len(chosen_word)              #선택된 정답의 문자열길이

#TODO-1: - Create a variable called 'lives' to keep track of the number of lives left. 
#Set 'lives' to equal 6.
lives = 6   #목숨 6개

#Testing code
print(f'Pssst, the solution is {chosen_word}.') #테스트 코드임 정답 보여줌

#Create blanks
display = []        #빈 리스트 생성
for _ in range(word_length):
    display += "_"  #정답의 문자열 길이 만큼 "_" 생성

while not end_of_game:  #게임이 끝나지 않았으면 반복
    guess = input("Guess a letter: ").lower() #문자 묻는 인풋

    #Check guessed letter
    for position in range(word_length): # 정답의 문자열 길이 만큼 반복
        letter = chosen_word[position]  # letter 에 정답 문자열 포지션 저장
       # print(f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}")
        if letter == guess:     # 입력한 문자가 letter 에 있을때
            display[position] = letter  #  디스플레이 포지션에 넣음

    #TODO-2: - If guess is not a letter in the chosen_word,
    #Then reduce 'lives' by 1. 
    #If lives goes down to 0 then the game should stop and it should print "You lose."
    if guess not in chosen_word: #입력한 문자가 정답안에 없을때
        lives -= 1      #목숨 -1
        if lives == 0:  #목숨이 0이 되면
            end_of_game = True #end_of_game 이 true로 바뀜 = while반복문 끝남
            print("You lose.")  # 졌다고 출력

    #Join all the elements in the list and turn it into a String.
    print(f"{' '.join(display)}") 

    #Check if user has got all letters.
    if "_" not in display:  #만약 display 에  _ 가 없으면 (문자가 다 체워지면)
        end_of_game = True  #while문 종료
        print("You win.")   #이겼다고 출력

    #TODO-3: - print the ASCII art from 'stages' that corresponds to the current number of 'lives' the user has remaining.
    print(stages[lives])

주말에 바다보이는 카페에 앉아서 다시 해봐야겠다

728x90
반응형

댓글()

3/8 Python 인강 Day 6 / Day 100

개발/파이썬|2023. 3. 8. 20:57
728x90
반응형

첫번째 Exam 로봇 점프 ㅋ 꽤 재밌는 과제였다.

 

def 함수명() : 로 나만의 함수를 만들고 들여쓰기로 기능을 넣는 형태

 

#Day6 Exam1
def turn_right():
    turn_left()
    turn_left()
    turn_left()
    
def cycle():
    move()
    turn_left()
    move()
    turn_right()
    move()
    turn_right()
    move()
    turn_left()


cycle()
cycle()
cycle()
cycle()
cycle()
cycle()

해보고 싶으신분은 https://reeborg.ca/ 여기서 해볼수 있습니다.

 

Exam2

랜덤 골지점

 

#Day6 Exam2
#Goal 지점이 나올때까지 while 문 이용 반복
def turn_right():
    turn_left()
    turn_left()
    turn_left()
    
def cycle():
    move()
    turn_left()
    move()
    turn_right()
    move()
    turn_right()
    move()
    turn_left()


while not at_goal():
    cycle()

 

Exam3 

랜덤 장애물

 

#Day6 Exam3
def turn_right():
    turn_left()
    turn_left()
    turn_left()
    
def cycle():
    
    turn_left()
    move()
    turn_right()
    move()
    turn_right()
    move()
    turn_left()


while not at_goal():
    if front_is_clear():
        move()
    elif wall_in_front():
        cycle()

게임으로 하니까 쉬운것 같기도하고. 그냥 쉬운 문제를 내준건가 싶기도 하고.

 

Day6 Exam4

랜덤 장애물 피하기

 

def turn_right():
    turn_left()
    turn_left()
    turn_left()
    
def cycle1():
    turn_left()
    while wall_on_right():
        move()
    turn_right()
    move()
    turn_right()

    while front_is_clear():
            move()
    turn_left()
   


while not at_goal():
    if wall_in_front():
        cycle1()
    else:
        move()

오늘 수업은 여기까지.

728x90
반응형

'개발 > 파이썬' 카테고리의 다른 글

3/9 Python 인강 Day 7 / Day 100  (0) 2023.03.09
3/9 Java 인강 공부(feat.chatGPT)  (2) 2023.03.09
3/8 Java 인강 공부 (feat . chatGPT)  (0) 2023.03.08
3/7 Python 인강 Day 5 / Day 100  (0) 2023.03.07
3/6 Python 공부 day 4 / day 100  (0) 2023.03.06

댓글()

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
반응형

댓글()

파이썬 숫자 맞추기 게임 연습

개발/파이썬|2023. 3. 5. 12:15
728x90
반응형
import random  #랜덤 모듈 불러오기

num = random.randint(1,100) #1 ~ 100 범위의 난수 생성
i = 0						#횟수 카운팅을 위한 변수 i
x = 0						#입력한 수 저장을 위한 변수

while x != num:
    i += 1   				#반복문 진행될수록 +1 씩 카운팅
    x = int(input("1~100 숫자 입력: ")) #입력받은 수를 변수 x에 저장
    
    if x < num:					# 입력받은 수가 생성된 랜덤수보다 작으면
        print("UP")				# True 일때 Up 을 출력
    elif x > num:				# 입력받은 수가 생성된 램덤수보다 크면
        print("DOWN")			# True 일때 Down 출력
    elif x == num:				# 입력받은 수가 생성된 랜덤수와 같으면
        print(f"정답입니다! {i}회 만에 맞췄어요.") # 정답입니다 출력 , 카운팅된 i 같이 출력 (f-string이용 )

처음엔 반복문의 존재를 생각도 안하고

if , elif 만을 이용해 만들었다가 숫자 한번 입력하면 바로 종료되길래 뭔가 했다....

반복문은 여러번해도 적응이 잘 안된다.

728x90
반응형

댓글()