Python Forum
John Guttag Book - Finger Exercise 3 - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: Code sharing (https://python-forum.io/forum-5.html)
+--- Thread: John Guttag Book - Finger Exercise 3 (/thread-7910.html)



John Guttag Book - Finger Exercise 3 - pritesh - Jan-29-2018

Hi,
Uploading my way of solving the 3rd Finger Exercise from John Guttag's book.

Not as tough as Finger Exercise for 2 though.

#"Introduction to Computation and Programming Using Python: \
#With Application to Understanding Data (MIT Press) 2nd , Kindle Edition" 
#by John Guttag

#       Finger Exercise 3:
#       Replace the comment in the following code with a while loop
#       numXs = int(input('How many times should I print the letter X? '))
#       toPrint = ''
#       #concatenate X to toPrint numXs times
#       print (toPrint)

numXs = int( input("How many times should I print the letter X? ") )
toPrint = ''
if numXs < 1:
    print ("Value of numXs is less than or equal to zero")
else:
    while numXs > 0:
      toPrint = toPrint + "x"
      numXs = numXs -1
    print(toPrint)


#Another way to do it, is convert numXs to absolute value.
#numXs = int( (input("How many times should I print the letter X? ") ) )
#toPrint = ''
#if numXs == 0:
#    print ("Are you sure??")
#if numXs < 0 :
#    print ("Value of numXs is less than zero. Converting ", numXs, " to " , abs(numXs) )
#    numXs = abs(numXs)
#
#    while numXs > 0:
#      toPrint = toPrint + "x"
#      numXs = numXs -1
#    print(toPrint)

#One more way to do it is to initialize numXs to absolute value.
#numXs = abs (int( input("How many times should I print the letter X? ") ) )
#print ("Note: Negative numbers will be converted to absolute value")
#toPrint = ''
#while numXs > 0:
#    toPrint = toPrint + "x"
#    numXs = numXs -1
#print(toPrint)
#



RE: John Guttag Book - Finger Exercise 3 - Larz60+ - Jan-29-2018

I am familiar with this guy's work. He's a prof at MIT, assistant head of Computer Science and Artificial Intelligence Laboratory's Networks and Mobile Systems Group.
Not familiar with the book, but sounds like fun.


RE: John Guttag Book - Finger Exercise 3 - pritesh - Jan-29-2018

Hi Larz60+,
Thanks for the reply. Yes, it's quite an interesting book. Especially for me, who has done some Perl scripting in the past, is aware of the basics such as list, hashes, perl map and grep etc and is looking forward to learn Python.


RE: John Guttag Book - Finger Exercise 3 - collectorKim - Aug-15-2018

Hello pritesh,

I've purchased the book couple of days ago so can be prepared for my Mathematics and Computer Science course starting from September / October.

Thought I'd share my method!

numXs = int(input('How many times should I print the letter X?\n'))
counter = 0
toPrint = ''

while counter < numXs:
    toPrint += 'X'
    counter += 1
    
print(toPrint)
I used a counter instead of changing the value of numXs.