examples of methods in python programming


All Contributions

create simple calculater using functions in python:

this example contains definitions of 6 functions, and call it by the user.

#create simple calculater و using functions:
def sum(num1,num2):
    return num1+num2

def subtract(num1,num2):
    return num1-num2

def multiply(num1,num2):
    return num1*num2

def divide(num1,num2):
    return num1/num2

def remainder(num1,num2):
    return num1%num2
def power(number,power):
    counter = 1
    result = 1
    while counter <= power:
        result *= number  # same as result=result*n
        counter += 1  # same counter=counter+1
    return result

x=int(input('please enter first number:'))
y=int(input('please enter second number:'))
if choice=="1":
    print('the summation result is :' , sum(x,y))
elif choice=="2":
    print('the subtraction result is :',subtract(x,y))
elif choice=="3":
    print('the multiplication result is :',multiply(x,y))
elif choice=="4":
    print('the division result is :',divide(x,y))
elif choice == "5":
    print('the remainder result is :', remainder(x, y))
elif choice == "6":
    print('the power result is :',power(x, y))
    print("invalid entry")

Exercise : Write a function g that computes g(x, y) where g(x, y) = x^2 + √2

import math

def g(x , y):
    return x**2 + math.sqrt(y)

print("example: result of g(2,3) is : ",g(2,3))

Write a function f that computes f(x) where f(x) = x^3 - x + 1.

solutions are expected: with and without calling pow() from cmath library)

import cmath
def f(x):
    #i= x ** 3 - x + 1 #without using pow()
    i=pow(x,3)-x+1  #using pow()
    print('the result is ',i)

write python program that prompts user to enter the color of traffic light, and then acts upon it.

#write python program that prompts user to enter the color of traffic light, and then acts upon it.
def guessLight(l):
    if l == 'red':
    elif l == 'yellow':
        print('Slow down')
    elif l == 'green':
        print('invalid entry, Choose between red, green, and yellow.')

light = input('please enter the color of traffic light')


function maximum that returns the largest number of 2 numbers:

def maximum(x, y):
    if x > y:
        return x
    elif x == y:
        return 'The numbers are equal'
        return y

print(maximum(2, 3))

total contributions (10)

need a help?

find thousands of online teachers now

New to examplegeek.com?

Join us