P ython p rogramming e xercises



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

Exercise #7: ASCII Table 
def printASCIITable(): 
# Loop over integers 32 up to and including 126: 
for i in range(32, 127): 
# Print the integer and its ASCII text character: 
print(i, chr(i)) 
printASCIITable() 
Exercise #8: Read Write File 
def writeToFile(filename, text): 
# Open the file in write mode: 
with open(filename, 'w') as fileObj: 
# Write the text to the file: 
fileObj.write(text) 
def appendToFile(filename, text): 
# Open the file in append mode: 
with open(filename, 'a') as fileObj: 
# Write the text to the end of the file: 
fileObj.write(text) 
def readFromFile(filename): 
# Open the file in read mode: 
with open(filename) as fileObj: 
# Read all of the text in the file and return it as a string: 
return fileObj.read() 
Exercise #9: Chess Square Color 
def getChessSquareColor(column, row): 
# If the column and row is out of bounds, return a blank string: 
if column < 1 or column > 8 or row < 1 or row > 8: 
return '' 


Python Programming Exercises, Gently Explained 
137 
# If the even/oddness of the column and row match, return 'white': 
if column % 2 == row % 2: 
return 'white' 
# If they don't match, then return 'black': 
else: 
return 'black' 
Here is a second solution: 
def getChessSquareColor(column, row): 
# If the column and row is out of bounds, return a blank string: 
if column < 1 or column > 8 or row < 1 or row > 8: 
return '' 
# If the even/oddness of the column and row match, return 'white': 
if not (column % 2 ^ row % 2): 
return 'white' 
# If they don't match, then return 'black': 
else: 
return 'black' 

Yüklə 1,51 Mb.

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




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

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin