Write a program that takes in a string input of names and returns an email address. For names with both letters and alphabets, end with
@yahoo.com
. For names that have only alphabets, return with@gmail.com
My code:
names = input().split()
ending_g = '@gmail.com'
ending_y = '@yahoo.com'
for i in range(len(names)): [MY QUESTION PERTAINS TO THIS LINE]
if names[i].isalpha() == True:
print(names[i],ending_g)
else:
print(names[i],ending_y)
For the for
loop, when I have it like that it works fine. 1) Why doesn't work when I have it as for I in (names):
?
The error it returns is that list indices must be integers or slices, not str
. I thought that using .split()
puts each element into the list with its own index value.
- is the extra
range(len)
only necessary when the input is a string? Because when an input is a string getting converted into a float (example below) it works properly.
ex:
for i in score():
scores[i] = float(scores[i])
CodePudding user response:
In Python, there's usually no need for explicit indexing of iterables. So don't use an index variable. You can just do
names = input().split()
ending_g = '@gmail.com'
ending_y = '@yahoo.com'
for n in names:
addr = n (ending_g if n.isalpha() else ending_y)
print(addr)
CodePudding user response:
In for name in names:
- name
is NOT an integer number - and indexes into lists mus be integers - that is exactly what the error tells you ... name
is one of your strings:
names = "A B C2 42".split()
for name in names:
if name.isalpha():
print(name, ".alpha", sep = "")
else:
print(name, ".number", sep = "")
Output:
A.alpha
B.alpha
C2.number
42.number
Treating a string as an index is what produces your error:
names = "A B C".split()
for name in names:
if names[name].isalpha(): # makes no sense as name is not an index
print(name, ".alpha", sep="")
Exception has occurred: TypeError list indices must be integers or slices, not str File "whatever", line 4, in <module> if names[name].isalpha() == True: