This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Python noob here. I'm trying to add a set of input variables defined in an 'if' statement and whenever I try to find the sum it will just display the values inline. For example, when a, b, c, and d equal 5, perimeter = 555...
shape = raw_input("Is the plot a (q) quadrilateral or (t) triangle?")
if shape.lower() == "q":
a = raw_input("What is the length in feet of side 'a'?")
b = raw_input("What is the length in feet of side 'b'?")
c = raw_input("What is the length in feet of side 'c'?")
d = raw_input("What is the length in feet of side 'd'?")
elif shape.lower() == "t":
a = raw_input("What is the length in feet of side 'a'?")
b = raw_input("What is the length in feet of side 'b'?")
c = raw_input("What is the length in feet of side 'c'?")
else:
print "Please enter 'q' for quadrilateral or 't' for triangle."
if shape.lower() == "q":
perimeter = a + b + c + d
elif shape.lower() == "t":
perimeter = a + b + c
else:
print "Please make sure you enter numbers only."
print perimeter
str values can be added to each other much like numbers. The + operator you use works fine, but concatenates values for strings. The result of raw_input is a string (str), so that's why you'd see '555' in stead of 15. To sum numbers, use int() to coerce the values to numbers before adding them up:
try:
a = int(raw_input('gimme a number'))
except ValueError as e
print 'that was not a number, son'
Make sure that your raw_input actually Is an int():
shape = raw_input("Is the plot a (q) quadrilateral or (t) triangle?")
if shape.lower() == "q":
try:
a = raw_input("What is the length in feet of side 'a'?")
b = raw_input("What is the length in feet of side 'b'?")
c = raw_input("What is the length in feet of side 'c'?")
d = raw_input("What is the length in feet of side 'd'?")
perimeter = int(a) + int(b) + int(c) + int(d)
except ErrorValue as e
print "Please make sure you enter numbers only."
elif shape.lower() == "t":
try:
a = raw_input("What is the length in feet of side 'a'?")
b = raw_input("What is the length in feet of side 'b'?")
c = raw_input("What is the length in feet of side '
perimeter = int(a) + int(b) + int(c)
except ErrorValue as e
print "Please make sure you enter numbers only."
else:
print "Please enter 'q' for quadrilateral or 't' for triangle."
for variables a, b, c, and d, use input(prompt) instead of raw_input(prompt).
raw_input returns a string,
but input returns the console input evaluated as a python literal. (As of right now, you're
concatenating strings, not adding integers).
Your code is not a good design. What if you want to add more shapes, hexagon, octagon and so on. You can actually use a dict to store shape mapping to number of sides. You don't have to write multiple if statements for each shape. You will have to do less type checking and you could use python builtin function sum to return the parameter. Go on now and try the following:
d = {'q': 4, 't': 3}
shape = raw_input("Is the plot a (q) quadrilateral or (t) triangle?\n")
if shape.lower() not in d:
print "Please enter 'q' for quadrilateral or 't' for triangle."
else:
sides = []
for i in range(0,d.get(shape.lower())):
side = raw_input("What is the length in feet of side " + str(i+1))
try:
sides.append(int(side))
except ValueError:
print "Integer value only"
print sum(sides)
I did this using a dictionary.
sides = {'a':0,'b': 0,'c': 0,'d': 0}
perimeter = 0
shape = raw_input("Is the plot a (q) quadrilatral or (t) triangle?: ")
if shape.lower() == "q":
for side, length in sides.iteritems():
sides[side] = input("What is the length (in feet) of side %s?: " % side)
perimeter+=int(sides[side])
elif shape.lower() == "t":
sides.pop("d",None)
for side, length in sides.iteritems():
sides[side] = input("What is the length (in feet) of side %s?: " % side)
perimeter+=int(sides[side])
else:
print "Please enter 'q' or 't'."
print "Perimeter is: %d" % perimeter
I figured a dictionary would be easier to use. Might be much cleaner, rather than repeat yourself.
Related
I need to create a program that calculates the vector resultant but I need to allow the user to choose between polar and cartesian coordinates. This is what I have so far but it gives me errors and I am not sure what to do to ask the user both x,y coordinates and how to make the program stop after the vectors have been entered. Please help, I don't know much about this!
import math
#calculate vector components and change from polar to cartesian and vice versa
def fxcomponent(x, y): # to find cartesian x
number = x
y = math.cos(math.degrees(y))
result = number * y
return result
def fycomponent(x, angle): #to find cartesian y
number = x
angle = math.sin(math.degrees(angle))
result = number * angle
return result
def polar_length(r,t): #to find polar lenght
number = r
length =((r**2) + (t**2))
result = math.sqrt(number)
return result
def polar_angle(r,theta): #to find polar angle
result = math.atan2(theta,r)
return result
#prompts
prompt = 'Hi!'
type_coor = input('Enter the type of coordinate you will use: use p for polar \n enter c for cartesian')
vector_number = input('Enter the number of vectors you will be adding: ')
i = 0
while i <= vector_number:
if type_coor == 'p': #if polar values are entered
print('What is the r value?:')
x, angle = [int(x) for x in input('>').split()]
result = fxcomponent(x, angle)
print('The x component of %d at %d° is: %d' % (x, angle, result))
elif type_coor == 'p':
print ('What is the value of the angle?:')
y, angle = [int(x) for x in input('>').split()]
result = fycomponent(y, angle)
print('The y component of %d at %d° is: %d' % (y, angle, result))```
there are a lot of different error sources here, this is a difficult task...
First, this code will break if someone enters something unexpected,
to fix this you can use if conditions to check if input values are ok like this :
variable = input('enter "c" or "p" \n>>')
if variable not in ['c','p']: # to check if variable is in the list
exit() # quit the program
# and for a number (integer only !!!)
variable = input('enter a number \n>>')
if !variable.isnumeric():
exit()
then, I don't know much about the math you use here, but, if your 4 functions at the top are correct, then you should ask for each variable with a different input and use your if ... elif only to differenciate between type_coord == 'p' and type_coord == 'c'
something like this works, but it is only with integers and I believe this is not what you want :
#prompts
prompt = 'Hi!'
type_coor = input('Enter the type of coordinate you will use: \nuse p for polar \nenter c for cartesian \n("q" for quit):\n>> ')
if type_coor not in ['c', 'p']:
print('coordinate type must be "c" or "p"')
exit() # quitting the program
vector_number = input('Enter the number of vectors you will be adding: \n>> ')
if vector_number.isnumeric() == False:
print('must be integer')
exit()
vector_number = int(vector_number)
i = 0
while i < vector_number:
if type_coor == 'p': #if polar values are entered
r = input('What is the r value?: \n>>')
if r.isnumeric() == False:
print('r must be integer')
exit()
r = int(r)
t = input('What is the t value?: \n>>')
if t.isnumeric() == False:
print('theta must be integer')
exit()
t = int(t)
theta = input('What is the theta value?: \n>>')
if theta.isnumeric() == False:
print('theta must be integer')
exit()
theta = int(theta)
length = polar_length(r, t)
angle = polar_angle(r,theta)
print('length = %d' % (length))
print('angle = %d' % (angle))
elif type_coor == 'c': # if cartesian values are entered
# do the same for cartesian coordinates
i += 1
if you want to work with decimal values, then the code gets even more complicated. For each float value you should do something like this :
variable = input('enter a decimal \n>> ')
try:
variable = float(variable)
except ValueError:
print('not a decimal')
exit()
... And the final step, is to replace all the if input condition checking by while loops that ask the user to enter a value until this value is correct...
Hope this helps, have fun!
Starting on my first project, a calculator which solves different math problems. At this stage it only does Pythagora's theorem (it has options to calculate the hypotenuse or another side). There is also an option to convert temperatures, though the actual code isn't implemented yet.
I try to run the code with the latest version of python and it does that thing where it opens for a split second and then closes. I know this means something in the code is wrong. Because I'm new to this, I get things wrong a lot and I'm having trouble finding my mistakes.
This is my code if anyone wants to read it. Feedback is appreciated and I'm happy to answer any questions.
option = input("1. Pythagora's Theorem 2. Tempurature Conversions")
option = int(option)
if option == 1:
op = input("1. Calculate the length of the hypotenuse 2. Calculate the length of another side")
op = int(op)
if op == 1:
a = input("Enter the length of side a: ")
b = input("Enter the length of side b: ")
a = int(a)
b = int(b)
c = a*a + b*b
print(c)
print ("Answer is in surd form.")
if option == 2:
a = input("Enter the length of side a: ")
hyp = input("Enter the length of the hypotenuse: ")
a = int(a)
hyp = int(hyp)
b = hyp*hyp - a*a
print(b)
print("Answer is in surd form.")
else:
print("That is not a valid option. Enter a valid option number.")
else: ("That is not a valid option. Eneter a valid option number.")
Edit: It is fixed, problem was a missing ")" and probably my weird indentation. It all works fine now, thanks for all the help, it makes learning this much easier!
The python interpreter should actually give you feedback. Run python directly from a terminal so that your program doesn't close.
Here's a fixed version of your code which works:
option = input("1. Pythagora's Theorem 2. Tempurature Conversions")
option = int(option)
if option == 1:
op = input("1. Calculate the length of the hypotenuse 2. Calculate the length of another side")
op = int(op)
if op == 1:
a = input("Enter the length of side a: ")
b = input("Enter the length of side b: ")
a = int(a)
b = int(b)
c = a*a + b*b
print(c)
print ("Answer is in surd form.")
elif op == 2:
a = input("Enter the length of side a: ")
hyp = input("Enter the length of the hypotenuse: ")
a = int(a)
hyp = int(hyp)
b = hyp*hyp - a*a
print(b)
print("Answer is in surd form.")
else:
print("That is not a valid option number.")
Please note that most programmers use 4 spaces to indent code.
You're missing a ")" on line
a = input("Enter the length of side a: "
You havent followed proper indentations, and you have made one logical mistake
option = input("1. Pythagora's Theorem 2. Tempurature Conversions > ")
option = int(option)
if option == 1:
op = input("1. Calculate the length of the hypotenuse 2. Calculate the length of another side > ")
op = int(op)
if op == 1:
a = input("Enter the length of side a: ")
b = input("Enter the length of side b: ")
a = int(a)
b = int(b)
c = a*a + b*b
print(c)
print ("Answer is in surd form.")
elif op == 2:
a = input("Enter the length of side a: ")
hyp = input("Enter the length of the hypotenuse: ")
a = int(a)
hyp = int(hyp)
b = hyp*hyp - a*a
print(b)
print("Answer is in surd form.")
else:
print("That is not a valid option. Enter a valid option number.")
elif option == 2:
print("You havent programmed it")
else:
print("That is not a valid option. Eneter a valid option number.")
I am learning python and I am having a hard time with a practice sheet where I am trying to convert millimeters to inches and vice versa. I am building it off a similar script that converts Fahrenheit to Celsius (and also vice versa).
Here's the script that converts F <-> C:
temp = input("Input the temperature you like to convert? (e.g., 45F, 102C etc.) : ")
degree = int(temp[:-1])
i_convention = temp[-1]
if i_convention.upper() == "C":
result = int(round((9 * degree) / 5 + 32))
o_convention = "Fahrenheit"
elif i_convention.upper() == "F":
result = int(round((degree - 32) * 5 / 9))
o_convention = "Celsius"
else:
print("Input proper convention.")
quit()
print("The temperature in", o_convention, "is", result, "degrees.")
I wrote this, based on the one above:
meas = input("Convert mm to in and vice versa, enter a value (e.g. 10mm, 2in): \n")
num = int(meas[:-2])
i_measType = meas[-2]
if i_measType.upper() == "MM":
result = int((num * (1/25.4)))
o_measType = "in"
elif i_measType.upper() == "IN":
result = int((num * 25.4))
o_measType = "mm"
else:
print("Input proper convention.")
quit()
print(meas, " = ", result, o_measType)
I assume the problem is with the [:-2] and the [-2] because based on what I can understand, this part is used to maybe pull the convention from the number? I thought like if someone enters 44mm, meas[:-2] is used to convert that to 44 and the meas[-2] is mean to call the mm. But I am clearly wrong...
Any help and possibly explanation would be greatly appreciated.
The error is:
ValueError: invalid literal for int() with base 10:
meas[-2] is the 2nd to the last characters in the input string meas, in your case, it can either be 'm' or 'i'. It's a single character.
you can change your if/else conditions to
if i_measType.upper() == "M" ...
or change your i_measType = [-2:]
to fix the problem.
My program is supposed to answer equations in the form ax = b
a = input("What is the part with the variable? ")
b = input("What is the answer? ")
print('the equation is', a , '=', b)
letter = a[-1]
number = a[0:-1]
answer = b /= number
print(letter,"=",answer)
In line 6, I'm getting an invalid syntax error. How can do it to answer the equation?
a = input("What is the part with the variable? ")
b = input("What is the answer? ")
print('the equation is', a , '=', b)
letter = a[-1]
number = a[0:-1]
answer =float(b)/float(number)
print(letter,"=",answer)
What is the part with the variable? 25c
What is the answer? 8
the equation is 25c = 8
c = 0.32
A quick solution. Note, you need to change the type of your input from string (I used float for this, but integer should also work).
a = float(input("What is the part with the variable? "))
b = float(input("What is the answer? "))
print('the equation is',a,'* X =',b)
# solve the equation: aX = b for X
x = b/a
print("X =",x)
This is a better version of you code :
a = input("What is the part with the variable? ")
b = input("What is the left hand side of the equation? ")
print('the equation is {}x = {}'.format(a , b))
answer = float(b) /float(a) // convert the inputs to floats so it can accept mathematical operations
print("x=",answer)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The Problem has been solved. However, my account is new, so it won't let me answer the question. It seems that changing the instances of input() with raw_input() makes it work. I honestly have no clue why, but it may have something to do with the differences between 2 and 3.
I'm supposed to make a program that can calculate area and circumference. That part hasn't been so difficult.
However, the menu isn't working. The first part of the menu works just fine, but after you make a selection, it doesn't print what it's supposed to.
import math
print ("""
1) Calculate circumference
2) Calculate area
""")
ans = input("Enter 1, 2, or 0 to exit this program: ")
if ans == "1":
diameter = float(input("Enter the diameter: "))
if diameter > 0:
circumference = (diameter*math.pi)
print("The circumference is", circumference)
else:
print("Error: the diameter must be a positive number.")
if ans == "2":
radius = float(input("Enter the radius: "))
if radius > 0:
area = ((radius**2)*math.pi)
print("The area is", area)
else:
print("Error: the radius must be a postive number.")
if ans == "0":
print("Thanks for hanging out with me!")
quit()
After indenting properly, change if ans == "1" to str(ans) == "1" or ans == 1 and it should be fine.
This should work:
import math
print ("""
1) Calculate circumference
2) Calculate area
""")
ans = input("Enter 1, 2, or 0 to exit this program: ")
if str(ans) == "1":
diameter = input("Enter the diameter: ")
print diameter
if float(diameter) > 0.0:
circumference = (diameter*math.pi)
print("The circumference is", circumference)
else:
print("Error: the diameter must be a positive number.")
....
PS: As mentionned in the comments, it works, but it is disgusting. We should only use ans == 1 or modify input to input_raw if you use python < python 3
Your code's indentation shows the span of control of each 'if', 'for', or 'while'.
You need to further indent the instructions under each major 'if' statement so that
they only get executed when that 'if' statement is selected. Otherwise, everything
that is at the leftmost indentation gets executed every time through the loop. For example, you should have something like:
if answer == '1':
....<statements that execute under condition 1>
elif answer == '2':
....<statements that execute under condition 2>
where I have emphasized the indentation with '....'.
The second if statement is not within the brackets of the first. this is true for both 1 and 2.
if ans == "1";
diameter = float(input("enter the diameter: "))
if diameter ....
for me treating ans as integer worked. What I mean by treating ans as integer is instead of writing ans=="1" ,I wrote ans==1.it print corret cvalue. Check this code:
import math
print ("""
1) Calculate circumference
2) Calculate area
""")
ans = input("Enter 1, 2, or 0 to exit this program: ")
print ans
if ans ==1:
diameter = float(input("Enter the diameter: "))
if diameter > 0:
circumference = (diameter*math.pi)
print("The circumference is", circumference)
else:
print("Error: the diameter must be a positive number.")
if ans == 2:
radius = float(input("Enter the radius: "))
if radius > 0:
area = ((radius**2)*math.pi)
print("The area is", area)
else:
print("Error: the radius must be a postive number.")
if ans == 0:
print("Thanks for hanging out with me!")
quit()