Calculator function outputs nothing [duplicate] - python

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 6 months ago.
I need to design a calculator with the following UI:
Welcome to Calculator!
1 Addition
2 Subtraction
3 Multiplication
4 Division
Which operation are you going to use?: 1
How many numbers are you going to use?: 2
Please enter the number: 3
Please enter the number: 1
The answer is 4.
This is what I have so far:
print("Welcome to Calculator!")
class Calculator:
def addition(self,x,y):
added = x + y
return sum
def subtraction(self,x,y):
diff = x - y
return diff
def multiplication(self,x,y):
prod = x * y
return prod
def division(self,x,y):
quo = x / y
return quo
calculator = Calculator()
print("1 \tAddition")
print("2 \tSubtraction")
print("3 \tMultiplication")
print("4 \tDivision")
operations = int(input("What operation would you like to use?: "))
x = int(input("How many numbers would you like to use?: "))
if operations == 1:
a = 0
sum = 0
while a < x:
number = int(input("Please enter number here: "))
a += 1
sum = calculator.addition(number,sum)
I seriously need some help! All the tutorials on calculators in Python 3 are far more simple than this (as in it only take 2 numbers and then simply prints out the answer).
I need help getting the functions in the Calculator class I made to work. When I try running what I have so far, it lets me input my numbers and whatnot, but then it just ends. It doesn't run the operation or whatever. I am aware I only have addition so far, but if someone can just help me figure out addition, I think I can do the rest.

The code as it is does not work. In the addition function you return the variable sum which will conflict with the build in sum function.
So just return the added and in general avoid the sum, use something like sum_ :
This works fine for me:
print("Welcome to Calculator!")
class Calculator:
def addition(self,x,y):
added = x + y
return added
def subtraction(self,x,y):
diff = x - y
return diff
def multiplication(self,x,y):
prod = x * y
return prod
def division(self,x,y):
quo = x / y
return quo
calculator = Calculator()
print("1 \tAddition")
print("2 \tSubtraction")
print("3 \tMultiplication")
print("4 \tDivision")
operations = int(input("What operation would you like to use?: "))
x = int(input("How many numbers would you like to use?: "))
if operations == 1:
a = 0
sum_ = 0
while a < x:
number = int(input("Please enter number here: "))
a += 1
sum_ = calculator.addition(number,sum_)
print(sum_)
Running:
$ python s.py
Welcome to Calculator!
1 Addition
2 Subtraction
3 Multiplication
4 Division
What operation would you like to use?: 1
How many numbers would you like to use?: 2
Please enter number here: 45
Please enter number here: 45
90

Your program takes input, runs a series of operations, and then ends without ever displaying the result. Try something like print(sum) after the while loop ends.

Related

Writing a program to find sum of a series using math.pow and math.factorial

Here is the question my teacher gave us:
Write a program to find the sum of the following series (accept values of x and n from user). Use functions of the math library like math.pow and math.factorial:
1 + x/1! + x2/2! + ……….xn/n!
This is the code I've come up with. I calculated it on paper with simple numbers and there's clearly some logic errors because I can't get a correct answer. I think I've been looking at it for too long to really grasp the issue, so I could use some help.
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
for i in range (n):
power = math.pow(x,i)
ans = 1 + (power / math.factorial(i))
print(ans)
Note: This is an entry level class, so if there's an easier way to do this with a specific function or something I can't really use it because I haven't been taught it yet, although appreciate any input!
I would not recommend using those functions. There are better ways to do it that are within the grasp of entry level programmers.
Here's what I recommend you try:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
sum = 1
term = 1.0
for i in range (1,n+1):
term *= x/i
sum += term
print(sum)
You don't need those functions. They're inefficient for this case.
I believe the following will work for you:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
ans = 1
for i in range (1,n+1):
power = math.pow(x,i)
ans += (power / math.factorial(i))
print(ans)
We start the ans variable at 1 and we add the new term to ans through each iteration of the loop. Note that x+=n is the same as x=x+n for integers.
I also changed the range that your loop is going through, since you start at 1 and go up to n, rather than starting at 0 and going to n-1.
Output:
Input x: 2
Input n: 5
7.266666666666667
For people familiar with the mathematical constant e:
Input x: 1
Input n: 15
2.718281828458995
Your ans only includes (the 1 and) the latest term. You should instead Initialize it before the loop and then add all the terms to it. The first term 1 doesn't deserve ugly special treatment, so I compute it like all the others instead:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
ans = 0
for i in range(n + 1):
ans += math.pow(x, i) / math.factorial(i)
print(ans)
And a preview how you'll likely soon be taught/allowed to write it:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
print(sum(math.pow(x, i) / math.factorial(i)
for i in range(n + 1)))

Write a Python program to print the following sequence of numbers (N to be entered by user): X + X^3/3! + X^5/5!... Upto the Nth Term

