Code Club – Simple Python 3 Functions

As we are learning Python at Code Club, I am going to make some related posts looking at the very basics of this. We are using for this

Firstly open a new Python Trinket

Firstly we are going to tell the interpreter to use python3.

#!/usr/bin/env python3 #use python 3

We are going to create a function called print_name() and then call it. The function will just print hello to the standard output.

def print_name():
  print ("hello")

So this in does the same as what

print ("hello")

To the next step is to run the function several times.

We could run


However it is probably better to put the print_name() in a loop, so it calls the function a specified number of times (in this case 4)

for x in range(0,4):

So this will now call the print_name() four times (or however many times is specified.

Assuming this works, we can now add some user interactivity

y = input("iterations")

As we are dealing with numbers (integers) than y will be a string we fix this in the line for x in range(0,int(y)): int(y) will convert string y in to integer y

Final program looks like this:-

def print_name(y):
  print ("hello")

y = input("iterations")
for x in range(0,int(y)):

Will ask for user input, store this in the variable y, as an integer. It run a loop which calls the function y times. Which in turn prints hello.

If you add the line


After the


Line, then the program should output a number count for each iteration. This can be a useful too for debugging loops. This will also make use of the fact we are passing the value of y to the function.




MastodonPeertubeQoto sign up

Donate using Liberapay