I need help with my python program. I'm doing a calculator.
The numbers must be formed, but for some reason they do not add up.
It seems that I did everything right, but the program does not work.
Please help me. Picture
Code:
a = input('Enter number A \n');
d = input('Enter sign operations \n')
b = input('Enter number B \n')
c = a + b
if str(d) == "+":
int(c) == "a + b"
print('Answer: ' + c)
Please don't post screenshots. Copy and paste text and use the {} CODE markdown.
What data type is returned by input()? It's always a string. It doesn't matter what you type.
Where is the variable c actually calculated in this program? Line 4.
What types of data are used to compute c? Two strings.
What happens when you use the "+" operation on two strings instead of two numbers? Try running your program and when it prompts you to "enter number A", type "Joe". When it prompts you to "enter number B", type "Bob". What does your program do?
You need to create numerical objects from each of the strings you entered if you want to do arithmetic.
I think that you tried what you thought would do that on line 7. It doesn't work though. "==" is used to test for equality, not to assign a value. The single "=" is used to bind values to variable names. You do that correctly on lines 1 through 4. Notice that the plain variable name is always by itself on the left of the "=" sign. You do all the fancy stuff on the right side of the "=".
You can actually delete lines 6 and 7 and the output of the program will not change.
a and b are strings.
a + b concatenates strings a and b.
You need to convert the strings to int:
c = int(a) + int(b)
And remove the lines:
if str(d) == "+":
int(c) == "a + b"
Here is the complete code, that should to what you want:
a = input('Enter number A \n');
operation = input('Enter sign operations \n')
b = input('Enter number B \n')
c = a + b
if operation == "+":
c= int(a) + int(b)
print('Answer:', c)
Since it looks like you also want to enter an operation sign you might also try eval
a = input('Enter number A \n');
d = raw_input('Enter sign operations \n')
b = input('Enter number B \n')
eval_string = str(a) + d + str(b)
print ( eval(eval_string) )
You should know input accepts only integers and raw_input even if given an integer saves it as a string so it saves only strings.
Related
This problem has been getting in my way over and over:
Is there any way to make the input() function in python not be read as a string, nor an integer, nor a float? Let me explain:
I am trying to make an input where I can reference a variable in the input. Here is an example of what I need to do:
def main():
x = 2
# Below, I would enter x*x as my function.
fx = (input("Please enter your Function: ")
print(fx)
main()
I would hope to receive 4 (i.e. 22) as my output, but instead I get "xx". In other words, python is not recognizing that I am referring to a variable (i.e. x) in my program. It thinks I'm writing a string.
So is there any way for python to receive input that is not a string or a specific number?
In other words: Can input variables into my input? I don't want all my input to be converted to string literals. (I am aware of the fact that I could use int() and float() functions to get numbers, but I need to input variables, not actual numbers in this case).
Sorry about the length of my question
Using Sympy
Note: Similar to this previous question:
Code
import sympy as sym
def main():
x = 2
s = input("Please enter your Function: ") # String expression
fx = sym.sympify(s) # create symbolic expression from string
print('Symbolic expression: ', fx) # print symbolic expression
print('Value of expresion: ', fx.subs({'x' : x})) # substitute for x in expression
main()
Output
Please enter your Function: x*x
Symbolic expression: x**2
Value of expression: 4
You can use eval to do what you want:
def main():
x = 2
# Below, I would enter x*x as my function.
fx = (input("Please enter your Function: ")) # x*x
print(eval(fx))
main()
Output
4
But honestly, this is almost never a good idea. If you are expecting different sorts of inputs, it's better to check the string entered and use some if..else logic to understand what the input really wants.
Keep in mind eval runs all expressions. So (if you have to worry about this sort of thing), someone with malicious intent could also execute anything they want using this code.
If you put your values into a dict (using the name of the variable as the key in the dict), you can convert the name (a string) into the value via a dictionary lookup. For example:
nums = {
"x": 2,
"y": 3,
}
ops = {
"*": int.__mul__,
"+": int.__add__,
}
while True:
fx = input("Please enter your function:")
a, op, b = fx
print(ops[op](nums[a], nums[b]))
Please enter your function:x*x
4
Please enter your function:x+y
5
Please enter your function:y*x
6
is42= False
while(raw_input()):
d = _
if d == 42:
is42 = True
if not is42:
print d
for this python block of code I want to use outside of the interactive prompt mode. So I can't use _ as the last output. How do I assign raw_input to a variable? I'm doing an exercise off a site. about 5 values is the input and I'm suppose to spit some output out for each corresponding input value. What's the best way to take in this input to do that?
This appears to be very inefficient logic. Do you really need the is42 status flag as well? If not, you might want something like
stuff = raw_input()
while stuff:
if stuff != "42":
print stuff
stuff = raw_input()
Does that fix enough of your troubles?
Hi and welcome to Python!
The raw_input() function returns the input read as a string. So where you have d = _, you can replace that with d = raw_input(). A question I have for you is why you had it inside the while condition? If you wanted it to keep asking the user for a number over and over, then replace while(raw_input()): with while True:.
One more thing, raw_input() always returns a string. So if you run print '30' == 30, you'll see that a string representation of 30 is not equal to the number representation of 30. But that's not a problem! You can turn the return value of raw_input() into an integer type by replacing d = raw_input() with d = int(raw_input()).
Now there will be another problem when the user gives you an input that can't be converted to an integer, but handling that can be an exercise for you. :)
Final code:
is42= False
while True:
d = int(raw_input())
if d == 42:
is42 = True
if not is42:
print d
is42=False
while(!is42):
d = int(raw_input("Enter a number: "))
is42 = d==42
print "d = ", d
That should do it if I understand the requirements of your problem correctly.
I'm a beginner programmer. I want to write a program that gives me the maximum product of all the products of 4-adjacent digits in an input number.
So, if the input is "12345678"
Possible selections are 1234, 2345,3456,4567,5678 and the largest product is 5*6*7*8.
My code:
number = str(input("Enter a number:"))
i = 0
L = []
while (i!=len(number)-3):
a = int(number[i])
b = int(number[i+1])
c = int(number[i+2])
d = int(number[i+3])
product = a*b*c*d
L.append(product)
i = i+1
print(L)
print(number)
print(max(L))
I need to apply this to a 1000-digited number. My code works for 8-digited input number and gave an answer for a 500-digited number.
But I tried it with a 600-digited number and it throws this error.
I understand ValueError is an error that appears when the argument given to a function call has correct type, but inappropriate value. There are also examples of when the user gives a string "Alexander" as input in code Eg: int(input("Enter a number"))
the error is for '' an empty string that cannot be converted to an integer. But I cannot understand where/why the empty string was formed.
I have read a few other answers of this Error type, but all involve code that use features of Python I am NOT familiar with and hence cannot understand. I'm just a beginner! So, please help!
And apologies for breaking any rules laid out with regards to question formation!
You've got a space there, not an empty string. Most likely, you just hit the space bar at the end of your input, and Python can't convert that to an integer. You can either just ensure that you don't leave a space at the end, or do some checking of your input (e.g., add a line number = number.strip() to remove any trailing whitespace).
Validate your input as numeric, and strip any whitespace:
number ='123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890'
def foo(number):
number = number.strip()
if number.isdigit():
i = 0
L = []
while (i in range(len(number)-3)):
a = int(number[i])
b = int(number[i+1])
c = int(number[i+2])
d = int(number[i+3])
product = a*b*c*d
L.append(product)
i = i+1
return max(L)
This functions should return a None if user has provided invalid input (e.g., "Alexander"), this should avoid the error you describe:
There are also examples of when the user gives a string "Alexander" as input in code Eg: int(input("Enter a number"))
You can also simplify this using a generator statement for a set of only the unique results:
def foo2(number):
number = number.strip()
if number.isdigit():
return max({int(number[i]) * int(number[i+1]) * int(number[i+2]) * int(number[i+3]) for i in range(len(number)-3)})
I went through a couple of converters in python but they entered the int value seperately. If the input is 100C i want the output in F and if its 50F i want it in C. I'm new to python and tried some simple lines but the error says its impossible to concatenate str and int.
a = raw_input(" enter here")
char = "f"
char2 = "c"
for s in a:
if s in char:
b=(5*(a-32))/9
print(b,"c")
continue
elif s in char2:
d = (9*a/5)+32
print(d,"f")
continue
Since the user will enter a number followed by the unit, you need to only check if the last character of the string to understand which conversion to do.
You can use slicing, here is an example:
>>> a = '45F'
>>> a[-1]
'F'
>>> a[:-1]
'45'
Of course '45' is a string not a number, converting it to a number with int() will allow you do math on it.
Putting all that together, we have something like this:
a = raw_input('Enter here: ')
number = int(a[:-1])
letter = a[-1].lower()
if letter == 'f':
print('{} in C is {}'.format(a, 5*(number-32)/9))
if letter == 'c':
print('{} in F is {}'.format(a, 9*(number/5)*32))
my input is something like this
23 + 45 = astart
for the exact input when i take it as raw_input() and then try to split it , it gives me an error like this
SyntaxError: invalid syntax
the code is this
k=raw_input()
a,b=(str(i) for i in k.split(' + '))
b,c=(str(i) for i in b.split(' = '))
its always number + number = astar
its just that when i give number+number=astar i am not getting syntax error ..!! but when i give whitespace i get sytax error
Testing with Python 2.5.2, your code ran OK as long as I only had the same spacing
on either side of the + and = in the code and input.
You appear to have two spaces on either side of them in the code, but only one on either
side in the input. Also - you do not have to use the str(i) in a generator. You can do
it like a,b=k.split(' + ')
My cut and pastes:
My test script:
print 'Enter input #1:'
k=raw_input()
a,b=(str(i) for i in k.split(' + '))
b,c=(str(i) for i in b.split(' = '))
print 'Here are the resulting values:'
print a
print b
print c
print 'Enter input #2:'
k=raw_input()
a,b=k.split(' + ')
b,c=b.split(' = ')
print 'Here are the resulting values:'
print a
print b
print c
From the interpreter:
>>>
Enter input #1:
23 + 45 = astart
Here are the resulting values:
23
45
astart
Enter input #2:
23 + 45 = astart
Here are the resulting values:
23
45
astart
>>>
Edit: as pointed out by Triptych, the generator object isn't the problem. The partition solution is still good and holds even for invalid inputs
calling (... for ...) only returns a generator object, not a tuple
try one of the following:
a,b=[str(i) for i in k.split(' + ')]
a,b=list(str(i) for i in k.split(' + '))
they return a list which can be unpacked (assuming one split)
or use str.partition assuming 2.5 or greater:
a, serperator, b = k.partition('+')
which will always return a 3 tuple even if the string isn't found
Edit: and if you don't want the spaces in your input use the strip function
a = a.strip()
b = b.strip()
Edit: fixed str.partition method, had wrong function name for some reason
I think I'd just use a simple regular expression:
# Set up a few regular expressions
parser = re.compile("(\d+)\+(\d+)=(.+)")
spaces = re.compile("\s+")
# Grab input
input = raw_input()
# Remove all whitespace
input = spaces.sub('',input)
# Parse away
num1, num2, result = m.match(input)
You could just use:
a, b, c = raw_input().replace('+',' ').replace('=', ' ').split()
Or [Edited to add] - here's another one that avoids creating the extra intermediate strings:
a, b, c = raw_input().split()[::2]
Hrm - just realized that second one requires spaces, though, so not as good.
Rather than trying to solve your problem, I thought I'd point out a basic step you could take to try to understand why you're getting a syntax error: print your intermediate products.
k=raw_input()
print k.split(' + ')
a,b=(str(i) for i in k.split(' + '))
print b.split(' = ')
b,c=(str(i) for i in b.split(' = '))
This will show you the actual list elements produced by the split, which might shed some light on the problem you're having.
I'm not normally a fan of debugging by print statement, but one of the advantages that Python has is that it's so easy to fire up the interpreter and just mess around interactively, one statement at a time, to see what's going on.