The problem i am having with this question is that the code i have written is showing a logical error. Here is the code i have written:
x = int(input("Please enter the base number: "))
n = int(input("Please enter the number of terms: "))
s = 0
factorial = 1
for i in range(1,n+1,2):
factorial = factorial*i
s = (x**i) / factorial
#using f string to format the numbers to a fixed number of decimal places
print(f"{s:.6f}", end='+')
I used the for loop to only show odd values of index, because that is the requirement in the question. My output is coming as follows:
Please enter the base number: 2
Please enter the number of terms: 4
2.000000+2.666667+
We don't have to actually find the sum, only display all the individual addends separated by a plus sign. What changes should i make within the code to get the required results?
My required output would look something like this:
Please enter the base number: 2
Please enter the number of terms: 4
2.000000+1.333333+0.266666+0.025396
Just change to
for i in range(1,2*(n)+1,2):
from
for i in range(1,n+1,2):
Now, the output is:
Please enter the base number: 2
Please enter the number of terms: 4
2.000000+2.666667+2.133333+1.219048+
Also, the method of calculating factorial is wrong as it skips half of the terms, when you jump i from 1 to 3 to 5, so that 2, 4, 6.. are getting missed.
So, you can do:
if i > 1:
factorial = factorial*i*(i-1)
elif i == 1:
factorial*i
So, the final code would be:
x = int(input("Please enter the base number: "))
n = int(input("Please enter the number of terms: "))
s = 0
factorial = 1
for i in range(1,2*n+1,2):
if i > 1:
factorial = factorial*i*(i-1)
elif i == 1:
factorial*i
s = (x**i) / factorial
#using f string to format the numbers to a fixed number of decimal places
print(f"{s:.6f}", end='+')
Factorial is in the loop but the loop does i=1,3,5 and not i=1,2,3,4,5, that's might be a problem. If the "number of terms" : "2.000000+2.666667" is two so in the loop your range avec to be until n*2 and not n but careful because the factory will be changed.

Printing multiple objects without spaces

I'm writing a basic program to convert any 4 digit number in reverse.
I know I'm taking a very complex approach, but that's what my professor requires. So far I've got:
print("This program will display any 4-digit integer in reverse order")
userNum = eval(input("Enter any 4-digit integer: "))
num1 = userNum % 10
userNum2 = userNum // 10
num2 = userNum2 % 10
userNum3 = userNum // 100
num3 = userNum3 % 10
userNum4 = userNum // 1000
num4 = userNum4 % 10
print(num1,num2,num3,num4)
The issue I'm having is the output from the print statement gives me
x x x x
When I would prefer to have
xxxx
Any advice?
If you read the description of the print(), you can see that you can change your last line for:
print(num1,num2,num3,num4, sep='')
Since you just want to convert the input in reverse order. You can take the following approach.
print("This program will display any 4-digit integer in reverse order")
userNum = input("Enter any 4-digit integer: ")
reverse_input = userNum[::-1]
reverse_input = int(reverse_input) # If you want to keep input as an int class
print(reverse_input)
If you want to use your own code then just change the print statement.
print(str(num1) + str(num2) + str(num3) + str(num4))
String concatenation does not add space so you should get desired result.
I used this as a sort of exercise for myself to nail down loops. There are a few loops you can use.
#if using python <3
from __future__ import print_function
x = 3456
z = x
print('While:')
while z > 0:
print(z % 10, end="")
z = z / 10;
print()
print('For:')
for y in xrange(4):
z=x%10
print(z, end="")
x = x / 10
Thanks for asking this question. It encouraged me to go look at python syntax, myself, and I think it's a good exercise.

how to solve this factorial

I've managed to get factors in a list but I can't finish because I'm doing something wrong in the end, the count variable is not updating with the products.
I want to solve it without using the factorial function.
Question:
Write a program which can compute the factorial of a given number.
The results should be printed in a comma-separated sequence on a single line.
Suppose the following input is supplied to the program:
8
Then, the output should be:
40320
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
user = int(input("Input a number: "))
factors = []
while user > 0:
n = user * (user - 1)
if user == 1:
factors.append(1)
break
else:
factors.append(user)
user -= 1
count = 0 # this should be updating but it's not
for f in range(factors[0]): # I'm not sure if this is the correct range
counting = factors[f] * factors[f + 1] # I'm not sure about this either
count = count + counting
f = f + 1
Just change the last part of your program to:
result = 1
for f in factors:
result *= f
print result
Finding the factorial of a number is simple. I'm no python expert, and it could probably be written simpler but,
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
I think #erip may be right in the comment section.
num = int(input("Input a number: "))
factorial = 1
for i in range(2,num+1): # range isn't inclusive
factorial*=i

Check if numbers are in a certain range in python (with a loop)? [duplicate]

This question already has answers here:
Determine whether integer is between two other integers
(16 answers)
Closed 4 years ago.
Here's my code:
total = int(input("How many students are there "))
print("Please enter their scores, between 1 - 100")
myList = []
for i in range (total):
n = int(input("Enter a test score >> "))
myList.append(n)
Basically I'm writing a program to calculate test scores but first the user has to enter the scores which are between 0 - 100.
If the user enters a test score out of that range, I want the program to tell the user to rewrite that number. I don't want the program to just end with a error. How can I do that?
while True:
n = int(input("enter a number between 0 and 100: "))
if 0 <= n <= 100:
break
print('try again')
Just like the code in your question, this will work both in Python 2.x and 3.x.
First, you have to know how to check whether a value is in a range. That's easy:
if n in range(0, 101):
Almost a direct translation from English. (This is only a good solution for Python 3.0 or later, but you're clearly using Python 3.)
Next, if you want to make them keep trying until they enter something valid, just do it in a loop:
for i in range(total):
while True:
n = int(input("Enter a test score >> "))
if n in range(0, 101):
break
myList.append(n)
Again, almost a direct translation from English.
But it might be much clearer if you break this out into a separate function:
def getTestScore():
while True:
n = int(input("Enter a test score >> "))
if n in range(0, 101):
return n
for i in range(total):
n = getTestScore()
myList.append(n)
As f p points out, the program will still "just end with a error" if they type something that isn't an integer, such as "A+". Handling that is a bit trickier. The int function will raise a ValueError if you give it a string that isn't a valid representation of an integer. So:
def getTestScore():
while True:
try:
n = int(input("Enter a test score >> "))
except ValueError:
pass
else:
if n in range(0, 101):
return n
You can use a helper function like:
def input_number(min, max):
while True:
n = input("Please enter a number between {} and {}:".format(min, max))
n = int(n)
if (min <= n <= max):
return n
else:
print("Bzzt! Wrong.")

Categories

Resources