Home > other >  Simple for loop to guess variable name in python
Simple for loop to guess variable name in python

Time:10-06

I am new to python (coming from R) and trying to practice for loops, so I made up this challenge to have the computer guess the name string. Unfortunately I have stumped myself. Can anyone offer assistance?

## Guess a name

name = 'Kate'
char = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRZTUVWXYZ'

for k in range(len(name)):
 for i in range(len(char)):
  if name[k] == char[i]:
     print('Your name is '   char[i])

This gives the following output:

Your name is K
Your name is a
Your name is t
Your name is e

But I am looking for:

Your name is Kate

CodePudding user response:

the print() call is called every time a character is guessed correctly.
to fix this, I would move the print("Your name is"...) function outside of the for loops. Python also has a way of changing how print() ends its lines.

...
print("Your name is ", end="")
for k in range(len(name)):
 for i in range(len(char)):
  if name[k] == char[i]:
     print(char[i], end="")
  • Related