Python

Coursera_Python for everyone_Chapter 5.

심리밀당남 2016. 7. 28. 17:13

Week 5. 정리노트


week 5 Conditional Statement 

' if '

' elif '

' else '

*indent : 들여쓰다.
-조건문은 들여쓰기(indentation)로 구분.

' indentation errors ' - 들여쓰기 할 때 tap이랑 space bar랑 섞어쓰면 안됨. 무조건 tap으로만.

' The try  / except Structure '. 예외처리 구문.
- 코드오류로 인해 프로그램이 죽는걸 방지.
- 오류가 날 가능성이 있는 코드들을 try 구문에 적음. 
- try가 실패할 시 실행할 코드들을 except에 적음.

- syntax
try:
     ~~~
except:
     ~~!@

Assignment 1.
      3.1 Write a program to prompt the user for hours and rate per hour using raw_input to compute gross pay. Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use raw_input to read a string and float() to convert the string to a number. Do not worry about error checking the user input - assume the user types numbers properly.

-----CODE
try :
hrs = raw_input("Enter Hours : ")
h = float(hrs)

rate = raw_input("Enter Rate Per Hours : ")
r = float(rate)

except :
print 'please input numeric values'

pay = 0

if h < 40:
pay = r * h

else:
pay = 40 * r + (h - 40) * r * 1.5

print pay
-----CODE------

Assignment 2.
3.3 Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error. If the score is between 0.0 and 1.0, print a grade using the following table:
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
If the user enters a value out of range, print a suitable error message and exit. For the test, enter a score of 0.85.

----CODE---
try:
    score = raw_input("Enter Score: ")
    s = float(score)
    if s >= 0.0 and s <= 1.0:
        if s >= 0.9:
            print 'A'

        elif s >= 0.8:
            print 'B'

        elif s >= 0.7:
            print 'C'

        elif s <= 0.6:
            print'D'

        else:
            print 'F'

    else:
        print 'please input appropriate numeric value(0.0~1.0)'


except:
    print 'please input appropriate numeric value(0.0~1.0)'

----CODE---



수업후기

이번 5주차에서는 제어문 중에서도 'if문들(if, elif, else)'과 파이썬에서의 예외처리 구문인 'try -- except'에 대해서 공부했다. if문들은 새로운 내용이 딱히 없었으나 try-except 문은 C에서 내가아는 수준에서는 몰랐던 내용이라 재밌게 들었다. 과제 2번에서 입력이 숫자가 아닐때의 예외처리를 하고싶어 처음에는

s = float(score) 

까지만 try문에 적었었다. 예상으론 숫자가 안들어오면 float으로 캐스팅 하는 것 자체가 안돼 바로 except 문으로 갈 줄 알았는데 다음 코드도 자동으로 실행되는지 s값이 존재하지 않는다는 오류가 뜨며 실행되지 않았었다. 그래서 그냥 전체 코드를 다 try문에 넣으니 이상없이 실행됬다. 첫번째 시도 떄 왜 안됬는지 아직도 잘 모르겠다.

댓글수0