P ython p rogramming e xercises


A P P E N D I X A : S O L U T I O N S



Yüklə 1,51 Mb.
Pdf görüntüsü
səhifə109/124
tarix14.05.2023
ölçüsü1,51 Mb.
#113537
1   ...   105   106   107   108   109   110   111   112   ...   124
PythonProgrammingExercisesGentlyExplained

A P P E N D I X A : S O L U T I O N S
As long as your programs pass all the assert statements or match the output given in the 
exercise, they don’t have to be identical to my solutions. There’s always several ways to write code. 
This appendix contains the complete solutions that were partially given in the Solution Template 
sections of each exercise. 
I highly recommend attempting to solve these exercises on your own instead of immediately 
jumping to these solutions, even if you have to struggle with them for a while. More important than 
the knowledge of these solutions is the practice that attempting to solve them gives you. However, if 
you feel stuck and cannot move on, reading the solution program for an exercise can give you insights 
for how to solve the other exercises in this book. 
Exercise #1: Hello, World! 
# Print "Hello, world!" on the screen: 
print('Hello, world!') 
# Ask the user for their name: 
print('What is your name?') 
# Get the user's name from their keyboard input: 
name = input() 
# Greet the user by their name: 
print('Hello, ' + name) 
Exercise #2: Temperature Conversion 
def convertToFahrenheit(degreesCelsius): 
# Calculate and return the degrees Fahrenheit: 
return degreesCelsius * (9 / 5) + 32 
def convertToCelsius(degreesFahrenheit): 
# Calculate and return the degrees Celsius: 
return (degreesFahrenheit - 32) * (5 / 9) 
Exercise #3: Odd & Even 
def isOdd(number): 
# Return whether number mod 2 is 1: 
return number % 2 == 1 
def isEven(number): 
# Return whether number mod 2 is 0: 
return number % 2 == 0 


Python Programming Exercises, Gently Explained 
135 
Exercise #4: Area & Volume 
def area(length, width): 
# Return the product of the length and width: 
return length * width 
def perimeter(length, width): 
# Return the sum of the length twice and the width twice: 
return length * 2 + width * 2 
def volume(length, width, height): 
# Return the product of the length, width, and height: 
return length * width * height 
def surfaceArea(length, width, height): 
# Return the sum of the area of each of the six sides: 
return ((length * width) + (length * height) + (width * height)) * 2 

Yüklə 1,51 Mb.

Dostları ilə paylaş:
1   ...   105   106   107   108   109   110   111   112   ...   124




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin