[Tutor] Inputting variables into functions containing if, elif, else.

Alan Gauld alan.gauld at yahoo.co.uk
Mon Jun 26 14:20:08 EDT 2023


On 26/06/2023 12:11, Jack Simpson wrote:
> Hi,
> 
> I was hoping to gain some knowledge on how I can test out a function.
> Should I have used the return function somewhere or have I totally missed a
> step?

You have missed a vital step. You haven't created a function.
I think you might still be misssing a concept here.
A function is like a little mini-program that has its own name.
You can then call that mini-program from inside your own programs.

You create such a mini-program using the def keyword

def mini_program(input values here):


> Or have I not defined a variable properly?
> 
> number = 25

You have defined the variable number and given it the value 25.


But...

> if number <= 5:
>    print("The number is 5 or smaller.")
> elif number == 33:
>    print("The number is 33.")
> elif number < 32 and number >= 6:
>    print("The number is less than 32 and greater than 6.")
> else:
>    print("The number is " + str(number))

This is just regular code. It is not inside a function.
To do that you need to put all of the above code underneath
a def statement. Like this(note the all-important indentation!):

def test_number(aNumber):
  if aNumber <= 5:
    print("The number is 5 or smaller.")
  elif Anumber == 33:
    print("The number is 33.")
  elif aNnumber < 32 and aNumber >= 6:
    print("The number is less than 32 and greater than 6.")
  else:
    print("The number is " + str(number))

And then you can call it with your number variable from above:

test_number(number)

A couple of bonus points:
The line
  elif aNnumber < 32 and aNumber >= 6:

can be written:

  elif 6 =< aNumber < 32:

It doesn't make much difference but saves a little typing.
Just be careful about which comparison sign you use.

Also, the line
    print("The number is " + str(number))

can be written

    print("The number is ",number)

print() will automatically convert things to strings if
possible. And doing it this way is actually very slightly
faster and memory efficient than adding the two strings
together.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos





More information about the Tutor mailing list