I'm trying to build a calculator that does basic operations of complex numbers. I'm using code for a calculator I found online and I want to be able to take user input as a complex number. Right now the code uses int(input) to get integers to evaluate, but I want the input to be in the form of a complex number with the format complex(x,y) where the user only needs to input x,y for each complex number. I'm new to python, so explanations are encouraged and if it's something that's just not possible, that'd be great to know. Here's the code as it is now:
# define functions
def add(x, y):
"""This function adds two numbers"""
return x + y
def subtract(x, y):
"""This function subtracts two numbers"""
return x - y
def multiply(x, y):
"""This function multiplies two numbers"""
return x * y
def divide(x, y):
"""This function divides two numbers"""
return x / y
# take input from the user
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice: 1, 2, 3, or 4: ")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
Pass your input to the complex type function. This constructor can also be called with a string as argument, and it will attempt to parse it using Python's representation of complex numbers.
Example
my_number = complex(input("Number"))
Note that Python uses "j" as a symbol for the imaginary component; you will have to tell your user to input numbers in this format: 1+3j
If you would like your calculator to support a different syntax, you will have to parse the input and feed it to the complex constructor yourself. Regular expressions may be of help.
In order to get complex type input from user we have to use complex type function as suggested by #sleblanc. And if you want to separate real and imaginary part then you have to do like this:
complx = complex(input());
print(complx.real, complx.imag);
Example Output:-
>>> complx = complex(input());
1+2j
>>> print(complx.real, complx.imag);
1.0 2.0
>>>
There is no such way to input directly a complex number in Python. But how we can do is take a complex number.
Method 1-
Take a sting as input then convert it into complex.
Method 2-
Take two separate numbers and then convert them into complex.
Code for Method 1-
a = input() # user will enter 3+5j
a = complex(a) # then this will be converted into complex number.
Code for Method 2-
a ,b = map(int, input().split())
c = complex(a, b)
I know this is an old question and is already solved, but I had a little fun messing with it and including numpy to report the angle of the resulting complex number:
import numpy as np
def add(x, y):
"""This function adds two numbers"""
z1=x+y
print(num1,"+",num2,"=", z1)
return z1
...
...
num1 = complex(input("Enter first number: "))
num2 = complex(input("Enter second number: "))
if choice == '1':
z2=add(num1,num2)
print('mag = ', abs(z2))
print('angle = ', np.angle(z2, deg=True))
...
...
I like it, but I might trim the length of some of the resulting numbers, lol:
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice: 1, 2, 3, or 4: 1
Enter first number: 2+2j
Enter second number: 1+j
(2+2j) + (1+1j) = (3+3j)
mag = 4.242640687119285
angle = 45.0
Related
I am trying to solve where x = -57.8. I am new to coding, so I do not know where I am going wrong in this code. I am constantly facing either object not iterable. I have not been able to figure out why!
import math
realNumber = input("Enter a floating-point real number:")
number =int(float(realNumber))
def f(x):
for x in number:
if x<5:
print("The value of x is:",(x**2/(math.fabs(x)+2))**2)
elif x==5:
print("The value of x is:",equal=(x**2/math.fabs(x)+2))
else:
print("The value of x is:",math.sqrt(x**2/(math.fabs(x)+2)))
return(x)
print(f("-57.8"))
f("-57.8")
The core problem here is that many lines of your function have no reason to be there and act at direct cross-purposes to what you're trying to do. Don't use a for loop if you don't mean to iterate, don't convert to int when you're supposed to be operating on a float, and above all else, don't enter random lines of code when you're trying to solve a problem; they will almost never help, and they will usually just break your program.
Here is a version of the code that I think accomplishes what you're trying to do. The function f computes the value and returns it (using return) rather than printing it inside the function -- this makes it a pure mathematical function (you put a number in, you get a number out). You can then call that function in the context of a print statement to print the returned value.
import math
def f(x):
if x < 5:
return (x**2 / (math.fabs(x) + 2))**2
elif x == 5:
return x**2 / math.fabs(x) + 2
else:
return math.sqrt(x**2 / (math.fabs(x) + 2))
number = float(input("Enter a floating-point real number: "))
print("The value of f(x) is:", f(number))
import math
realNumber = input("Enter a floating-point real number:")
# Here you are converting string {ex: "2.5"} to float {ex: 2.5} then to int {ex: 2}
# You can directly cast string to int if it is possible
#number =int(float(realNumber))
number =int(realNumber)
def f(x):
#for x in number:
# x is a number {ex: 5}, you can not loop over it, so this line not required
if x<5:
print("The value of x is:",(x**2/(math.fabs(x)+2))**2)
elif x==5:
print("The value of x is:",equal=(x**2/math.fabs(x)+2))
else:
print("The value of x is:",math.sqrt(x**2/(math.fabs(x)+2)))
return(x)
# After return statement no code gets executed
# So this line not required
# Also it is calling the function itself, which is {recursion}, it can lead to infinite loop
#print(f("-57.8"))
#f("-57.8")
# you want to pass number
f(number)
as you can tell by my code, i want to make a basic calculator, you get asked what you want to do first then asked 2 input 2 numbers to be worked out by the code. I am having a problem where the code returns nothing and doesnt even attempt to use the functions it is meant to.
##Simple Calculator program##
print("Welcome to my basic calculator program")
print("In this program you will be asked to input what function you want to do then")
print("select 2 numbers, where the program will then do the mathematic operation on those 2 numbers")
#Class containing the functions and basic caluclation
class calculator_class():
print("Please select a function by entering these :")
print("Addition")
print("Subtraction")
print("Multiplication")
print("Division")
#this is a function which asks the user to choose what operator to choose before choosing their number
def userchoice():
userchoices = str(input())
if userchoices in ["Addition","Subtraction","Multiplication","Division"]:
return(
if userchoices == "Addition":
print(addition())
elif userchoices == "Subtraction":
print(subtraction())
elif userchoices == "multiplication":
print(multiplication())
elif userchoices == "division":
print(division())
else:
print(invalid_choice())
print(userchoice())
#here the user chooses the 2 numbers
print("Please select 2 numbers to calculate")
usernumber1 = int(input("Please input your first number here : "))
usernumber2 = int(input("Please input your second number here : "))
#Functions of which contain addition, subtraction, multiplication and division
def addition():
print("A D D I T I O N")
print("Just calculating...")
print(usernumber1 + usernumber2)
def subtraction():
print("S U B T R A C T I O N")
print("Just calculating...")
print(usernumber1 - usernumber2)
def multipliction():
print("M U L T I P L I C A T I O N ")
print("Just calculating...")
print(usernumber1 * usernumber2)
def division():
print("D I V I S I O N ")
print("Just calculatin...")
print(usernumber1 / usernumber2)
def invalid_choice():
print("You did not pick a valid option, please try again")
You have many wrong approaches in this code.
More easier to type just a one sign (* for example) instead of typing "multiplication"
It is better to apply .lower() for every user input
input in python is always str, so str() in userchoices = str(input()) is redundant
int() for input() may lead to error (int('1.2') # error), so put such code in try/except block
I have been trying to write a Mean, Median, and Mode Calculator. I have two questions. 1) How would I add the numbers the user inputs into the empty list. If I simply punch in the numbers it gives me this error:
userNumbers = int(raw_input("Enter the digits here: "))
ValueError: invalid literal for int() with base 10: '2, 4, 6, 8'
I would love to know how to avoid that.
Secondly, I am using Python 2.7.10 and will be moving to 3.4 soon. I know that on 3.4 there is a module named statistics with a median function, however it doesn't work on 2.7.10. Out of curiosity, how would I find the median without the function. Thanks everyone!
from collections import Counter
def numberPlacement():
print("Welcome to the PyCalculator, please enter a series of digits!")
userNumbers = int(raw_input("Enter the digits here: "))
userNumbers = []
def userChoice():
while True:
print("Awesome, now that we haave your numbers please choose an operation (Mean, Median, or Mode!)")
userAnswer = raw_input("Enter your choice here: ")
if userAnswer == "Mean":
mean = sum(userNumbers) / float(len(userNumbers))
return mean
elif userAnswer == "Mode":
mode = Counter(userNumbers)
return mode
continue
print numberPlacement()
print userChoice()
The error you are receiving is because you are trying to cast invalid characters to int.
Your input is: 1, 2, 3, 4 so those commas is what is causing that error.
To rectify this, simply remove the int() cast you have, make your input a list by appending a .split(',') to your input. What that split does is convert your string to a list by splitting on the comma. That way you will have a list of numbers represented by strings.
So, since you are doing math, you need to make sure you are actually using the numerical representation and not the string representation of the data in your list. There is a neat one line solution for this you can do, by using Python's map method (documentation), that will cast all your entries to an int.
So, your user input, can simply look like this:
Python 3:
userNumbers = list(map(int, input("Enter the digits here: ").split(',')))
Python 2:
userNumbers = map(int, raw_input("Enter the digits here: ").split(','))
There is another problem in your code. In your userChoice method, you are referencing userNumbers. Which I think is the reference to userNumbers inside the numberPlacement method. You can't do this.
What I suggest doing, since it seems like you want to call these two methods separately, is make your userChoice method take a parameter, which would be a list, called userNumber. So simply:
def userChoice(userNumbers):
# the rest of your code
Now, it is very important to remember, that this userNumbers in your userChoice method is not the same as the userNumbers in your numberPlacement method. To understand why, this is part of scoping. Which you can read about here.
So, then when you call your methods now, you just have to do something like this:
number_placements = numberPlacement()
print(number_placements)
print(userChoice(number_placements))
When you put it all together, your code now looks like this:
(Python 2)
from collections import Counter
def numberPlacement():
print("Welcome to the PyCalculator, please enter a series of digits!")
userNumbers = map(int, raw_input("Enter the digits here: ").split(','))
return userNumbers
def userChoice(userNumbers):
while True:
print("Awesome, now that we haave your numbers please choose an operation (Mean, Median, or Mode!)")
userAnswer = raw_input("Enter your choice here: ")
if userAnswer == "Mean":
mean = sum(userNumbers) / float(len(userNumbers))
return mean
elif userAnswer == "Mode":
mode = Counter(userNumbers)
return mode
continue
r = numberPlacement()
print(userChoice(r))
Demo:
Welcome to the PyCalculator, please enter a series of digits!
Enter the digits here: 1,2,3,4
Awesome, now that we haave your numbers please choose an operation (Mean, Median, or Mode!)
Enter your choice here: Mode
Counter({1: 1, 2: 1, 3: 1, 4: 1})
You need to split your input:
a = raw_input("Enter the digits here: ").split(',')
b = [int(x) for x in a]
Then you can reference your numbers.
You're printing random things that don't need printing, and you've also got locally scoped variables you're trying to call globally
def numberPlacement():
print("Welcome to the PyCalculator, please enter a series of digits, comma seperated!")
userNumbers = raw_input("Enter the digits here: ")
return [ int(u.strip()) for u in userNumbers.split(',') ]
def userChoice(userNumbers):
print("Awesome, now that we haave your numbers please choose an operation (Mean, Median, or Mode!)")
userAnswer = raw_input("Enter your choice here: ")
if userAnswer == "Mean":
mean = sum(userNumbers) / float(len(userNumbers))
return mean
#omitted
userNumbers = numberPlacement()
print(userChoice(userNumbers))
#list comprehension rewritten as a basic for loop in response to question in comment
final_list = []
for u in userNumbers.split(','):
x = u.strip()
y = int(x)
final_list.append(y)
return final_list
I am working in python 2.7.8.
I'm currently learning about parameters and methods. What I'm trying to accomplish is have a user enter two different variables then pass them to an argument within different methods, sum() and difference().
My following code is something like this:
def computeSum(x, t):
x = int(raw_input('Please enter an integer: '))
t = int(raw_input('Please enter a second integer: '))
x+t
return Sum
def computeDif(y, j):
y = int(raw_input('Please enter an integer: '))
j = int(raw_input('Please enter a second integer: '))
y+j
return Dif
def main():
raw_input('Would you like to find the sum of two numbers or the difference of two numbers?: ')
answer = 'sum'
while True:
computeSum()
else:
computeDif()
For some reason my compiler (pyScriptor) isn't running and I cannot see any output nor error messages, its just blank. Can anyone possibly help me with any syntax/logic errors?
There are a few problems with your code
Your indentation is way off
computeSum and computeDif expect the two numbers as parameters, but then also ask for them from the terminal
You return the variables Sum and Dif, but never assign values to them
You call either computeSum or computeDif, but never do anything with the returned value
You never call main. Do you know that you don't need a main function? You can just put the code in line after the function definitions
This is probably a little closer to what you had in mind
def computeSum(x, t):
return x + t
def computeDif(y, j):
return y - j
def main():
while True:
answer = raw_input('Would you like to find the "sum" of two numbers or the "dif"ference of two numbers? ')
a = int(raw_input('Please enter an integer: '))
b = int(raw_input('Please enter a second integer: '))
if answer == 'sum':
print(computeSum(a, b))
elif answer == 'dif':
print(computeDif(a, b))
else:
print('Please enter "sum" or "dif"')
main()
The problem is that you don't need a main() function. Just put the code, unindented, by itself, and it will run when you run the program.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I'm making a calculator on python for a school assignment but the trouble is, my teacher knows nothing. I've made the calculator, but I need to add some code so the user cannot input a number larger than 999, and if they do it creates a loop where the software asks what the users inputs are. Any help?
# Program make a simple calculator
# that can add, subtract, multiply
# and divide using functions
# define functions
def add(x, y):
"""This function adds two numbers"""
return x + y
def subtract(x, y):
"""This function subtracts two numbers"""
return x - y
def multiply(x, y):
"""This function multiplies two numbers"""
return x * y
def divide(x, y):
"""This function divides two numbers"""
return x / y
# take input from the user
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
I've tried a variety of things but nothing works
P.S. I'm a bit of a novice so go easy
Thanks
while True:
num = int(raw_input('enter an integer <= 999: '))
if num <= 999:
break
print('invalid input, please try again!')
print('you entered: {}'.format(num))
MAX_VALUE = 999
def read_number(message):
n = MAX_VALUE
while (n >= MAX_VALUE):
n = int(raw_input(message))
return n
num1 = read_number("Enter first number:")
num2 = read_number("Enter second number:")
Example run:
Enter first number: 1000
Enter first number: 56
Enter second number: 800