[Tutor] Help Passing Variables
alan.gauld at btinternet.com
Thu Oct 18 09:46:36 CEST 2012
On 18/10/12 08:08, Daniel Gulko wrote:
> The function calls for passing in two variables "a_string, width" but I
> am still confused on this concept.
You just provide the list of input parameters when you define the function:
>>> def add(x,y):
... return x+y
I define add to take two parameters x and y.
I then supply two corresponding arguments, 4,5 when I call add.
I then use x and y inside my function (x+y) like ordinary variables.
> am still unsure how to pass in the variable "width".
add it to your function definition as I did for add()
Then add a width value to the call to your function
> centering but I am not sure if instead I use the variable width to
> determine the centering.
Yes, or being pedantic, you use the parameter 'width' in your call to
> def SwapCaseAndCenter(a_string):
> while True:
> a_string=raw_input("give me a word: (enter to quit): ")
> if a_string:
> print a_string.center(60).swapcase()
> elif not a_string:
> print "you did not provide a word. goodbye"
BTW putting break here means your loop only ever executes once.
Frankly I would take the loop out and prompt the user for a_string
outside the function and pass the string in along with the width.
I'd also return the modified string so the caller can print it.
Also rather than use the elif line I'd change it to an else.
The test is implied by the fact it failed the initial if test.
Either a_string is True (it exists) or it is not True, there is no third
option so you don't need a separate elif test.
If you really want to prompt the user multiple times do that outside the
my_string=raw_input("give me a word: (enter to quit): ")
print "you did not provide a word. goodbye"
Author of the Learn to Program web site
More information about the Tutor