P ython p rogramming e xercises



Yüklə 1,51 Mb.
Pdf görüntüsü
səhifə118/124
tarix14.05.2023
ölçüsü1,51 Mb.
#113537
1   ...   114   115   116   117   118   119   120   121   ...   124
PythonProgrammingExercisesGentlyExplained

Exercise #26: Handshakes 
def printHandshakes(people): 
# The total number of handshakes starts at 0: 
numberOfHandshakes = 0 
# Loop over every index in the people list except the last: 
for i in range(len(people) - 1): 
# Loop over every index in the people list after index i: 
for j in range(i + 1, len(people)): 
# Print a handshake between the people at index i and j: 
print(people[i], 'shakes hands with', people[j]) 
# Increment the total number of handshakes: 
numberOfHandshakes += 1 
# Return the total number of handshakes: 
return numberOfHandshakes 
Exercise #27: Rectangle Drawing 
def drawRectangle(width, height): 
# Special case: If width or height is less than 1, draw nothing: 
if width < 1 or height < 1: 
return 
# Loop over each row: 
for row in range(height): 
# Loop over each column in this row: 
for column in range(width): 
# Print a hashtag: 
print('#', end='') 
# At the end of the row, print a newline: 
print() 
Exercise #28: Border Drawing 
def drawBorder(width, height): 
# Special case: If the width or height is less than two, draw nothing: 
if width < 2 or height < 2: 
return 
# Print the top row: 
print('+' + ('-' * (width - 2)) + '+') 
# Loop for each row (except the top and bottom): 


Python Programming Exercises, Gently Explained 
145 
for i in range(height - 2): 
# Print the sides: 
print('|' + (' ' * (width - 2)) + '|') 
# Print the bottom row: 
print('+' + ('-' * (width - 2)) + '+') 
Exercise #29: Pyramid Drawing 
def drawPyramid(height): 
# Loop over each row from 0 up to height: 
for rowNumber in range(height): 
# Create a string of spaces for the left side of the pyramid: 
leftSideSpaces = ' ' * (height - (rowNumber + 1)) 
# Create the string of hashtags for this row of the pyramid: 
pyramidRow = '#' * (rowNumber * 2 + 1) 
# Print the left side spaces and the row of the pyramid: 
print(leftSideSpaces + pyramidRow) 

Yüklə 1,51 Mb.

Dostları ilə paylaş:
1   ...   114   115   116   117   118   119   120   121   ...   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