728x90
반응형
목차
1. print()
2. 기본 자료형: 숫자형, 문자열, 리스트
3. 변수
4. 연산: 사칙연산, 특수연산, 문자열 연산
5. 인덱싱과 슬라이싱

1. print()

Point I
print() : 문자열을 출력하는 명령어

print("Hello Rabbit!")  

## 출력결과 ##
Hello Rabbit!

Point II
콤마(,)를 통해 여러 자료를 출력

print(3, "Hello")   

## 출력결과 ##
3 Hello

Point III
print()를 여러 번 사용하여 여러 줄에 걸쳐 출력

print(3)  
print(6)  
print(9)  

## 출력결과 ##
3
6
9

2. 기본 자료형

Point I
숫자형 : 숫자로 이루어진 자료형

3 : 정수  
3.14 : 실수  

Point II
문자열 : 문자, 혹은 문자들의 집합 - 큰따옴표(“)/작은따옴표(‘)로 구분

'Hello'  
'3.14'  
"3.14"  

Point III
리스트 : 여러 자료를 함께 보관하는 자료형 - 대괄호([])로 구분

[]  
['a', 'b']  
['a', 2]  

3. 변수

Point I
변수 : 자료를 담는 그릇
변수 이름 = 자료 형태로 사용

num = 10   
name = "Michael"   
grade = ['A+', 'B+', 'A0']  

Point II
변수 이름 짓기
숫자, 알파벳, 언더바(_) 등을 사용

Point III
금지 규칙

  • 숫자로 시작하는 변수이름 금지
1st = 1000 #Error
  • 숫자로만 구성된 변수 이름은 사용 불가
123 = "Hello!" #Error
  • 파이썬 문법에서 이미 사용되는 단어(keyword, 예약어)는 사용 불가
for = 10 #Error
  • 공백 문자( )와 연산자는 사용 불가
I am = "groot" #Error  
3+4 = 12 #Error

4. 연산

Point I
숫자의 사칙연산 : +(더하기), -(빼기), *(곱하기), /(나누기)

print(6+3) #9
print(6-3) #3
print(6*3) #18
print(6/3) #2.0

Point II
숫자의 특수연산 : **(제곱), //(몫 연산), %(나머지 연산)

print(6**3) #216
print(6//3) #2
print(6%3) #0

Point III
문자열의 연산: +(연결하기), *(반복하기)

print("Hello" + "World") #HelloWorld
print("Hello"*3) #HelloHelloHello

5. 인덱싱과 슬라이싱

Point I
인덱스 : 문자열과 리스트의 특정 원소의 위치, 0부터 시작

"Hello"에서 H = Index 0, e = index 1, ...

Point II
인덱싱 : 문자열과 리스트의 특정 위치(인덱스)의 원소를 가져오는 것

greet = "Hello!"  
print(greet[1])  

## 출력결과 ##
e

Point III
슬라이싱 : 문자열과 리스트의 특정 부분을 가져오는 것

greet = "Hello!"  
print(greet[0:5])  
Hello

[Next] (2주차) 조건문

2022.05.25 - [Dev/Python] - [Python] 02 조건문 - week.02

 

[Python] 02 조건문 - week.02

목차 1. 입력 1) 변수 2) 형 변환 2. 논리 자료형(Boolean Data) 1) 논리 자료형 2) 비교 연산자 3) 논리 연산자 3. 조건문 1) if문 2) elif문 3) else문 [Review] (1주차) 기초 자료형 2022.07.10 - [Dev/Python]..

sarahee.tistory.com

 

728x90
728x90

'Development > Python' 카테고리의 다른 글

[Python] 02 함수와 메서드 - week.06  (0) 2022.11.08
[Python] 01 기초 자료형 II - week.05  (0) 2022.09.05
[Python] 04 반복문 - week.04  (0) 2022.08.08
[Python] 03 리스트 - week.03  (0) 2022.07.28
[Python] 02 조건문 - week.02  (0) 2022.07.22
728x90
반응형

[Review] (2주차) 실습

2022.06.26 - [Swift] - [Xcode] iOS Swift 앱 개발 Byte Degree - week.02

 

[Xcode] iOS Swift 앱 개발 Byte Degree - week.02

iOS 아키텍처 패턴 중 애플에서는 기본적으로 MVC 패턴을 가이드함 Product Name: HelloiOS Organization Identifier: com.sehee Interface: Storyboard (other options: SwiftUI) Language: Swift (other option..

sarahee.tistory.com


Intro

Swift의 기본 기능, 리스트 및 그리드에 대해 알아보자

Xcode 실행시 기본 스토리보드

File > New > File (or command + n)

view controller 추가하기

Cocoa Touch Class > (Choose options for your new file) Class: StockRankViewController > Next > Create

좌측 Main Tab의 View Controller > 우측 Custom Class - Class 및 Identity - Storyboard ID: StockRankViewController 설정

* Storyboard ID에서 검색이 용이하도록(class 이름 자체가 unique한 id이므로 동일하게 설정해도 무방)

 

Main storyboard에서 우측 상단 + 버튼 클릭하여 UI components(objects) 선택

Collection View 추가

 


Auto rayout 설정

자식 뷰(Collection View)를 부모 뷰(View)에 연관되게 설정하기 위함

control 버튼을 누른 상태에서 Collection View → View 드래그

Shift를 누른 상태에서 클릭하여 다중 선택(상단 네개 Space to Safe Area 모두 클릭) 이후 Enter

View를 Code로 연결하기

해당하는 스토리보드(Collection View) 클릭 후 우측 상단 =(리스트) 아이콘 클릭

Assistant 클릭하여 새로운 view 생성

control 누른 상태에서 연결하고 싶은 뷰(Collection View) → 코드 드래그

name: collectionView > connect

import UIKit

class StockRankViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

Connection View Cell 내에 Label, Image View 추가 (option 누르고 드래그할 경우 복제)

Image View는 우측 Image View > Image에서 검색하여 변경 (e.g. heart.fill)

적용: option + command + =

//
//  StockRankViewController.swift
//  StockRank
//
//  Created by sehee on 2022/06/30.
//

import UIKit

class StockRankViewController: UIViewController {

    let stockList: [StockModel] = StockModel.list
    @IBOutlet weak var collectionView: UICollectionView!
    
    // Data, Presentation, Layout
    // Data: 어떤 떼이터? - stockList
    // Presentation: 셀을 어떻게 표현?
    // Layout: 셀을 어떻게 배치?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView.dataSource = self
        collectionView.delegate = self
    }
}

extension StockRankViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return stockList.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "StockRankCollectionViewCell", for: indexPath)
        return cell
        // return UICollectionViewCell()
    }
}

extension StockRankViewController: UICollectionViewDelegateFlowLayout {
    }
}

extension StockRankViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        // width == collectionView
        return CGSize(width: collectionView.bounds.width, height: 80)
    }
}

StockRankCollectionViewCell code - data update

//
//  StockRankCollectionViewCell.swift
//  StockRank
//
//  Created by sehee on 2022/07/01.
//

import UIKit

class StockRankCollectionViewCell: UICollectionViewCell {
    // uicomponent 연결하자
    // uicomponent에 데이터 업데이트 하는 코드를 넣자
    @IBOutlet weak var rankLabel: UILabel!
    @IBOutlet weak var companyIconImageView: UIImageView!
    @IBOutlet weak var companyNameLabel: UILabel!
    @IBOutlet weak var companyPriceLabel: UILabel!
    @IBOutlet weak var diffLabel: UILabel!
    
    func configure(_ stock: StockModel) {
        rankLabel.text = "\(stock.rank)"
        companyIconImageView.image = UIImage(named: stock.imageName)
        companyNameLabel.text = stock.name
        companyPriceLabel.text = "\(stock.price) 원"
        diffLabel.text = "\(stock.diff)%"
    }
}

