Python Forum

Full Version: what does x reprsent in this code ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2 3
thisset = {"apple", "banana", "cherry"}

for x in thisset:
  print(x)
x basically represents all the items in the set, and prints them out.
but the thing is i can change it to anything...i can even call it 'you' or 'she'...and it will act on it in the same way - the set it still being printed...
yes, x is variable, or name as we call them in python.
you iterate over a set in the for loop and in each iteration x takes the value from the set
okay, got it !
thanks !
Yes the loop variable can be called whatever you want.
The only job it has is to take on the value of the next element in iterable each time through the loop.

A general rule if the iterable data collection has some stuff that can be given useful loop variable name,then do that.
>>> colors = ['Red', 'Blue', 'Green']
>>> for color in colors:
...     print(color)
...     
Red
Blue
Green
Is clearer than.
>>> colors = ['Red', 'Blue', 'Green']
>>> for rubberduck in colors:
...     print(rubberduck)    
...     
Red
Blue
Green
thank you too !
certainly that is a better habit...

pyzyx3qwerty thank you !
another one which is simple, but i'm trying to understand the underlying theme...
how can this function be defined with 'food' and when it is called it is given the list argument ?

def my_function(food):
  for x in food:
    print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)
in the function definition (line 1) food is a parameter.
when you call the function on line 7, you pass fruits as arguments to the function. That is the actual value of food in this particular call of the function.
There are positional and keyword parameters/arguments. check the links for more details. In this case food is positional parameter.

read our tutorial on functions: https://python-forum.io/Thread-Basic-Functions
also glossary for parameters and arguments
food is one of the things defined under the function. You will frequently see that as you go through functions.
So, for example:
def abc(name):
   print(name)
In the above lines, name is one of the parameters. Now,
n = "pyzyx3qwerty"
abc(n)
in the above lines, it will n out because n represents name in the lines
Pages: 1 2 3