Python lists and operators - python

From Learn Python the Hard Way:
Python sees you mentioned mystuff and looks up that variable. It might have to look backwards to see if you created with =, look and see if it is a function argument, or maybe it's a global variable. Either way it has to find the mystuff first.
Once it finds mystuff it then hits the . (period) operator and starts
to look at variables that are a part of mystuff. Since mystuff is a
list, it knows that mystuff has a bunch of functions.
It then hits append and compares the name "append" to all the ones
that mystuff says it owns. If append is in there (it is) then it grabs
that to use. Next Python sees the ( (parenthesis) and realizes, "Oh
hey, this should be a function." At this point it calls (aka runs,
executes) the function just like normally, but instead it calls the
function with an extra argument.
That extra argument is ... mystuff! I know, weird right? But that's
how Python works so it's best to just remember it and assume that's
alright. What happens then, at the end of all this is a function call
that looks like: append(mystuff, 'hello') instead of what you read
which is mystuff.append('hello').
Where does he get "mystuff" from? And I'm still unsure about how that period operator thing works (sorry I'm new at this please bear with me), later on we get this:
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print "Wait there's not 10 things in that list, let's fix that."
stuff = ten_things.split(' ')
I don't see how that string becomes a list after the last line, does the .split automatically turn it into one or what? What is the name of that period "split" or "append" thing he's doing? One of the main things screwing me up in programming is that I don't know what a lot of things are actually called. I know functions, variables, etc but some stuff like that .split just confuse me.
Help?

stuff = ten_things.split(' ') doesn't change the value of ten_things. Instead, it creates a new variable named stuff and saves the list created by ten_things.split(' ') to it. The space passed as an argument to the split method here is significant. What it is saying is that Python should take the string ten_things and split it up, using splits argument as a delimiter.
Example:
"This is a string".split(' ') == ["This", "is", "a", "string"]
or
"This|is|a|string".split('|') == ["This", "is", "a", "string"]

Regarding “Where does he get "mystuff" from?”, mystuff is an object of some kind, and there are methods or functions among the object's attribute values (or among the attribute values of its class). The dot (period) is a qualifier operator; for example, mystuff.append qualifies or identifies the relevant append function to be the one associated with object mystuff. Object methods typically have an implicit argument (often called self) as the first argument, and that argument is made equal to the object the method belongs to. In this case, that's mystuff.
As mentioned in a previous answer, split splits a string and returns a list. For more information, also see tutorialspoint regarding split:
The method split() returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num. ... Following is the syntax for split() method: str.split(str="", num=string.count(str)).

Related

Why should I set a function list argument as empty or none instead of using a normal variable

I've been looking up the information about why people should not use empty list as a function argument and pass none type as an argument and came up with a few questions.
Here is my code:
def add_employee(emp, emp_list=None):
if emp_list is None:
emp_list = []
emp_list.append(emp)
print(emp_list)
And here is code without second argument's type specified:
def add_employee(emp, emp_list):
emp_list.append(emp)
return emp_list
When I do not define emp_list as an empty list or none I can not utilize function's deafualt argument behavior: I can't call it like add_employee('Mark'), I had to add second variable to pass. Why is it good to have that backup default behaviour? Why couldn't I just leave it as emp_list.
Here is a great explanation of why you should avoid using mutable arguments in your defaults. Or at least use them sparingly: link
The general gist of it that the list will be created for the first time (in a location in memory) when you define the function. So as python reads the code and interprets it, you will end up creating that list once on the first 'read' of the function.
What this means is that you are not creating a fresh list each time you call that function, only when you define it.
To illustrate I will use the example from the link I shared above:
def some_func(default_arg=[]):
default_arg.append("some_string")
return default_arg
>>> some_func()
['some_string']
>>> some_func()
['some_string', 'some_string']
>>> some_func([])
['some_string']
>>> some_func()
['some_string', 'some_string', 'some_string']
If I understood your question correctly, you are asking why you're better off defining the emp_list explicitly rather than having it outside the function. In my mind it boils down to encapsulation. You're essentially trying to make sure that your function doesn't change the behavior of anything outside of its scope so you're forced to pass it things directly and be explicit. In practice if you have a variable outside of the scope named emp_list, it is absolutely fine to just append to it as long as you understand what the expected behavior is.
If you pass a list in the first bit of code as the emp_list, then the variable emp_list will contain your list a. The if statement will check if list a is None and since that check fails, it will skip the next line of assigning it a fresh empty list.

