Paul Sutton

Functions

Code Club – Python functions 2

So to follow the previous post, we are going to look at passing 2 arguments to a function, adding them together, then displaying the result.

Firstly open a new Python Trinket

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

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

Now we create a function to take two arguments and display the sub of both

def add_numbers(x,z):
  #print(x)
  #print(z)
  add = (int(x) + int(z))
  print ('Total = ')
  print(add)

Get user input

x = input("First Number") # ask for first number
z = input("Second Number") # ask for second number

Convert to integers

int(x)
int(z)

Call function and pass values to function

add_numbers(x,z)

Tags

#CodeClub,#Python.#Programming,#Functions,#Arguments


MastodonPeertubeQoto sign up

Donate using Liberapay

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 Trinket.io 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")
  
print_name()  

So this in does the same as what

print ("hello")

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

We could run

print_name()  
print_name() 
print_name() 

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):
  print_name()

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)):
  print_name(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

print(y)

After the

print("hello") 

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.

Links

Tags

#CodeClub,#Programming,#Education,#Python.#Functions


MastodonPeertubeQoto sign up

Donate using Liberapay