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
Related
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 months ago.
I have the following code:
print('''How to use this calculator:
1 - Enter the type of function you want it to do like addition(+), subtraction(-), etc.
2 - Enter your number and it'll keep asking you until you say it to stop
3 - Voila! you have your answer\n''')
while 1 > 0:
function = input("Enter the type of function you want to do:\n")
if function == 'addition' or 'Addition' or 'ADDITION' or 'aDDITION' or '+' or 'add':
num1 = int(input("Enter your number:\n"))
num2 = int(input("Enter your number:\n"))
total = num1 + num2
print('Your answer is ' + str(total))
continue
elif function == 'subtraction' or 'Subtraction' or 'SUBTRACTION' or 'sUBTRACTION' or '-' or 'subtract':
num1 = int(input("Enter the number you want to subtract from:\n"))
num2 = int(input(f"Enter the number you want to subtract from {num1}:\n"))
total = num1 - num2
print('Your answer is' + str(total))
continue
elif function == 'multiplication' or 'multiply' or '*' or 'Multiply' or 'MULTIPLY':
num1 = int(input("Enter the number you want to multiply:\n"))
num2 = int(input(f"Enter the number you want to multiply {num1} wit:\n"))
total = num1 * num2
print('Your answer is' + str(total))
continue
elif function == 'divide' or 'DIVIDE' or '/':
num1 = int(input("Enter the number you want to divide:\n"))
num2 = int(input(f"Enter the number you want to divisor for {num1}:\n"))
total = num1 / num2
print('Your answer is' + str(total))
continue
elif function == 'stop' or 'STOP' or 'Stop' or 'sTOP':
break
else:
print('Can\'t understant what you want to do please write your choice in the format below\n' + '''How to use this calculator:
1 - Enter the type of function you want it to do like addition(+), subtraction(-), etc.
2 - Enter your number and it'll keep asking you until you say it to stop
3 - Voila! you have your answer''')
I have a infinite loop which asks you to enter a function. And I have if-elif-else statements to see, which function the user inputed. I want the function the user inputed to be the one that gets activated, but for a reason it always does addition. Any help is appreciated!
In python a string can get evaluated as a boolean. An empty string returns False and a non-empty one returns True.
Example:
print(bool("A non empty string"))
Output:
True
Example:
print(bool("")) # <---- Empty String
Output:
False
In the if statements you have, you wrote:
if function == 'addition' or 'Addition' or 'ADDITION' or 'aDDITION' or '+' or 'add':
...
Python first checks if function equals "addition" then if not it continues to the next condition and that is simply "Addition". Since there is no comparison or anything like that it simply gets evaluated to True and, thus the if statement becomes True, because you used or (So only one of the conditions have to be True.)
To fix this you have to add function == ... to your every check as such:
if function == 'addition' or function == 'Addition' or function == 'ADDITION' or function == 'aDDITION' or function == '+' or function == 'add':
...
To make this more readable you can use the in keyword and check if function is in the tuple as such:
if function in ('addition', 'Addition', 'ADDITION', 'aDDITION', '+', 'add'):
...
And to make this even better you can upper case the function and check if function is ADDITION only not every combination like "Addition", "aDdition"...
This is how you do it:
if function.upper() in ('ADDITION', '+', 'ADD'):
...
And here is the full working code (I also did a little bit of cleaning):
print('''How to use this calculator:
1 - Enter the type of function you want it to do like addition(+), subtraction(-), etc.
2 - Enter your number and it'll keep asking you until you say it to stop
3 - Voila! you have your answer\n''')
while True:
function = input("Enter the type of function you want to do:\n").upper()
if function in ('ADDITION', '+', 'ADD'):
num1 = int(input("Enter your number:\n"))
num2 = int(input("Enter your number:\n"))
total = num1 + num2
print(f'Your answer is {total}')
continue
elif function in ('SUBTRACTION', '-', 'SUBTRACT'):
num1 = int(input("Enter the number you want to subtract from:\n"))
num2 = int(input(f"Enter the number you want to subtract from {num1}:\n"))
total = num1 - num2
print(f'Your answer is {total}')
continue
elif function in ('MULTIPLICATION', '*', 'MULTIPLY'):
num1 = int(input("Enter the number you want to multiply:\n"))
num2 = int(input(f"Enter the number you want to multiply {num1} wit:\n"))
total = num1 * num2
print(f'Your answer is {total}')
continue
elif function in ('DIVISION', '/', 'DIVIDE'):
num1 = int(input("Enter the number you want to divide:\n"))
num2 = int(input(f"Enter the number you want to divisor for {num1}:\n"))
total = num1 / num2
print(f'Your answer is {total}')
continue
elif function == 'STOP':
break
else:
print('Can\'t understand what you want to do please write your choice in the format below\n' + '''How to use this calculator:
1 - Enter the type of function you want it to do like addition(+), subtraction(-), etc.
2 - Enter your number and it'll keep asking you until you say it to stop
3 - Voila! you have your answer''')
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()
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
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 1 year ago.
I wanted to do the following simple calculation by passing values for the parameters num1 and num2 from input() methods.
I tried following code:
def add(num1, num2):
return num1 * num2
num1 = input('Enter number1: ')
num2 = input('Enter number2: ')
print(add(num1, num2))
But it is showing the following error when it is run (After input num1 and num2):
TypeError: can't multiply sequence by non-int of type 'str'
Can somebody please explain where did I go wrong and how to convert an input string to the integer type?
input() will returns a string, you have to convert the string to a int or float, you can test if the input is a valid number.
isnumeric() will return true if all chars in the string are numeric ones and the string is not empty.
Note: i renamed the function to multiply because this is not adding ...
def multiply(num1,num2):
return num1*num2
inp1=input('Enter number1: ')
inp2=input('Enter number2: ')
if inp1.isnumeric() and inp2.isnumeric():
num1 = int(inp1)
num2 = int(inp2)
print(multiply(num1,num2))
else:
print("Atleast one input is not numeric")
You can try this:
def add(num1, num2):
return num1 * num2
num1 = int(input('Enter number1: '))
num2 = int(input('Enter number2: '))
print(add(num1, num2))
The input function stores the input as a string and so what is happening in your code is that you are entering two integers but they are being stored as strings. You cannot multiply two strings. All you need to do is convert the input strings to integers by using the [int()][2] function. If you want to multiply floats, you can use the [float()][3] function in place of the int() function. You can also convert the strings to integers or floats once you have passed them into the function. Something like this:
def add(num1, num2):
return int(num1) * int(num2)
num1 = input('Enter number1: ')
num2 = input('Enter number2: ')
print(add(num1, num2))
input (in Python 3) returns a str which is seen as text and not a number. If you want to multiply (or add) numbers, you must first parse the strings as numbers.
Sometimes this will fail as well. If you're assuming the input is always going to be a valid number, you can convert a string using:
float("3.1415926")
You can use this in your code with:
def add(num1,num2):
return num1*num2
num1=float(input('Enter number1: '))
num2=float(input('Enter number2: '))
print(add(num1,num2))
To avoid floating point errors, you can print/display the float using an f-string (added in Python 3.6).
def add(num1,num2):
return num1*num2
num1=float(input('Enter number1: '))
num2=float(input('Enter number2: '))
print(f"{add(num1,num2):.2f}")
def mul(num1,num2):
return(num1*num2)
inp1 = input('Enter number1:')
inp2 = input('Enter number2:')
num1 = int(inp1)
num2 = int(inp2)
print(mul(num1,num2))
The idea is, that the calculator is supposed to detect the numbers of num1 in the calculation and add more until it is equal to the num2, as it is supposed to be num1 raised to the power of num2.
But I keep receiving this message "'int' object has no attribute 'count'". I know the count is for lists, so I was wondering, what the appropriate command would be for int (or float).
Furthermore, how would I go about adding the numbers of "num1" to the equation?
Here is the whole code
num1 = int(input("Enter a number"))
operator = input("Now enter an operator")
num2 = int(input("Enter a new number"))
Pow = (num1*num1)
if operator == "^":
print(Pow)
while Pow.count(num1) < num2 += 1:
Pow = num1 * num1
num1 = int(input("Enter a number: "))
operator = input("Now enter an operator: ")
num2 = int(input("Enter a new number: "))
goal = num1 ** num2
#print("goal: " + str(goal))
count = 1
if operator == '^':
while num1 < goal:
#print(num1)
num1 += num1
count += 1
#print(num1)
print ("It took %(count)d loops to get to %(num)d!" % {'count': count, 'num': goal})
Your question is vague, but I believe this is what you are looking for?
Edited code above and included example below
You have an Invalid Syntax here which is while Pow.count(num1) < num2 += 1:
Have a look at this edited code:
num1 = int(input("Enter a number"))
operator = input("Now enter an operator")
num2 = int(input("Enter a new number"))
Pow = (num1*num1)
if operator == "^":
print(Pow)
while num1 < num2:
Pow = num1 * num1
num2 += 1