How can I avoid retyping long variable names in calling functions

How can I avoid lines like:
this_long_variable_name = this_long_variable_name.replace('a', 'b')
I thought I could avoid it by making a function, repl,
def repl(myfind, myreplace, s):
s = s.replace(myfind, myreplace)
print(s) # for testing purposes
return s
but because of stuff about the local vs. global namespaces that I don't understand, I can't get the function to return a changed value for this_long_variable_name. Here's what I've tried:
this_long_variable_name = 'abbbc'
repl('b', 'x', this_long_variable_name)
print('after call to repl, this_long_variable_name =', this_long_variable_name)
The internal print statement shows the expected: axxxc
The print statement after the call to repl show the unchanged: abbbbc
Of course, it works if I give up and accept the redundant typing:
this_long_variable_name = repl('b', 'x', this_long_variable_name)
BTW, it's not just about the length of what has to be retyped, even if the variable's name were 'a,' I would not like retyping a = a.replace(...)
Since in the function s is a parameter, I can't do:
global s
I even tried:
this_long_variable_name.repl('b', 'x')
which shows you both how little I understand and how desperate I am.
The issue you're running into is that Python strings are immutable. str.replace() returns an entirely new string, so in s = s.replace(myfind, myreplace), the name s no longer refers to the original string, which is why you don't see any change on the outside of the function's namespace.
There probably isn't a great solution to your problem. I recommend using a modern IDE or Python REPL with autocompletion to alleviate it. Trying to abuse the standard way of writing things like this may feel good to you, but it will confuse anyone else looking at your code.
Harry it does not work because inside your repl function you actually have a local copy of the content of your this_long_variable_name. This is called "pass by copy" which means python hands over a copy to the function. Unfortunately this is how python does it. Check also here:
Python: How do I pass a string by reference?
Also strings are immutable in python so if you wanna change them you always create a new modified version. Check here:
Aren't Python strings immutable?
Question would be why should you need long variable names in the first place?

Why can't I "string".print()?

