I am trying to split my students according to their names using python. If it has its letter from a to m it goes to group 1 and if it is between na to z to group 2 When I run the following script I get the option that it is always in group 2, when its name starts with A
variable_num =[]
for i in range(ord('a'), ord('m')+1):
variable_num.append(chr(i))
variable_num=str(variable_num)
nombre_alumno = input('Nombre del alumno:')
nombre_alumno_letra = str(nombre_alumno[0:1])
if nombre_alumno_letra == variable_num:
nom_alumno = 'Grupo 1'
else:
nom_alumno = 'Grupo 2''
What am I doing wrong? Thanks in advance.
The simple version of your code:
To remove the first character of the name, just use
nombre_alumno[0]
. You also have to convert it to lowercase to compare it with the letters of the first group: you don't know how they will enter it.Just to expand the answer I point out the errors and why:
1.
This in itself is two errors: First it is unnecessary to call
str()
becausechr()
it already returns a value of type str, and second is that itvariable_num=str(variable_num)
converts the variable of type list to a variable of type tuple, which causes a type errorAttributeError: 'str' object has no attribute 'append'
in the next loop of the for because the variablevariable_num
is no longer a list but a tuple of type "str" and the tuples are immutable, that is, once created you can no longer modify or extend them (you can't do.append()
).two.
You use the variable
nom_alumno
but it's not declared outside the loop nor do you return it in any way so you're really just overwriting it over and over again with the text "Group 1" and "Group 2" (with the detail that you may have missed a double quote at the end of 'Group 2'') and when the loop ends all local variables within the loopfor
are gone and cannot be reclaimed later.3.
It is also unnecessary to use
str()
because the output ofinput()
is already of type "str"There are more appreciations but they are above all conceptual and idiomatic than syntax errors. I hope this helps you, greetings.