My python always gives me this error..
There is no root of negative number because all bits inside are squared..help!
elif coordNumber == "4":
fourInputXOne = int(input ("Please enter the x value of the first co-ordinate "))
fourInputYOne = int(input ("Please enter the y value of the first co-ordinate "))
print ("")
fourInputXTwo = int(input ("Please enter the x value of the second co-ordinate "))
fourInputYTwo = int(input ("Please enter the y value of the second co-ordinate "))
print ("")
fourInputXThree = int(input ("Please enter the x value of the third co-ordinate "))
fourInputYThree = int(input ("Please enter the y value of the third co-ordinate "))
print ("")
fourInputXFour = int(input ("Please enter the x value of the fourth co-ordinate "))
fourInputYFour = int(input ("Please enter the y value of the fourth co-ordinate "))
print ("")
print ("Here are the co-ordinates you have entered:")
print ("1: (",fourInputXOne,",",fourInputYOne,")")
print ("2: (",fourInputXTwo,",",fourInputYTwo,")")
print ("3: (",fourInputXThree,",",fourInputYThree,")")
print ("4: (",fourInputXFour,",",fourInputYFour,")")
sideOneLength = math.sqrt((fourInputXTwo-fourInputXOne)^2 + (fourInputYTwo-fourInputYOne)^2 )
sideTwoLength = math.sqrt((fourInputXThree-fourInputXTwo)^2 + (fourInputYThree-fourInputYTwo)^2 )
sideThreeLength = math.sqrt((fourInputXFour-fourInputXThree)^2 + (fourInputYFour-fourInputYThree)^2 )
sideFourLength = math.sqrt((fourInputXOne-fourInputXFour)^2 + (fourInputYOne-fourInputYFour)^2 )
Error with the sidelengths bit.
in python you use a**b to square not a^b
the caret symbol is a binary XOR operator
elif coordNumber == "4":
fourInputXOne = int(input ("Please enter the x value of the first co-ordinate "))
fourInputYOne = int(input ("Please enter the y value of the first co-ordinate "))
print ("")
fourInputXTwo = int(input ("Please enter the x value of the second co-ordinate "))
fourInputYTwo = int(input ("Please enter the y value of the second co-ordinate "))
print ("")
fourInputXThree = int(input ("Please enter the x value of the third co-ordinate "))
fourInputYThree = int(input ("Please enter the y value of the third co-ordinate "))
print ("")
fourInputXFour = int(input ("Please enter the x value of the fourth co-ordinate "))
fourInputYFour = int(input ("Please enter the y value of the fourth co-ordinate "))
print ("")
print ("Here are the co-ordinates you have entered:")
print ("1: (",fourInputXOne,",",fourInputYOne,")")
print ("2: (",fourInputXTwo,",",fourInputYTwo,")")
print ("3: (",fourInputXThree,",",fourInputYThree,")")
print ("4: (",fourInputXFour,",",fourInputYFour,")")
sideOneLength = math.sqrt((fourInputXTwo-fourInputXOne)**2 + (fourInputYTwo-fourInputYOne)**2 )
sideTwoLength = math.sqrt((fourInputXThree-fourInputXTwo)**2 + (fourInputYThree-fourInputYTwo)**2 )
sideThreeLength = math.sqrt((fourInputXFour-fourInputXThree)**2 + (fourInputYFour-fourInputYThree)**2 )
sideFourLength = math.sqrt((fourInputXOne-fourInputXFour)**2 + (fourInputYOne-fourInputYFour)**2 )
Why are you logically XORing your values?
Printing the offending numbers:
print( (fourInputXTwo-fourInputXOne)^2 ) # you can see its negative
or experimenting:
print(6^2) # prints 4 - because 0b110^0b010 == 0b100
print(6**2) # prints 36 - because 6**2 = 6*6 = 36
would have shown you that what you do wrong.
See binary bitwise operations for the full documentation.
Related
I have a homework problem and I need to add a while loop to my function that will give the user 3 additional tries to enter another value if the value originally entered is not a number. The original function of the code is to determine the area of a triangle or trapezoid.
loopCount = 0
# The "while" statement keeps looping until its condition (loopCount<4) made False.
while loopCount<4:
# loopCount will increase 1 for each loop
loopCount += 1
Though I'm not even sure where to fit the above lines in my code.
# This program calculates the area of a triangle or trapezoid
# Statement: print function outputs the statement on screen
print("This program finds the area of a triangle or trapezoid.")
print()
# Module: math module imported
import math
# Determine the objects shape
print("Please enter the shape from the following menu")
print("Triangle = type 1")
print("Trapezoid = type 2")
# If user types a number other than 1 or 2, this will prompt them again to pick a valid choice
user_input = 0
while user_input not in (1,2) :
user_input = int(input("Enter your choice: "))
# Variables: asigns new value to a variable depending on which shape we are caluclating the area of
if (user_input == 1):
print("Alright, you want to calculate the area of a triangle: ")
height = float(input("Please enter the height of the triangle: "))
base = float(input("Please enter the base length of the triangle: "))
if (user_input == 2):
print("Alright, you want to calculate the area of a trapezoid: ")
base_1 = float(input("Please enter the base length of the trapezoid: "))
base_2 = float(input("Please enter the second base length of the trapezoid: "))
height = float(input("Please enter the height of the trapezoid: "))
# Expression and operators: calculates area based on shape choosen. Triangle_area = (base*height)/2, Trapezoid_area = ((base1+base2)/2)*height
if (user_input == 1):
area_triangle = 0.5 * height * base
if (user_input == 2):
area_trapezoid = ((base_1+base_2)/2)*height
# Function: math function returns a statement defining the height, base(s) and area of the triangle or trapezoid
if (user_input == 1):
print("The area of a triangle with height", height, "and base", base, "is", area_triangle)
if (user_input == 2):
print("The area of a trapezoid with height", height, ", base 1", base_1, "and base 2", base_2, "is", area_trapezoid)
If the user enters a value that could not be converted to numeric type, allow 3 additional opportunities to enter a new value. If the user fails to enter a correct value after 4 attempts, inform them of such failure and allow the program to end without crashing.
You can use a try/except on the input to handle the ValueError when float() fails to convert the value to a float or an OverflowError "if the argument is outside the range of a Python float".
loopCount = 0
while loopCount < 4:
try:
height = float(input("Please enter the height of the triangle: "))
break
except:
print("That is not a number.")
loopCount += 1
if loopCount == 4:
print("You failed to input valid values")
# return with an error or maybe abort with sys.exit(1)
else:
print("Great! I can now compute stuff.")
You can check for all the inputs at once inside the try block (if you don't care which one specifically is invalid or you don't need to point it out to the user):
loopCount = 0
while loopCount < 4:
try:
base_1 = float(input("Please enter the base length of the trapezoid: "))
base_2 = float(input("Please enter the second base length of the trapezoid: "))
height = float(input("Please enter the height of the trapezoid: "))
break
except:
print("One of the inputs is not a number.")
loopCount += 1
if loopCount == 4:
print("You failed to input valid values")
# return with an error or maybe abort with sys.exit(1)
else:
print("Great! I can now compute stuff.")
To avoid lots of repeated try-except's, I suggest creating a method for getting a float input (or all of the inputs), and then just calling it from your main method.
I am trying to write a program which asks an input of two numbers and then prints the sum, product and average by running it. I wrote a program but it asks an input for 2 numbers everytime i need a sum or average or product. How can I get all 3 at once, just making two inputs once.
sum = int(input("Please enter the first Value: ")) + \
int(input("Please enter another number: "))
print("sum = {}".format(sum))
product = int(input("Please enter the first Value: ")) * \
int(input("Please enter another number: "))
print ("product = {}".format(product))
Use variables to store the input:
first_number = int(input("Please enter the first Value: "))
second_number = int(input("Please enter another number: "))
sum = first_number + second_number
product = first_number * second_number
average = (first_number + second_number) / 2
print('Sum is {}'.format(sum))
print('product is {}'.format(product))
print('average is {}'.format(average))
You need to assign your numbers to variables and then reuse them for the operations.
Example
x = int(input("Please enter the first Value: "))
y = int(input("Please enter another number: "))
print("sum = {}".format(x+y))
print("product = {}".format(x*y))
print("average = {}".format((x+y)/2))
You're going to want to get the numbers first, then do your operation on them. Otherwise you're relying on the user to alway input the same two numbers:
a = int(input("Please enter the first Value: "))
b = int(input("Please enter the second Value: "))
print ("sum = {}".format(a+b))
print ("product = {}".format(a*b))
print ("average = {}".format((a*b)/2))
I have code that is supposed to determine the volume of a shape, determined by input. I have several if statements nested in a while loop. I want the loop to restart at the very beginning where it asks for input, but instead it is getting stuck in the condition statement. For example, if I enter "cube", it computes the volume and then asks me again to input the dimensions - instead I want it to ask me the shape, and proceed through the if statements again. Same at the end, if I enter a shape that isn't valid, it's supposed to ask me to input again and if that input is valid, proceed accordingly. But it doesn't, it gets stuck in an infinite loop and never stops asking me to input a shape.
import math
import decimal
shape = str(input("Please enter a shape: "))
shape = shape.lower()
shapes = ["cube", "pyramid", "ellipsoid", "quit"]
stored_cube_vol = []
stored_pymd_vol = []
stored_ellip_vol = []
while shape != "quit":
if shape == "cube":
def cube_volume(cube_side_length):
cube_total_vol = decimal.Decimal(cube_side_length**3)
return round(cube_total_vol, 2)
cube_side_length = float(input("Enter the length of length of one side of the cube: "))
print("The volume of a cube with sides with a length of", cube_side_length, "is", cube_volume(cube_side_length))
stored_cube_vol.append(cube_volume(cube_side_length))
elif shape == "pyramid":
def pymd_volume(pymd_base, pymd_height):
pymd_total_vol = decimal.Decimal(pymd_base**2)*pymd_height*(1/3)
return round(pymd_total_vol, 2)
pymd_base = float(input("Enter the length of the base of the pyramid: "))
pymd_height = float(input("Enter the height of the pyramid: "))
print("The volume of a pyramid with a base of", pymd_base, "and a height of", pymd_height, "is", pymd_volume(pymd_base, pymd_height))
stored_pymd_vol.append(pymd_volume(pymd_base, pymd_height))
elif shape == "ellipsoid":
def ellip_volume(ellip_rad_1, ellip_rad_2, ellip_rad_3):
ellip_total_vol = decimal.Decimal(math.pi*(4/3)*ellip_rad_1*ellip_rad_2*ellip_rad_3)
return round(ellip_total_vol, 2)
ellip_rad_1 = float(input("Enter the first radius: "))
ellip_rad_2 = float(input("Enter the second radius: "))
ellip_rad_3 = float(input("Enter the third radius: "))
print("The volume of an ellipsoid with radii", ellip_rad_1, ellip_rad_2, "and", ellip_rad_3, "is", ellip_volume(ellip_rad_1, ellip_rad_2, ellip_rad_3))
stored_ellip_vol.append(ellip_volume(ellip_rad_1, ellip_rad_2, ellip_rad_3))
elif shape == "quit":
print("You have come to the end of the session.")
print("The volumes calculated for each shape are shown below.")
print("Cube: ", sorted(stored_cube_vol))
print("Pyramid: ", sorted(stored_pymd_vol))
print("Ellipsoid: ", sorted(stored_ellip_vol))
else:
str(input("Please enter a shape: ").lower())
You're missing shape = in your else clause.
If I understand correctly, just remove the else clause and leave:
shape = str(input("Please enter a shape: ")).lower()
at the end of the loop.
This will ask the user as long as he didn't enter "quit", even if he did enter a valid choice.
I have made some changes to the code. I have put the statements taking input from the user into the while loop and added a break statement in the 'if=='quit'' statement.
Change 1:
import math
import decimal
shapes = ["cube", "pyramid", "ellipsoid", "quit"]
stored_cube_vol = []
stored_pymd_vol = []
stored_ellip_vol = []
shape = " "
while shape != "quit":
shape = str(input("Please enter a shape: "))
shape = shape.lower()
Change 2:
elif shape == "quit":
print("You have come to the end of the session.")
print("The volumes calculated for each shape are shown below.")
print("Cube: ", sorted(stored_cube_vol))
print("Pyramid: ", sorted(stored_pymd_vol))
print("Ellipsoid: ", sorted(stored_ellip_vol))
break
How can I get this program to stop at when the number 13 is entered?
print "\t:-- Enter a Multiplication --: \n"
x = ("Enter the first number: ")
y = ("Enter your second number to multiply by: ")
for total in range(1, 12):
x = input("Enter a number: ")
y = input("Multiplied by this: ")
print "\n TOTAL: "
print x, "X", y, "=", (x * y)
#Exits the program.
raw_input("\t\tPress Enter to Exit")
If I understand what you are trying to do here, I think an if statement would be a better solution. Something like this:
print("Enter a multiplication")
x = int(input("Enter a number: "))
y = int(input("Multiplied by this: "))
def multiply(x, y):
if 1 < x < 13 and 1 < y < 13:
answer = x * y
print("Total:")
print("%s X %s = %s" % (x, y, answer))
else:
print("Your number is out of range")
multiply(x, y)
But to be honest, there are quite a few parts of your code that some work.
You used a for loop; this is appropriate when you know before you enter the loop how many times you want to execute it. This is not the problem you have. Instead, use a while loop; this keeps going until a particular condition occurs.
Try something like this:
# Get the first input:
x = input("Enter a number (13 to quit): ")
# Check NOW to see whether we have to quit
while x <= 12:
# As long as the first number is acceptable,
# get the second and print the product.
y = input("Multiplied by this: ")
print "\n TOTAL: \n", x, "X", y, "=", (x * y)
# Get another 'x' value before going back to the top.
x = input("Enter a number (13 to quit): ")
# -- Here, you're done with doing products.
# -- Continue as you wish, such as printing a "times table".
I'm pretty new to Python, and what makes me mad about my problem is that I feel like it's really simple.I keep getting an error in line 8. I just want this program to take the numbers the user entered and print the largest and smallest, and I want it to cancel the loop if they enter negative 1.
'int' object is not iterable is the error.
print "Welcome to The Number Input Program."
number = int(raw_input("Please enter a number: "))
while (number != int(-1)):
number = int(raw_input("Please enter a number: "))
high = max(number)
low = min(number)
print "The highest number entered was ", high, ".\n"
print "The lowest number entered was ", low, ".\n"
raw_input("\n\nPress the enter key to exit.")
The problem is that number is an int. max and min both require lists (or other iterable things) - so instead, you have to add number to a list like so:
number = int(raw_input("Please enter a number: "))
num_list = []
while (number != int(-1)):
num_list.append(number)
number = int(raw_input("Please enter a number: "))
high = max(num_list)
low = min(num_list)
Just as a note after reading dr jimbob's answer - my answer assumes that you don't want to account for -1 when finding high and low.
That's cause each time you pass one integer argument to max and min and python doesn't know what to do with it.
Ether pass at least two arguments:
least_number = min(number1, number2,...,numbern)
or an iterable:
least_number = min([number1, number2, ...,numbern])
Here's the doc
You need to change number to an list of numbers. E.g.,
print "Welcome to The Number Input Program."
numbers = []
number = int(raw_input("Please enter a number: "))
while (number != -1):
numbers.append(number)
number = int(raw_input("Please enter a number: "))
high = max(numbers)
low = min(numbers)
print "The highest number entered was ", high, ".\n"
print "The lowest number entered was ", low, ".\n"
raw_input("\n\nPress the enter key to exit.")
As mentioned by another answer, min and max can also take multiple arguments. To omit the list, you can
print "Welcome to The Number Input Program."
number = int(raw_input("Please enter a number: "))
high = low = number
while (number != int(-1)):
number = int(raw_input("Please enter a number: "))
high = max(high, number)
low = min(low, number)
print "The highest number entered was ", high, ".\n"
print "The lowest number entered was ", low, ".\n"
raw_input("\n\nPress the enter key to exit.")
num = ''
active = True
largest = 0
smallest = 0
while active:
num = input("Please enter a number")
if num == 'done':
active = False
break
else:
try:
num = int(num)
if largest < num:
largest = num
if smallest == 0 or smallest > num:
smallest = num
except ValueError:
print("Please enter a valid number")
print("Largest no. is " + str(largest))
print("Smallest no. is " + str(smallest))