I started Python last week and this is the question my teacher wants us to solve: Write a function named average_of_3 that accepts three integers as parameters and returns the average of the three integers as a number. For example, the call of average_of_3(4, 7, 13) returns 8.
Functions are very confusing to me but this is what I have so far...
def average(num1, num2, num3):
avg = (num1) + (num2) + (num3)/3
return (avg)
num1 = int(input("Enter a number: "))
num2 = int(input("Enter a number: "))
num3 = int(input("Enter a number: "))
I'm not sure if this is right or not... I'm also not sure what to do after this.
Think of a function as a cook. You give the cook some ingredients and the cook gives you back a delicious dish. When you define the function, you "teach the chef how to cook" by telling Python what ingredients it takes, what it does to the ingredients, and what it gives back.
So you can ask your user what "ingredients they want to give your chef" like so:
a = int(input("Enter a number: "))
b = int(input("Enter a number: "))
c = int(input("Enter a number: "))
But you still need to give the chef those ingredients. You do that by calling the function like so:
answer = average(a, b, c)
Side note: The chef can have its own names for the ingredients, so even though you defined them as a, b, c while asking the user, when you pass them to the function, the function accesses them as num1, num2, num3 because that's how the function is defined.
Then you can do whatever you want with answer, such as print(answer)
Oh, and another thing: remember PEMDAS / BEDMAS / whatever you call the order of operations in mathematics? Such a concept exists in programming too. If you simply do
avg = 1 + 2 + 3 / 3
You get avg = 4. Instead, surround the entire sum in parentheses so that you actually get the average
avg = (1 + 2 + 3) / 3
this can be done using optional argument or using a list of your values
def averaged(*args):
return sum(args)/len(args)
#or
def averaged1(args: list):
return sum(args)/len(args)
#------------------------------
print(averaged(3,4,5))
print(averaged1([3,4,5]))
4.0
4.0
you could simply implement this like:
num = None
nums = []
while True:
num = int(input("value: "))
if num !=0: nums.append(num)
else: break
def averaged1(args: list):
return sum(args)/len(args)
print(averaged1(nums))
value: 1
value: 2
value: 3
value: 0 # <-- breaks here
2.0
def average_of_3(num1, num2, num3):
return (num1 + num2 + num3)/3
# call your func
average_of_3(4, 7, 13)
You need to pass your numbers as arguments of the function, if you want to see the output use print()
Related
Suppose I have the following function that asks for 2 numbers and adds them.
def sum():
a = int(input('Enter the first number: '))
b = int(input('Enter the second number: '))
return a + b
Also I have two variables:
first_number = 2
second_number = 4
Considering that I can't copy paste the values of variable or change the function and the variables I want to fill in the values of these variables into the sum function. So, I was trying to do this by creating a function like input_values that could take the function and the variables as arguments and return the output of the function entered in it as an argument after imputing the variable values in it. I am working in a jupyter notebook and not able to understand how to build this function. Or is it possible even. Please help. The resultant function should be defined something like following:
def input_values(func,var1, var2):
#The computation should be held here.
It should be called like this:
input_values(func=sum(), var1=first_number,var2=second_number)
Again specifying, the input_values should follow the following algo.
Initiate the function given to it(in this case it is the sum function)
When the sum function ask to enter the first value from user, fill the value of var1 in it and somehow proceed.
Again, when it asks to enter the other number, enter the value of var2 in it and proceed.
When the given function(sum) is executed, return its value.
You can try something like : Reference
Installation:
pip install pexpect
Then simply try this snippet
import pexpect
first_number = 2
second_number = 4
child = pexpect.spawn('your_script.py')
child.expect('Enter the first number:.*')
child.sendline(first_number)
child.expect('Enter the second number:.*')
child.sendline(second_number)
Make sure you call the function in your source main code
first_number = 2
second_number = 4
def sum():
a = int(input('Enter the first number: '))
b = int(input('Enter the second number: '))
return a + b
sum()
I apologize if I am misunderstanding your question, but is this what you are trying to achieve?
def input_values():
try:
a = int(input('Enter the first number: '))
b = int(input('Enter the second number: '))
except(ValueError) as e:
print(f'{str(e)}. Please only input integers.')
input_values()
return sum_numbers(a, b)
def sum_numbers(a, b):
try:
print(f'The sum of your two numbers is: {a + b}')
except(ArithmeticError) as e:
print(f'{str(e)}.')
if __name__ == "__main__":
input_values()
Please note that I have included some simple error handling to prevent unwanted input. You will want to expand on this to ensure all user input is handled correctly.
The code is:Take 2 numbers from the user. Pass these two numbers to a function mathExp(). This function will calculate the sum of the cubes of the two numbers.
Return and print this value.
Function Structure:
int mathExp(int,int)
My code is:
num1 = int(input("write a number: "))
num2 = int(input("write a number: "))
def mathExp(num1,num2):
print(num**3 + num**2, mathExp(num1,num2))
There is a lot wrong with this code:
First, you are calling the mathExp function IN itself. Thats recursion and I dont think that you want to do this.
Second, the parameters of the mathExp function are called num1 and num2. But in the function you use just num which doesnt exist.
So what you probably want to do is this:
num1 = int(input("write a number: "))
num2 = int(input("write a number: "))
def mathExp(n1,n2):
return n1**3 + n2**3
print(mathExp(num1, num2))
Your mathExp function was wrong. Try this instead:
num1 = int(input("write a number: "))
num2 = int(input("write a number: "))
def mathExp(num1,num2):
ans = num1**3 + num2**3
return ans
cubes = mathExp(num1, num2)
print(cubes)
Try this code:
# take two number as input from the user
num1 = int(input("write a number: "))
num2 = int(input("write a number: "))
# define the function which calculate the sum of cubes of the input numbers
def mathExp(num1,num2):
result = num1**3 + num2**3
return result
# call the function with user input and print the result
print(mathExp(num1, num2))
Example:
write a number: 4
write a number: 7
407
Alright, so I am new with python at the moment and I am absolutely confusing myself with such a simple task. I have to write a function to calculate the average of two numbers, but the user must input the numbers so the average should print out.
I keep getting a a name error, name 'number2' is not defined.Below is my code.
number1 = raw_input("Enter number1")
number2 =raw_input("Enter number2")
def average(number1, number2):
return (number1 + number2) / 2
avg=average = (number1,number2)
print avg
I'm doing something wrong and I know its obvious but I can't quite put my finger on it.
You are making incorrect call to your function. You should do:
# v type-cast value to `int` as `raw_input` returns `str` object
avg = average(int(number1), int(number2))
# ^ ^ make a call to `average()` and store the returned value as `avg`
Below is the complete code sample:
>>> number1 = raw_input("Enter number1: ")
Enter number1: 12
>>> number2 =raw_input("Enter number2: ")
Enter number2: 45
>>> def average(number1, number2):
... return (number1 + number2) / 2.0 # `2.0` to get floating precision
...
>>> avg = average(int(number1), int(number2))
>>> avg
28
Note: In Python 2.x, division of two int returns an int value. If you want the response as float, use 2.0 instead of 2 for division
You have defined average as a function, and you must use it as a function. Something like this:
number1 = raw_input("Enter number1")
number2 =raw_input("Enter number2")
def average(number1, number2):
return (int(number1) + int(number2)) / 2.0
avg=average(number1,number2)
print avg
There were two other things too. You must convert string to integer, and to get a good average you have to divide them by 2.0 instad of 2. Onother way to solve it is to convert the string to float directly.
You can try something like this:
#get number 1, number2 as integers
number1 = int(raw_input("Enter number1"))
number2 =int(raw_input("Enter number2"))
#your function as it was
def average(number1, number2):
return (number1 + number2) / 2
#function `average` returns an int. Store that result in `avg`
avg = average(number1,number2)
#print the result
print(avg)
What you are doing wrong is taking raw_input and not converting it to an integer before arithmetical operation.
When using numbers in python, always use input() other than raw input, to save yourselves from converting raw_iniput to an integer because the input command already takes it as an int.
def avg(a=input('Pls enter val 1: '),b=input('Pls entr val 2: ')):
return ((a / b) / 2.0)
a=avg()
And when using python 2.7 always use float values while dividing cause dividing two integers will always return int whether or not the answer is float.
So , you can use something like this as well:
number1 = float(input("Enter number1"))
number2 = float(input("Enter number2"))
def average(number1, number2):
return (number1 + number2) / 2.0
avg=average = (number1,number2)
print avg
I am brand new to Python coding, so keep that in mind for the following problem. I am just learning the use of defining functions, arguments, and variables.
Define a function called ratioFunction that takes two numbers called num1 and num2 as arguments and calculates the ratio of the two numbers, and displays the results as (in this example num1 is 6, num2 is 3): ‘The ratio of 6 and 3 is 2’. The output after running the code should look like this:
Enter the first number: 6
Enter the second number: 3
The ratio of 6 and 3 is 2.
So here's what I've cooked up with my limited knowledge of coding and my total confusion over functions:
def ratioFunction(num1, num2):
num1 = input('Enter the first number: ')
int(num1)
num2 = input('Enter the second number: ')
int(num2)
ratio12 = int(num1/num2)
print('The ratio of', num1, 'and', num2,'is', ratio12 + '.')
ratioFunction(num1, num2)
I am utterly confused, any help would be appreciated!
The problem is that you aren't capturing the results of the call to int.
def ratioFunction(num1, num2):
num1 = input('Enter the first number: ')
int(num1) # this does nothing because you don't capture it
num2 = input('Enter the second number: ')
int(num2) # also this
ratio12 = int(num1/num2)
print('The ratio of', num1, 'and', num2,'is', ratio12 + '.')
ratioFunction(num1, num2)
Change it to:
def ratioFunction(num1, num2):
num1 = input('Enter the first number: ')
num1 = int(num1) # Now we are good
num2 = input('Enter the second number: ')
num2 = int(num2) # Good, good
ratio12 = int(num1/num2)
print('The ratio of', num1, 'and', num2,'is', ratio12 + '.')
ratioFunction(num1, num2)
Also, when you call ratioFunction(num1, num2) in your last line, this will be a NameError unless you have num1 and num2 definied somewhere. But honestly, this is totally unecessary because you are taking input. This function has no need for arguments. Also, there will be another bug when you print because you are using the + operator on ratio12 + '.' but ratio12 is an int and '.' is a string. Quick fix, convert ratio12 to str:
In [6]: def ratioFunction():
...: num1 = input('Enter the first number: ')
...: num1 = int(num1) # Now we are good
...: num2 = input('Enter the second number: ')
...: num2 = int(num2) # Good, good
...: ratio12 = int(num1/num2)
...: print('The ratio of', num1, 'and', num2,'is', str(ratio12) + '.')
...:
In [7]: ratioFunction()
Enter the first number: 6
Enter the second number: 2
The ratio of 6 and 2 is 3.
Although, likely, your function is suppose to take arguments, and you get input outside the function and pass it to it.
There are primarily 3 issues with your function:
The int division problem:
In Python3, dividing an int object by another int object can return a float.
For example:
In[] : a = 10
In[] : b = 3
In[] : a / b
Out[]: 3.3333333333333335
In[] : a // b # Fix 01: Specifying integer division to the interpreter
Out[]: 3
In[] : int(a / b)
Out[]: 3 # Fix 02: Type casting the float to int
Catching the return value of type casting num1 and num2.
You need to store the value returned by the int function on num1 and num2. Better yet, you can make this explicit when you ask the user for input.
In[] : num1 = int(input("Enter the first number :"))
In[] : num2 = int(input("Enter the second number :"))
Arguments in function ratioFunction's definition:
Since, you are prompting the user for input, it is totally point less to pass them as parameters beforehand. This is a poor design technique and can lead to further issues when you call ratioFunction from other scripts or functions.
Fix: Remove the arguments, and define it as
def ratioFunction()
Tip: I notice that you are using JAVA convention for naming Python function. I would suggest you read PEP8 Python coding style guide.
There are several minor things to fix in your function:
The function ratioFunction should not receive any parameters, because you are asking the user to input the values for num1 and num2 inside the function.
The statement "int(num1)" (without quotes) doesn't alter by itself the value of num1, it just returns the integer representation of num1. You should assign num1 the returned value, or create another variable for that purpose.
You're mixing strings and ints in the print statement (you cannot add a string and an integer). You could replace the + with a comma, but that's a bit ugly. There are several ways to achieve what you want, but I recommend you to use String formatting:
print('The ratio of {0} and {1} is {2}.'.format(num1, num2, ratio12))
If you have to consider non-integer divisions, use float (num1)/num2 to calculate it.
without using division(/) operations, as bellow you can get ration of 2 numbers :)
Output will be as follow:
coff num1 / num2
static int GCD(int p, int q)//find greatest common divisor
{
if (q == 0)
{
return p;
}
int r = p % q;
return GCD(q, r);
}
static string FindRatio(int num1, int num2)
{
string oran = "";
int gcd;
int quotient = 0;
while (num1 >= num2)
{
num1 = num1 - num2;
quotient++;
}
gcd = GCD(num1, num2);
//without using division finding ration of num1 i1
int i1 = 1;
while (gcd*i1 != num1)
{
i1++;
}
//without using division finding ration of num1 i2
int i2 = 1;
while (gcd * i2 != num2)
{
i2++;
}
oran = string.Concat(quotient, " ", i1,"/",i2);
return oran;
}
def RatioFunctions(num1, num2):
n1 = float(num1)
n2 = float(num2)
return n1/n2
Im having trouble with sorting Variables/lists and then being able to transfer them across functions. Im still quite new to python and am probably missing something very basic. but ive been going over this for hours.
I need to create a program which generates 20 random integers and indicates whether each number is odd or even. I need to sort the two original integers into ascending order and transfer them to random.randint function but am having trouble, any help would be appreciated.
This is what i have so far.
import random
def userinput():
global number1
global number2
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
userinput()
def numbersorting():
global both
both = [(number1),(number2)]
sorted(both)
numbersorting()
def random_gen():
global num
i = 0
for i in range(20):
num = random.randint(number1,number2)
def get_num():
return values.pop
def odd_even():
if num % 2 == 0:
print("Random Number", num, "is even")
else:
print("Random Number", num, "is odd")
odd_even()
random_gen()
Well it doesn't seems so clear on the question what actually you want to do but the use of global is a really bad practice in general.
However you can use the methods that returns the values you need for instace:
If you need a user input that returns 2 numbers it is better to use this approach:
def get_numeric_input(label):
try:
return int(input(label))
except NameError:
print "Please enter a number"
return get_numeric_input(label)
With this function you can get a numeric value from a user.
Using it you can the 2 next values like
def get_user_input():
n = get_numeric_input("Enter First Integer: ")
m = get_numeric_input("Enter First Integer: ")
return [n, m]
Now you have a function that returns the 2 values from the user and using the sort method for list you have those values sorted
def get_sorted_values(l):
return l.sort()
Check this information about sorting in python https://wiki.python.org/moin/HowTo/Sorting
Using the random numbers as you have described is ok, but also try to use the is_odd and is_even function outside of any other function and you will be able to reuse them more times.
Are you looking for something like this?
I edited your code to work with what I understand your problem to be...
You want the user to input 2 numbers to set the upper and lower bound of each random number. Then you want to generate 20 random numbers within that range and find out whether each number of even or odd?
import random
def random_gen(number1, number2):
for i in range(20):
num = random.randint(number1,number2)
if num % 2 == 0:
print("Random Number", num, "is even")
else:
print("Random Number", num, "is odd")
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
random_gen(number1, number2)
You have a few problems with your current code:
Indentation (fixed in the edit)
Unnecessary use of global variables. If you need that type of functionality you should consider passing the variables into each function as you need it instead
A number of functions are unnecessary too. For example, you dont need the get_num() and odd_even() functions as you can just perform those actions within the loop that you have. Even in the case I just posted you dont even really need the random_gen() function - you can just move all of that code to after user input. I just left it there to show what I mean with point #2 above
from random import randint
def user_input():
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
if number1 > number2:
number1, number2 = number2, number1
return number1, number2
def odd_even(num):
if num % 2 == 0:
print("Random Number " + str(num) + " is even")
else:
print("Random Number " + str(num) + " is odd")
def random_gen():
number1, number2 = user_input()
for i in range(20):
num = randint(number1, number2)
odd_even(num)
random_gen()
You generally want to try to avoid using global variables when possible. It's just good programming practice, as they can get rather messy and cause problems if you don't keep careful track of them. As far as sorting your two integers, I think that that one if statement is a much more pythonic way of doing things. Well, I think it's easier at least. Also, in Python, you don't need to declare your for loop variables, so the line i=0 is unnecessary. Also, I'm sure this is an assignment, but in real life you're going to want to run an exception clause, in which you would say something like
while True:
try:
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
break
except ValueError:
print("Oops! Try entering an integer!")
Hope that helps!
Avoid globals by passing the variables to functions and returning the new values from functions.
import random
def userinput():
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
return number1, number2
def numbersorting(nums):
return sorted(nums)
def random_gen(hi, lo):
return random.sample(range(hi, lo), 20)
def odd_even(num):
if num % 2 == 0:
print("Random Number %d is even" % num)
else:
print("Random Number %d is odd" % num)
nums = userinput()
sortnum = numbersorting(nums)
randoms = random_gen(*sortnum)
[odd_even(n) for n in randoms]
In keeping with your original function names.
You should be aware of the difference between list.sort and sorted. If you have a list li then li.sort() sorts in place, that is it alters the original list and returns None. So return li.sort() is always wrong. on the other hand return sorted(li) is ok, but just sorted(li) is a wasted sort since the result is thrown away.
Try both.sort()
sorted returns a new list.
sort() is done in place.