Write a program that allows the user to enter a nonnegative integer $k$ and returns the sum of the first $k$ perfect squares, $$\sum_1^k{k^2}.$$ For example, if $k=4$ the sum should be $1^2 + 2^2 + 3^2 + 4^2 = 1 + 4 + 9 + 16 = 30$. A sample execution might appear as
Enter k: 4 30
Solution:
k = int(input('Enter k: '))
total = 0
for j in range(1, k+1):
total += j*j
print(total)
Ask the user for a word and then output the following pattern.
Enter word: example e ex exa exam examp exampl example
Our first solution is an index-based loop which uses the index value to create an appropriate slice.
word = input('Enter a word: ')
for k in range(len(word)):
print(word[ :1+k])
An alternative approach uses the more traditional loop over characters of the string, while maintaining a buffer that includes all characters seen thus far (and thus those that should be printed on the current line).
buffer = ''
word = input('Enter a word: ')
for c in word:
buffer += c # add new character to the line
print(buffer)