My understanding of the print() in both Python and Ruby (and other languages) is that it is a method on a string (or other types). Because it is so commonly used the syntax:
print "hi"
works.
So why doesn't "hi".print() in Python or "hi".print in Ruby work?
When you do something like "hi".print(), you are implying that the string object "hi" has a method print. This is not the case. Instead, print is a function that takes a string (or other types) as input.
Ruby does have a method Object#display (doc here), which sends a representation of the object to the current output stream, or one specified as an argument.
(I find that it's hard to work with in irb if I use ; at the end of a line to suppress the printing of the return value; if I do that, display's output isn't shown, even if I flush the stream.)
It's not a method on a string. Prior to Python 3, it was a statement (just like break or import), and you could use both print "hi" and print("hi"). From Python 3, it was replaced by a function, thus you can no longer use print "hi":
Print Is A Function
The print statement has been replaced with a
print() function, with keyword arguments to replace most of the
special syntax of the old print statement (PEP 3105).
Why should it work? String classes rarely have void print methods - and you would never need them, because the standard static print function can print those strings anyway. It is important to note: method(someObject) is not necessarily the same as someObject.method().
What do you propose str.print should do?
print to stdout? how about stderr? or a file? or a serial port?
Printing to stdout is really a special case but it's so ubiquitous that sometimes it can be overlooked.
Then we'd have to specify where str should print to every time we create a string?
At the very least we'd have to say
"foo".print(sys.stdout)
Hopefully that looks awful to you too. It's a confusion of responsibilities
print isn't a method on a string in Python (or in Ruby, I believe). It's a statement (in Python 3 it's a global function). Why? For one, not everything you can print is a string. How about print 2?
In case you are more happy to use a method rather than a statement in Ruby you can use the method display ("test".display) to achieve this or define a new method easily like
class String
def print
puts self
end
end
and use it like this
"test".print

Python Parameters (beginner)

I need help with parameteres. Do both of these function definitions do the exact same thing for print_twice?
def print_twice(lol):
print lol
print lol
def print_twice(michael):
print michael
print michael
If yes, then I'm guessing the word used for the parameter doesn't matter, correct?
The word we use for the parameter does matter. It is important that the word you use:
is meaningful and clearly explains what the argument is for,
does not override some variable name from the external scope.
Importance of meaningful arguments' names
The name you use for argument is important, because the names of the arguments, their default values and the function name are the things developers using your function first see, even without the need to look into function documentation (eg. by using help(your_function)). Just use IDLE to define your function and then try to use it - when writing it, the IDLE will show you possible arguments.
So please, give them meaningful names that will make using your function easier and will not require looking into the documentation.
Overriding variables from outer scopes
When it comes to the second point, just look at this example:
def show_elements(elements):
"""Shows elements of the passed argument
"""
for element in elements:
print element
which works ok, but if you replace elements with eg. list, you will override list within this specific scope:
def show_elements(list):
"""Shows elements of the passed argument
"""
for element in list:
print element
and then if you would like to use list eg. for building a list, or converting from other type into list, then you will have problems. list is a builtin and you should not override it. Similar is true also about the other variables from the scopes surrounding the function.
Historically, when Python was resolving variable names by first looking into local scope, then global and builtin scopes, skipping all nonlocal ones (eg. scope from the function in which our function was defined), enclosing scope's variables were passed that way:
def funca():
local_val1 = 'some value1'
local_val2 = 'some value2'
def funcb(local_val1=local_val1):
# local_val1 is accessible here, even though local_val2 is not
...
...
But since the above is no longer true, you will need to take surrounding scopes into account, thus using non-conflicting name is important.
Yes they do. The name of a parameter is irrelevant, although good programming practices mandate that the name should be clear and self-explanatory
That's correct, the name of the parameter doesn't matter.
yes that is correct its just a variable name ...
That is correct. The word used for the parameter in the function definition is only a name, and does not refer to anything external.
Programming is supposed to be logical. So, let's think logically. If you write "a" on a paper twice, you get "a" two times. Same with "b." So you're doing the same function with letters. But what if you reassigned a value to a, each time a went through the function. I mean, what if a was a number, then IMO the closest you could get is something like this:
def func1(a, b):
a = input("Enter a number: ")
b = input("Enter another number: ")
b *= b
a *= a
print func1(a)
print func1(a)
print func1(b)
print func1(b)
Now, when I try to compile this specific code online, I get an error but I think something like this will work for the sake of trying to do what you're doing if done correctly? It's a good experiment, and I would imagine some usage in it.

Python arguments- how do you use them? [duplicate]

What are [function] arguments? What are they used for?
I started learning Python very recently; I'm new to programming and I apologize for this basic question.
In every Python tutorial I go through they talk about arguments. I have looked for the answer to this question and have found many answers but they are just a little too hard for me to understatnd. I may just be missing some conceptual background.
So... when I define a function, what are the things in parenthesis used for?
Example:
def hi( This is the part that i dont get):
print 'hi'
Edit:
Two follow-up questions related to this one were later closed and merged here, hence the partial out-of-context trait of some of the answers.
The follow-up questions were: [paraphrased]
Can arguments only be used for input ?
what are other examples of the use of arguments ?
Why use arguments, rather than having the function call raw_input ?
Why is the concept of argument passing described as such a powerful thing? it seems to me we're merely using them to replace stuff the user could have type on the keyboard.
In a few words, they're data that gets "passed into" the function to tell it what to do. Wikipedia has details.
http://en.wikipedia.org/wiki/Function_argument
For instance, your hi() function might need to know who to say hello to:
def hi(person):
print "Hi there " + person + ", how are you?"
Or a mathematical function might need a value to operate on:
def square(x):
return x * x
This is not a Python question, but rather a generic programming question. A very basic one.
Before answering the question about arguments, and in view of the other questions you asked, it is useful to discuss the concept of variables.
A variable is a named piece of memory where information of interest to the underlying program can be stored and retrieved. In other words, it is a symbolic name, chosen by the programmer, that is associated to its contents. Using various language constructs generally known as assignments, the programmer can read or write the contents of a variable.
It is important to note that the value (i.e. the content) of a variable needn't be defined when the program is written. It is only necessary at run-time. This allows the program to describe actions to be performed on symbolic elements without knowing exactly the value these elements have. Consider this snippet, part of a bigger program:
# ... some logic above
ball_volume = 4.0 / 3 * math.pi * ball_radius
if ball_volume > 200:
print ("Man, that's a big ball")
# ... more logic below
At the time the program is written one doesn't need to know the actual value of ball_radius; yet, with the assumption that this variable will contain the numeric value of some hypothetical ball, the snippet is capable of describing how to compute the ball's volume. In this fashion, when the program is running, and somehow (more on this later) the ball_radius variable has been initialized with some appropriate value, the variable ball_volume can too be initialized and used, here in the conditional statement (if), and possibly below. (At some point the variable may go out-of-scope, but this concept which controls when particular variables are accessible to the program is well beyond this primer).
In some languages the type of data that may be associated with a particular variable needs to be explicitly defined and cannot change. For example some variables could hold only integer values, other variables string values (text) etc. In Python there is no such restriction, a variable can be assigned and re-assigned to any type of data, but of course, the programmer needs to keep track of this for example to avoid passing some text data to a mathematical function.
The data stored inside variable may come from very different sources. Many of the examples provided in tutorials and introductory documentation have this data coming from keyboard input (as when using raw_input as mentioned in some of your questions). That is because it allows interactive tests by the people trying out these tutorial snippets. But the usefulness of programs would be rather limited if variables only get their data from interactive user input. There are many other sources and this is what makes programming so powerful: variables can be initialized with data from:
databases
text files or files various text-base formats (XML, JSON, CSV..)
binary files with various formats
internet connections
physical devices: cameras, temperature sensors...
In a nutshell, Arguments, also called Parameters, are variables passed to the function which [typically] are used to provide different output and behavior from the function. For example:
>>> def say_hello(my_name):
... print("Hello,", my_name, "!")
>>> say_hello("Sam")
Hello, Sam !
>>> customer_name = "Mr Peter Clark" #imagine this info came from a database
>>> # ...
>>> say_hello(customer_name)
Hello, Mr Peter Clark !
>>>
In the example above, my_name is just like any local variable of the say_hello function; this allows the function to define what it will do with the underlying value when the function is called, at run-time.
At run-time, the function can be called with an immediate value (a value that is "hard-coded" in the logic, such as "Sam" in the example), or with [the value of] another variable (such as customer_name). In both cases the value of the function's my_name variable gets assigned some value, "Sam" and "Mr Peter Clark" respectively. In the latter case, this value is whatever the customer_name variable contains. Note that the names of the variables used inside the function (my_name) and when the function is called (customer_name) do not need to be the same. (these are called the "formal parameter(s)" and the "actual parameters" respectively)
Note that while typically most arguments as passed as input to a function, in some conditions, they can be used as output, i.e. to provide new/modified values at the level of the logic which called the function. Doing so requires using, implicitly or explicitly, the proper calling convention specification (See Argument passing conventions below)
Now... beyond this very basic understanding of the purpose of parameters, things get a little more complicated than that (but not much). I'll discuss these additional concepts in general and illustrate them as they apply to Python.
Default values for arguments (aka "optional" arguments)
When the function is declared it may specify the default value for some parameters. These values are used for the parameters which are not specified when the function is called. For obvious reasons these optional parameters are found at the end of the parameter list (otherwise the language compiler/interpreter may have difficulty figuring out which parameter is which...)
>>> def say_hello(dude = "Sir"):
... print("Hello,", dude, "!")
...
>>> say_hello()
Hello, Sir !
>>> say_hello("William Gates")
Hello, Bill ! #just kidding ;-)
Hello, William Gates ! # but indeed. works as the original function when param
# is specified
Variable number of parameters
In some cases it may be handy to define a function so that it may accept a variable number of parameters. While such lists of parameter values ultimately get passed in some kind of container (list, array, collection...) various languages offers convenient ways of accessing such parameter values.
>>> def add_many(operand1, *operands):
... Sum = operand1
... for op in operands:
... Sum += op
... return Sum
...
>>> add_many(1, 3, 5, 7, 20)
36
>>> add_many(1, 3)
4
Named Arguments (Keyword Arguments)
With Python and a few other languages, it is possible to explicitly name the arguments when calling the function. Whereby argument passing is by default based a positional basis ("1st argument, 2nd argument etc.), Python will let you name the arguments and pass them in any order. This is mostly a syntactic nicety, but can be useful, in combination with default arguments for functions that accept very many arguments. It is also a nice self-documenting feature.
>>> def do_greetings(greeting, person):
... print (greeting, "dear", person, "!")
...
>>> do_greetings(person="Jack", greeting="Good evening")
Good evening dear Jack !
In Python, you can even pass a dictionary in lieu of several named arguments for example, with do_greetingsas-is, imagine you have a dictionary like:
>>> my_param_dict = {"greeting":"Aloha", "person":"Alan"}
>>> do_greetings(**my_param_dict)
Aloha dear Alan !
In closing, and while the fancy ways of passing arguments, and the capability for methods to handle variable number of arguments are useful features of various languages, two key concepts need to be mentioned:
Argument passing convention : by value or by reference
So far all the functions we used didn't alter the value of the parameters passed to them. We can imagine however many instances when functions may want to do this, either to perform some conversion or computation on the said values, for its own internal use, or to effectively change the value of the variable so that the changes are reflected at the level of logic which called the function. That's where argument passing conventions come handy...
arguments which are passed by value may be altered by the function for its own internal computations but are not changed at the level of the calling method.
arguments which are passed by reference will reflect changes made to them, at the level of the calling method.
Each language specifies the ways that arguments are passed. A typical convention is to pass integers, numberic values and other basic types by value and to pass objects by reference. Most language also offer keyword that allow altering their default convention.
In python all arguments are passed by reference. However a few variables types are immutable (numbers, strings, tuples...) and they can therefore not be altered by the function.
Implicit "self" or "this" argument of class methods
In object oriented languages, methods (i.e. functions within a class) receive an extra argument that is the value of underlying object (the instance of the class), allowing the method to use various properties members of the class in its computation and/or to alter the value of some of these properties.
in Python, this argument is declared at the level of the method definition, but is passed implicitly. Being declared, it may be named most anything one wishes, although by convention this is typically called self.
>>> class Accumulator:
... def __init__(self, initialValue = 0):
... self.CurValue = initialValue
... def Add(self, x):
... self.CurValue += x
... return self.CurValue
...
>>> my_accu = Accumulator(10)
>>> my_accu.Add(5)
15
>>> my_accu.Add(3)
18
In that case for using arguments, it is simply a demo on how to use them, not the most effective perhaps as you demonstrated. Functions are very useful. for example if i wanted to add two numbers:
def add(num1, num2):
x = num1 + num2
return x
add(1,3)
Functions are useful for performing repetitive tasks, let's say in your example you had to say hello to hundreds of names, instead of having to do a loop of that raw_input() function to read their name and add some text to it you could simply call a function to perform the task and pass arguments (the persons name to it).
Per your second question, arguments are just variables passed to the function, so whatever variable you pass to it from the outside, for example I pass numbers 1 and 3 to my function add on the inside of that function they are simply referred to as num1 num2.
In your case with passing too many arguments would yield this:
>>> add(1,2)
3
>>> add(1,2,3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add() takes exactly 2 arguments (3 given)
>>>
Best of luck! and feel free to shoot me an email if you need further help (sbrichards (at) mit.edu)
The stuff in the parentheses are called arguments. Basically these are variables that you want the function to work with. For example, say you have a function, and you want it to print a word when you call it. With arguments, you can define what that word will be. Here is an example:
def hi(word):
print word
now, if I do something like this:
hi('Hello!')
it will print:
'Hello!'
hi() gets passed 'Hello!' as a variable called word, and then it prints that word.
In your example they are not used.
If your function needs to behave differently depending on what arguments you give it, then what's arguments are for.
def hi_name(name):
print 'Hi ' + name
hi_name("John doe")
This prints "Hi John Doe".
Now back to the basics about functions.
An argument is a special variable that exists only in that function.
In your example you have a function that takes 2 arguments:
def add(num1,num2):
x = num1 + num2
return x
When I call this function with add(), I have to add in the parentheses what I want num1 and num2 to be. In your case, you have 1 and 3, so you call it like this add(1,3).
What you're saying there is that you want to call add() and you want the first argument, num1 to be equal to 1, and the second argument, num2, to be equal to 3.
def main(a, b):
print(a)
print(b)
main(3, 5)
This is a basic example of a function with parameters, check for more information here.
output:
3
5
Functions would be useless if you can't give them information they should handle.
Arguments are such information.
def GiveMeANumberAndIDuplicateIt(x):
return x * 2
def DontGiveMeAnythingAtAll():
return None

Categories