티스토리 뷰

파이썬/예제

파이썬 Chapter 2 예제

cll179 2017. 7. 14. 14:37

2.1 (Convert Celsius to Fahrenheit) Write a program that reads a Celsius degree from the console and converts it to Fahrenheit and displays the result. The formula for the conversion is as follows:

 

fahrenheit = (9 / 5) * celsius + 32

 

1
2
3
4
5
6
celsius = eval(input("Enter a degree in Celsius: "))
 
fahrenheit = (9/5* celsius + 32
 
print(celsius, " celsius is ", fahrenheit,"Fahrenheit.")
 
cs

 

2.2 (Compute the volume of a cylinder) Write a program that reads in the radius and length of a cylinder and computes the area and volume using the following formulas:

 

 area = radius * radius * π

volume = area * length

 

1
2
3
4
5
6
7
8
radius, length = eval(input("Enter the radius and length of a cylinder: "))
PI = 3.14159
 
area = radius * radius * PI
volume = area * length
 
print("The area is ", round(area,4))
print("The volume is ", round(volume,1))
cs

 

2.3 (Convert feet into meters) Write a program that reads a number in feet, converts it to meters, and displays the result. One foot is 0.305 meters.  

1
2
3
4
5
feet = eval(input("Enter a value for feet :"))
 
meters = feet * 0.305
 
print(feet," feet is ",meters, " meters")
cs

2.4 (Convert pounds into kilograms) Write a program that converts pounds into kilograms. The program prompts the user to enter a value in pounds, converts it to kilograms, and displays the result. One pound is 0.454 kilograms.

1
2
3
4
5
pounds = eval(input("Enter a value in pounds : "))
 
kilograms = pounds * 0.454
 
print(pounds," pounds is ", kilograms, " kilograms")
cs

 


*2.5 (Financial application: calculate tips) Write a program that reads the subtotal and the gratuity rate and computes the gratuity and total. For example, if the user enters 10 for the subtotal and 15% for the gratuity rate, the program displays 1.5 as the gratuity and 11.5 as the total.

1
2
3
4
5
6
subtotal, gratuityrate = eval(input("Enter the subtotal and a gratutity rate : "))
 
gratuity = subtotal * gratuityrate / 100
total = subtotal + gratuity
 
print("The gratuity is ",gratuityrate, "and the total is ",round(total,2))
cs

 


 **2.6 (Sum the digits in an integer) Write a program that reads an integer between 0 and
1000 and adds all the digits in the integer. For example, if an integer is 932, the
sum of all its digits is 14. (Hint: Use the % operator to extract digits, and use the //
operator to remove the extracted digit. For instance, 932 % 10 = 2 and 932 //
10 = 93.)

 

1
2
3
4
5
6
7
8
9
10
11
number = eval(input("Enter a number between 0 and 1000 : "))
sum = 0
 
sum += number % 10 
number //= 10
sum += number % 10 
number //= 10
sum += number % 10 
number //= 10
 
print("The sum of the digits is ", sum)
cs

**2.7 (Find the number of years and days) Write a program that prompts the user to enter the minutes (e.g., 1 billion), and displays the number of years and days for the minutes. For simplicity, assume a year has 365 days.

1
2
3
4
5
6
minutes = eval(input("Enter the number of minutes : "))
 
years = minutes // 525600
days = (minutes-years*525600// 1440
 
print(minutes ," minutes is approximantely ",years,"years and ",days, " days")
cs

2.8 (Science: calculate energy) Write a program that calculates the energy needed to heat water from an initial temperature to a final temperature. Your program should prompt the user to enter the amount of water in kilograms and the initial and final temperatures of the water. The formula to compute the energy is

 

Q = M * (finalTemperature – initialTemperature) * 4184

 

where M is the weight of water in kilograms, temperatures are in degrees Celsius, and energy Q is measured in joules.

 

1
2
3
4
5
6
7
waterKg = eval(input("Enter the amount of water in kilograms: "))
initTemper = eval(input("Enter the initial temperature: "))
finalTemper = eval(input("Enter the final temperature: "))
 
energy =  waterKg * (finalTemper - initTemper) * 4184
 
print("the energy needed is ",energy)
cs

 


*2.9 (Science: wind-chill temperature) How cold is it outside? The temperature alone is not enough to provide the answer. Other factors including wind speed, relative humidity, and sunshine play important roles in determining coldness outside. In 2001, the National Weather Service (NWS) implemented the new wind-chill temperature to measure the coldness using temperature and wind speed. The formula is given as follows:

 

twc = 35.74 + 0.6215*ta - 35.75*v^0.16 + 0.4275*ta*v^0.16

 

where is the outside temperature measured in degrees Fahrenheit and v is the speed measured in miles per hour. is the wind-chill temperature. The formula cannot be used for wind speeds below 2 mph or for temperatures below or above 41°F. Write a program that prompts the user to enter a temperature between and 41°F and a wind speed greater than or equal to 2 and displays the wind-chill temperature.

 

1
2
3
4
5
6
fahrenheit = eval(input("Enter the temperature in Fahrenheit between -58 and 41: "))
windSpeed = eval(input("Enter the wind speed in miles per hour: "))
 
wc = 35.74 + 0.6215*fahrenheit - 35.75*(windSpeed**0.16+ 0.4275*fahrenheit*(windSpeed**0.16)
 
print("The wind chill index is ",round(wc,5))
cs

*2.10 (Physics: find runway length) Given an airplane’s acceleration a and take-off speed v, you can compute the minimum runway length needed for an airplane to take off using the following formula: 

 

 

Write a program that prompts the user to enter v in meters/second (m/s) and the acceleration a in meters/second squared and displays the minimum runway length.

 

1
2
3
4
5
speed , accel = eval(input("Enter speed and acceleration : "))
 
length = (speed*speed)/(2*accel)
 
print("The minimum runway length for this airplane is ",round(length,3), "meters")
cs

*2.11 (Financial application: investment amount) Suppose you want to deposit a certain amount of money into a savings account with a fixed annual interest rate. What amount do you need to deposit in order to have $5,000 in the account after three years? The initial deposit amount can be obtained using the following formula:

 

 

Write a program that prompts the user to enter final account value, annual interest rate in percent, and the number of years, and displays the initial deposit amount.

 

1
2
3
4
5
6
7
8
9
final = eval(input("Enter final account value: "))
annualInter = eval(input("Enter annual interest rate in percent: "))
years = eval(input("Ente number of years: "))
 
monthlyInter = annualInter/1200 #퍼센테이지는 이미 100이 나누어져있는 상태이므로 1200으로 나누어야한다.
numOfMonths = years * 12
initial = final / ((1+monthlyInter)**numOfMonths)
 
print(round(initial,10))
cs

2.12 (Print a table) Write a program that displays the following table:

 

a     b    a ** b

1     2    1

2     3    8

3     4    81     

4     5    1024

5     6    15625

 

1
2
3
4
5
6
7
print("a\tb\ta*b")
 
print(1,"\t",2,"\t",1**2)
print(2,"\t",3,"\t",2**3)
print(3,"\t",4,"\t",3**4)
print(4,"\t",5,"\t",4**5)
print(5,"\t",6,"\t",5**6)
cs

 *2.13 (Split digits) Write a program that prompts the user to enter a four-digit integer and displays the number in reverse order.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
number = eval(input("Enter an integer: "))
 
print(number // 1000)
number %= 1000
 
print(number // 100)
number %= 100
 
print(number // 10)
number %= 10
 
print(number)
 
cs

*2.14 (Geometry: area of a triangle) Write a program that prompts the user to enter the three points (x1, y1), (x2, y2), and (x3, y3) of a triangle and displays its area. The formula for computing the area of a triangle is  

 

 

 

1
2
3
4
5
6
7
8
9
10
11
x1,y1, x2,y2, x3,y3 = eval(input("Enter three points for a triangle: "))
 
sideOne = ((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2))**0.5
sideTwo = ((x2 - x3)*(x2 - x3) + (y2 - y3)*(y2 - y3))**0.5
sideThree = ((x3 - x1)*(x3 - x1) + (y3 - y1)*(y3 - y1))**0.5
 
= (sideOne + sideTwo + sideThree) / 2
area = (s * (s - sideOne)*(s - sideTwo)*(s - sideThree))**0.5
 
print("The area of the triangle is ",round(area,1))
 
cs

 

2.15 (Geometry: area of a hexagon) Write a program that prompts the user to enter the side of a hexagon and displays its area. The formula for computing the area of a hexagon is

 

where Area = s is the length of a side. 

 

1
2
3
4
5
6
side = eval(input("Enter the side: "))
 
area = ((3 * (3**0.5)) / 2* (side**2)
 
print("The area of the hexagon is ", round(area,4))
 
cs

2.16 (Physics: acceleration) Average acceleration is defined as the change of velocity divided by the time taken to make the change, as shown in the following formula:

 

 

Write a program that prompts the user to enter the starting velocity in meters/second, the ending velocity in meters/second, and the time span t in seconds, and displays the average acceleration.

 

1
2
3
4
5
velZero, velOne, time = eval(input("Enter v0, v1 and t: "))
 
averageOfacc = (velOne - velZero) / time
 
print("The average acceleration is ",round(averageOfacc,4))
cs

*2.17 (Health application: compute BMI) Body mass index (BMI) is a measure of health based on weight. It can be calculated by taking your weight in kilograms and dividing it by the square of your height in meters. Write a program that prompts the user to enter a weight in pounds and height in inches and displays the BMI. Note that one pound is 0.45359237 kilograms and one inch is 0.0254 meters 

 

1
2
3
4
5
6
pounds = eval(input("Enter weight in pounds: "))
inches = eval(input("Enter height in inches: "))
 
BMI = (pounds*0.45359237)/((inches*0.0254)**2)
 
print("BMI is ",round(BMI,4))
cs

*2.18 (Current time) Listing 2.7, ShowCurrentTime.py, gives a program that displays the current time in GMT. Revise the program so that it prompts the user to enter the time zone in hours away from (offset to) GMT and displays the time in the specified time zone.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import time
 
offset = eval(input("Enter the time zone offset to GMT: "))
 
currenttime = time.time()
 
totalseconds = int(currenttime)
currentsecond = totalseconds % 60 #
 
totalMinutes = totalseconds // 60
currentMinute = totalMinutes % 60
 
totalHours = totalMinutes // 60 
currentHour = totalHours % 24 
 
print("The current time is ",currentHour+offset,":",currentMinute,":",currentsecond)
cs

*2.19 (Financial application: calculate future investment value) Write a program that reads in an investment amount, the annual interest rate, and the number of years, and displays the future investment value using the following formula

 

 

For example, if you enter the amount 1000, an annual interest rate of 4.25%, and the number of years as 1, the future investment value is 1043.33.

 

1
2
3
4
5
6
7
8
9
amount = eval(input("Enter invest amount: "))
annualInter = eval(input("Enter annual interest rate: "))
years = eval(input("Ente number of years: "))
 
monthlyInter = annualInter/1200
numOfMonths = years * 12
futureValue = amount * ((1+monthlyInter)**numOfMonths)
 
print(round(futureValue,2))
cs

*2.20 (Financial application: calculate interest) If you know the balance and the annual percentage interest rate, you can compute the interest on the next monthly payment using the following formula:

 

 

Write a program that reads the balance and the annual percentage interest rate and displays the interest for the next month.

 

1
2
3
4
5
bal, annualInter = eval(input("Enter blance and interest rate(e.g. 3 for 3%): "))
 
interest = bal * (annualInter / 1200)
 
print("The interest is ", round(interest,5))
cs

 **2.21 (Financial application: compound value) Suppose you save $100 each month into a savings account with an annual interest rate of 5%. Therefore, the monthly interest rate is After the first month, the value in the account becomes

 

100 * (1 + 0.00417) = 100.417

 

After the second month, the value in the account becomes

 

(100 + 100.417) * (1 + 0.00417) = 201.252

 

After the third month, the value in the account becomes

 

(100 + 201.252) * (1 + 0.00417) = 302.507

and so on.

 

Write a program that prompts the user to enter a monthly saving amount and displays the account value after the sixth month.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
monthlySaving = eval(input("Enter the monthly saving amount: "))
 
amountSaving = 0
 
amountSaving += monthlySaving
amountSaving *=(1+0.00417)
 
amountSaving += monthlySaving
amountSaving *=(1+0.00417)
 
amountSaving += monthlySaving
amountSaving *=(1+0.00417)
 
amountSaving += monthlySaving
amountSaving *=(1+0.00417)
 
amountSaving += monthlySaving
amountSaving *=(1+0.00417)
 
amountSaving += monthlySaving
amountSaving *=(1+0.00417)
 
print(round(amountSaving,2))
cs

2.22 (Population projection) Rewrite Exercise 1.11 to prompt the user to enter the number of years and displays the population after that many years.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
years = eval(input("Enter the number of years: "))
 
currentPop = 312032486
oneBirthInSec = 7
oneDeathInSec = 13
oneImmiInSec = 45
secondInYear= 60 * 60 * 24 * 365;
 
numBirth = secondInYear / oneBirthInSec
numDeath = secondInYear / oneDeathInSec
numImmi = secondInYear / oneImmiInSec
 
#Year 1
currentPop += 5*(numBirth + numImmi - numDeath);
print("The population in ",years," years is", round(currentPop))
cs

2.23 (Turtle: draw four circles) Write a program that prompts the user to enter the radius and draws four circles in the center of the screen, as shown in Figure 2.4a.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import turtle as t
 
t.penup()
t.goto(-25,25)
t.pendown()
t.circle(25)
 
t.penup()
t.goto(25,25)
t.pendown()
t.circle(25)
 
t.penup()
t.goto(-25,-25)
t.pendown()
t.circle(25)
 
t.penup()
t.goto(25,-25)
t.pendown()
t.circle(25)
 
t.done()
cs
'

 2.24 (Turtle: draw four hexagons) Write a program that draws four hexagons in the center of the screen, as shown in Figure 2.4b.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import turtle as t
 
t.penup()
t.goto(-25,25)
t.pendown()
t.circle(25,steps=6)
 
t.penup()
t.goto(25,25)
t.pendown()
t.circle(25,steps=6)
 
t.penup()
t.goto(-25,-25)
t.pendown()
t.circle(25,steps=6)
 
t.penup()
t.goto(25,-25)
t.pendown()
t.circle(25,steps=6)
 
t.done()
cs


**2.25 (Turtle: draw a rectangle) Write a program that prompts the user to enter the center of a rectangle, width, and height, and displays the rectangle, as shown in Figure 2.4c. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import turtle as t
 
x,y,width,height = eval(input("Enter the centerPoint, width and hegiht of rectangle: "))
 
t.penup()
 
t.goto(x-(width//2), y+(height//2))
t.pendown()
t.goto(x+(width//2), y+(height//2))
t.goto(x+(width//2), y-(height//2))
t.goto(x-(width//2), y-(height//2))
t.goto(x-(width//2), y+(height//2))
 
t.done()
cs

**2.26 (Turtle: draw a circle) Write a program that prompts the user to enter the center and radius of a circle, and then displays the circle and its area, as shown in Figure 2.5. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import turtle as t
 
x,y,radius = eval(input("Enter the centerPoint and radius of circle: "))
 
area = radius * radius * 3.14159
 
t.penup()
t.goto(x,y)
t.write(round(area,2))
t.goto(x,y-radius)
t.pendown()
t.circle(radius)
 
t.done()
cs

 참고 문헌 : Introduction to Programming Using Python / Y.DANIEL LIANG



본 게시물은 개인적인 용도로 작성된 게시물입니다. 이후 포트폴리오로 사용될 정리 자료이니 불펌과 무단도용은 하지 말아주시고 개인 공부 목적으로만 이용해주시기 바랍니다.

 

 

'파이썬 > 예제' 카테고리의 다른 글

[파이썬]Chapter 6 예제 part 1 (Q.1 ~ Q.25)  (0) 2017.08.30
[파이썬]Chapter 5 예제  (0) 2017.08.16
[파이썬]Chater 4 예제  (0) 2017.07.26
[파이썬] Chapter 3 예제  (0) 2017.07.19
댓글