P ython p rogramming e xercises


Exercise #12: Smallest & Biggest



Yüklə 1,51 Mb.
Pdf görüntüsü
səhifə113/124
tarix14.05.2023
ölçüsü1,51 Mb.
#113537
1   ...   109   110   111   112   113   114   115   116   ...   124
PythonProgrammingExercisesGentlyExplained

Exercise #12: Smallest & Biggest 
def getSmallest(numbers): 
# If the numbers list is empty, return None: 
if len(numbers) == 0: 
return None 
# Create a variable that tracks the smallest value so far, and start 
# it off a the first value in the list: 
smallest = numbers[0] 
# Loop over each number in the numbers list: 
for number in numbers: 
# If the number is smaller than the current smallest value, make 
# it the new smallest value: 
if number < smallest: 
smallest = number 
# Return the smallest value found: 
return smallest 
Exercise #13: Sum & Product 
def calculateSum(numbers): 
# Start the sum result at 0: 
result = 0 
# Loop over all the numbers in the numbers parameter, and add them 
# to the running sum result: 
for number in numbers: 
result += number 
# Return the final sum result: 
return result 


Python Programming Exercises, Gently Explained 
139 
def calculateProduct(numbers): 
# Start the product result at 1: 
result = 1 
# Loop over all the numbers in the numbers parameter, and multiply 
# them by the running product result: 
for number in numbers: 
result *= number 
# Return the final product result: 
return result 
Exercise #14: Average 
def average(numbers): 
# Special case: If the numbers list is empty, return None: 
if len(numbers) == 0: 
return None 
# Start the total at 0: 
total = 0 
# Loop over each number in numbers: 
for number in numbers: 
# Add the number to the total: 
total += number 
# Get the average by dividing the total by how many numbers there are: 
return total / len(numbers) 

Yüklə 1,51 Mb.

Dostları ilə paylaş:
1   ...   109   110   111   112   113   114   115   116   ...   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