StockRankViewController code - data update

//
//  StockRankViewController.swift
//  StockRank
//
//  Created by sehee on 2022/06/30.
//

import UIKit

class StockRankViewController: UIViewController {

    let stockList: [StockModel] = StockModel.list
    @IBOutlet weak var collectionView: UICollectionView!
    
    // Data, Presentation, Layout
    // Data: 어떤 떼이터? - stockList
    // Presentation: 셀을 어떻게 표현?
    // Layout: 셀을 어떻게 배치?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView.dataSource = self
        collectionView.delegate = self
    }
}

extension StockRankViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return stockList.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // guard: as? (꼭 참이어야 하는 조건) else { return (거짓일 경우) } (참일 경우)
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "StockRankCollectionViewCell", for: indexPath) as? StockRankCollectionViewCell else {
            return UICollectionViewCell()
        }
        let stock = stockList[indexPath.item]
        cell.configure(stock)
        return cell
    }
}

extension StockRankViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        // width == collectionView
        return CGSize(width: collectionView.bounds.width, height: 80)
    }
}

가격 표현(쉼표 추가)

//
//  StockRankCollectionViewCell.swift
//  StockRank
//
//  Created by sehee on 2022/07/01.
//

import UIKit

class StockRankCollectionViewCell: UICollectionViewCell {
    // uicomponent 연결하자
    // uicomponent에 데이터 업데이트 하는 코드를 넣자
    @IBOutlet weak var rankLabel: UILabel!
    @IBOutlet weak var companyIconImageView: UIImageView!
    @IBOutlet weak var companyNameLabel: UILabel!
    @IBOutlet weak var companyPriceLabel: UILabel!
    @IBOutlet weak var diffLabel: UILabel!
    
    func configure(_ stock: StockModel) {
        rankLabel.text = "\(stock.rank)"
        companyIconImageView.image = UIImage(named: stock.imageName)
        companyNameLabel.text = stock.name
        companyPriceLabel.text = "\(convertToCurrencyFormat(price: stock.price)) 원"
        diffLabel.text = "\(stock.diff)%"
    }

    func convertToCurrencyFormat(price: Int) -> String {
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .decimal
        numberFormatter.maximumFractionDigits = 0
        let result = numberFormatter.string(from: NSNumber(value: price)) ?? ""
        return result
    }
}

(추가) 사용자 UI 반영 - 마이너스일 때 파란색 표시, 플러스일 때는 기본 빨간색 표시

# sol1

        var color: UIColor
        if stock.diff > 0 {
            color = UIColor.systemRed
        } else {
            color = UIColor.systemBlue
        }
        diffLabel.textColor = color

# sol2

        diffLabel.textColor = stock.diff > 0 ? UIColor.systemRed : UIColor.systemBlue

최종 코드

//
//  StockRankViewController.swift
//  StockRank
//
//  Created by sehee on 2022/06/30.
//

import UIKit

class StockRankViewController: UIViewController {

    let stockList: [StockModel] = StockModel.list
    @IBOutlet weak var collectionView: UICollectionView!
    
    // Data, Presentation, Layout
    // Data: 어떤 떼이터? - stockList
    // Presentation: 셀을 어떻게 표현?
    // Layout: 셀을 어떻게 배치?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView.dataSource = self
        collectionView.delegate = self
    }
}

extension StockRankViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return stockList.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // guard: as? (꼭 참이어야 하는 조건) else { return (거짓일 경우) } (참일 경우)
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "StockRankCollectionViewCell", for: indexPath) as? StockRankCollectionViewCell else {
            return UICollectionViewCell()
        }
        let stock = stockList[indexPath.item]
        cell.configure(stock)
        return cell
    }
}

extension StockRankViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        // width == collectionView
        return CGSize(width: collectionView.bounds.width, height: 80)
    }
}
//
//  StockRankCollectionViewCell.swift
//  StockRank
//
//  Created by sehee on 2022/07/01.
//

import UIKit

class StockRankCollectionViewCell: UICollectionViewCell {
    // uicomponent 연결하자
    // uicomponent에 데이터 업데이트 하는 코드를 넣자
    @IBOutlet weak var rankLabel: UILabel!
    @IBOutlet weak var companyIconImageView: UIImageView!
    @IBOutlet weak var companyNameLabel: UILabel!
    @IBOutlet weak var companyPriceLabel: UILabel!
    @IBOutlet weak var diffLabel: UILabel!
    
    func configure(_ stock: StockModel) {
        rankLabel.text = "\(stock.rank)"
        companyIconImageView.image = UIImage(named: stock.imageName)
        companyNameLabel.text = stock.name
        companyPriceLabel.text = "\(convertToCurrencyFormat(price: stock.price)) 원"
/*        var color: UIColor
        if stock.diff > 0 {
            color = UIColor.systemRed
        } else {
            color = UIColor.systemBlue
        }
        diffLabel.textColor = color
 */
        diffLabel.textColor = stock.diff > 0 ? UIColor.systemRed : UIColor.systemBlue
        diffLabel.text = "\(stock.diff)%"
    }

    func convertToCurrencyFormat(price: Int) -> String {
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .decimal
        numberFormatter.maximumFractionDigits = 0
        let result = numberFormatter.string(from: NSNumber(value: price)) ?? ""
        return result
    }
}

기본 제공 코드

//
//  StockModel.swift
//  StockRank
//
//  Created by joonwon lee on 2022/04/19.
//

import Foundation

struct StockModel {
    let rank: Int
    let imageName: String
    let name: String
    let price: Int
    let diff: Double
}

extension StockModel {
    static let list: [StockModel] = [
        StockModel(rank: 1, imageName: "TSLA", name: "테슬라", price: 1_238_631, diff: 0.04),
        StockModel(rank: 2, imageName: "AAPL", name: "애플", price: 238_631, diff: 1.04),
        StockModel(rank: 3, imageName: "NFLX", name: "넷플릭스", price: 438_631, diff: -0.04),
        StockModel(rank: 4, imageName: "GOOG", name: "알파벳 A", price: 3_176_631, diff: 0.04),
        StockModel(rank: 5, imageName: "AMZN", name: "아마존", price: 3_538_631, diff: 0.04),
        StockModel(rank: 6, imageName: "NIKE", name: "나이키", price: 158_631, diff: 0.04),
        StockModel(rank: 7, imageName: "DIS", name: "디즈니", price: 138_631, diff: 0.04),
        StockModel(rank: 8, imageName: "TSLA", name: "테슬라", price: 1_238_631, diff: 0.04),
        StockModel(rank: 9, imageName: "AAPL", name: "애플", price: 238_631, diff: 1.04),
        StockModel(rank: 10, imageName: "NFLX", name: "넷플릭스", price: 438_631, diff: -0.04),
        StockModel(rank: 11, imageName: "GOOG", name: "알파벳 A", price: 3_176_631, diff: 0.04),
        StockModel(rank: 12, imageName: "AMZN", name: "아마존", price: 3_538_631, diff: 0.04),
        StockModel(rank: 13, imageName: "NIKE", name: "나이키", price: 158_631, diff: 0.04),
        StockModel(rank: 14, imageName: "DIS", name: "디즈니", price: 138_631, diff: 0.04),
    ]
}

[Next] (4주차) 실습

2022.07.10 - [Dev/Swift] - [Xcode] iOS Swift 앱 개발 Byte Degree - week.04

 

[Xcode] iOS Swift 앱 개발 Byte Degree - week.04

[Review] (3주차) 실습 2022.07.01 - [Swift] - [Xcode] iOS Swift 앱 개발 Byte Degree - week.03 [Xcode] iOS Swift 앱 개발 Byte Degree - week.03 [Review] (2주차) 실습 2022.06.26 - [Swift] - [Xcode] iOS..

sarahee.tistory.com

 

728x90
728x90

+ Recent posts