r/learnpython • u/Such-Pop8693 • 28d ago
For each character in name, print character
I am totally new to coding and working slowly through the course at futurecoder.io .
On the topic 'Introducing For Loops' we are asked to run the program:
name = 'World'
for character in name: print(character)I figured character might be some kind of term that python recognises and knows what to do with, like print. Colour me surprised when replacing character with kitten runs, and has the same output. I thought maybe number in place of character might not work, since the characters are all letters, but it works too.
Why is it so? What concept do I need to grasp here?
0
Upvotes
6
u/BluishMontoya 28d ago
You're just telling python "for each item in the variable 'name', assign that item to variable 'character' and run the code inside the loop". For strings, each item means each character.
20
u/Temporary_Pie2733 28d ago
It’s just a variable name. For loops are fancy assignment statements, and we pick relevant variable names to assign to for readability.
1
u/a18618 28d ago
That surprise hit me too the first time I swapped in a nonsense name and the loop just kept working, because the name is only a label you choose for each item as it comes around. One experiment that made it click for me was printing the loop variable after the loop finished, and seeing it still held the last letter, which showed me the loop was really just reassigning that label over and over. Have you tried swapping in a list of words instead of a single word, to see how the same label then holds a whole word each time?
3
u/cdcformatc 28d ago
it's just a variable name. just like how
nameis a variable, so ischaracter4
u/POGtastic itertools evangelist 28d ago
The Python interpreter does not care what you name your variables. You can name variables anything.
There are a tiny handful of keywords that are part of the Python language itself. Python cares about those. Every other word-looking thing in your program is a variable.
4
u/SamuliK96 28d ago
There technically is no concept, and you're just overthinking it. Python doesn't know the meaning of the words you might use in
for _ in x. In fact, it doesn't have to be a word at all. It doesn't even have to be letters. You don't even have to replace the_with anything, and it'll still work the same. When you use a for loop, you're naming a variable that changes value every iteration of the loop. And variable names don't have to be sensible words. Python doesn't care. It's just useful for humans.2
u/FreeLogicGate 28d ago edited 27d ago
Seems like you are pretty early on in the course, and while it's a fair question to ask yourself, you probably want to get some understanding of what a loop is, since the "for thing in things:" loop syntax is one of the fundamental Python language loop types.
In general, Python has a series of collection types, or functions that will provide a sequence.
for "loops" for every item in the collection or sequence. What is a little tricky here, is that Python, as is the case with many languages, can treat a "string" (ie. a word or series of words/characters) as if it was a collection of letters.
The loop in this case runs once for every character in the string. The code that runs each time in the loop, is the code (the instructions) that come after the ":" so one habit you want to get into is to indent the statements that are part of the loop, and don't put a statement on the same line. Your code works the same way if you write it this way:
So as you discovered, you supply the variable name that the for loop will use to copy the current element from the collection/array (which in this case is name).
This is why you get each letter from the string "World" printed on a line.
1
u/pythonwiz 28d ago
Strings in Python are iterable like lists or tuples, each element in a string is a string containing a character. Many languages have similar strings, for example in C a string is just a const array of char values ending in a null character.
1
u/Classic-Rate-5104 28d ago
These statements simply mean: create a variable with name "name" and value "World", and a variable with name "character" and let it loop over all characters in the variable named "name". The naming of the variables very arbitrary but a bit stupid and confusing in the example
1
u/Educational_Virus672 28d ago
the thing that "character" term is just a variable(a name for value) you can change it anything because a for loop just takes items(aka letters here) one by one it doesnt look what that "char" means which is its point so changing to anything
1
u/Careless-Web-6280 26d ago
I encourage you to know the list of keywords
0
u/DimensionMost8342 28d ago
character isn't a Python term, it's just the name you picked, which is why number and kitten worked too. In for character in name:, Python walks the string one character at a time and binds each one to whatever name follows the for:
0
u/North_South-West 28d ago edited 28d ago
You are assigning a variable name when you write a for loop like this and you can name it anything you want as long as it follows the regular naming rules.
A lot of people just make it a single letter like i or x. Makes code shorter and sometimes the name of a variable like this isnt too important.
If its an important variable name then name after the item you are iterating with the loop. In your example you could go-
for letter in name: print(letter)
0
u/JamzTyson 28d ago
It is considered good style in Python to use meaningful names. Hence rather than:
we would commonly use "character" or "ch" or anything that's more meaningful than "i". Whatever we name it, it is a temporary variable that takes the value of the next item from the iterable "name".
0
u/Rezrex91 28d ago
Okay, many people already explained the gist of this, so I'll go a bit more in depth, so you know how this behavior came to be.
In earlier, lower level languages, like in C, these "iterable" types didn't exist by default. If you wanted some more complex data structures, you needed to construct them using typedef, and if these data structures had special operations that would be done to them, you needed to write it as separate functions. Like you could construct a special
structthat has a key and a value variable in it, and name itdictto have a dictionary, but then you'd need to make functions likedict_append()to tell the computer how to do that operation on your dictionary type. But I digress. C also had strings, but unlike in Python, it was a low level construct, a simple data type, that was implemented as an array of characters with a NULL character at it's end as terminator, then they slapped on some minimal syntactic sugar to make it easier to declare new strings and to print a string, and they called it a day.Now, with OOP (and AFAIK with FP) languages came the concept of "iterable" types. Most of these are complex data structures (not all, because an array still matches the definition of an iterable type, as does the string, but it's debatable whether a string is a simple or complex data structure), wich are mostly implemented as classes in OOP languages. Classes are basically structs which also have the functions (methods) that are needed to handle them encapsulated in them along with the fields of data. So you don't do
dict_append(my_dict, key, value)anymore but something likemy_dict.append(key, value)This is also very good from the standpoint, that most of the iterables are complex types, so even declaring a new one is something that needs processing in the background. Now, the iterable types don't just have their "data", they also have an indexing method (the iterator) and they always know their own length too (unlike a basic C array for example.) Iterable types, as others have explained already, are always some type of collections in the sense that they are made up of individual items that can be served up one-by-one if we chose instead of as a whole. For strings, these individual items are the letters of the string, for lists they will be the list items, for dicts it the key-value pairs, etc.
Now, some languages, mainly C derived ones which want to preserve the old C style for loops for the purpose of backwards compatibility and familiarity, implement a new type of for loop, often called
foreachto make stepping through these iterable types easier. The foreach loop is different from the for loop by actually knowing that it will get an iterable object (since iterables are implemented as classes, all variables of an iterable type are actually new object instances of that class), which will in it have an iterator method which will tell do the stepping through, so it just needs to call this method over and over until the object tells it that the end is reached, no more iterations are possible.Python is different only in the sense that they implemented the basic for loop to do the work of a foreach loop depending on how you write that for loop. Well, actually the Python for loop is always a foreach loop, even when using an index and a range, or an index and enumerate(), because both the range and the enumerate functions return an iterable object for the for loop to loop through. As a matter of fact, if you visit the Python documentation, you won't really find the "for loop", but the "for statement", which is "used to iterate over the elements of a sequence [...] or other iterable object." So Python doesn't really have a for loop in the traditional meaning, instead it has the foreach renamed as for, and we're working around this with the range() and enumerate() functions to mimic how a classic for loop works when that's what we need.