I've been making a linear equation calculator and I'm wondering how to let python use negative numbers. Like int(), float() etc...
here is my code.
import time
print("Hello and welcome to the linear equation calculator.")
time.sleep(2)
print("Enter the first co-ordinate like this - (xx, yy): ")
coordnte1 = input()
print("Now enter the second co-ordinate like this, with the brackets, - (xx,yy): ")
coordnte2 = input()
print("Now the y-intercept: ")
yintrcpt = input()
ydif = coordnte2[1] - coordnte1[1]
xdif = coordnte2[0] - coodrnte1[0]
g = ydif / xdif
print("y = " + g + "x + " + yintrcpt)
And the problem:
Traceback (most recent call last):
File "C:/Users/Dale/Documents/GitHub/new_python_rpi_experiments/linear.py", line 17, in <module>
ydif = coordnte2[1] - coordnte1[1]
TypeError: unsupported operand type(s) for -: 'str' and 'str'
I'm very new to Python, so any help would be appreciated.
What your are reading from the input is a string, you need to extract the coordinates and convert them to float, for example:
print("Enter the first co-ordinate like this - (xx, yy): ")
s = input()
Now s = "(34, 23)" is a string and you need to process it (eliminate parens, comma, etc...):
coords = [float(coord) for coord in s.strip('()').split(',')]
Now coords is a list(array) of floats and you can do coords[0]- coords[1] and so on.
The problem has nothing to do with negative numbers. It's that input() gives you a text string. Python doesn't know how to subtract or do math with text strings, even if they happen to contain numeric characters.
You will need to write a function to convert a string of the form (10,3) to two numbers. I'll let you explore how to do that, but the strip and split methods of the string object may be useful to you, and you can use int() or float() on a string that contains only a numeric value to convert it to an integer or floating-point numeric variable. For example: int('123') gives you the number 123.
Try int:
ydif = int(coordnte2[1]) - int(coordnte1[1])
xdif = int(coordnte2[0]) - int(coodrnte1[0])
ydif = float(coordnte2[1]) - float(coordnte1[1])
I think is your problem ...
Try using eval to convert the string to type, e.g.
coordnte1 = eval(coordnte1)
coordnte2 = eval(coordnte2)
You might want to put that in a try statement, because it will fail if the user inputs a string that can't be evaluated.
Related
This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 1 year ago.
What I'm trying to do is make a function that subtracts the total value of another variable from the main one. I tried to create this but failed... I tried doing this.
def punch():
b = random.randint(0,100)
goblinhp = 100
goblinhp = goblinhp - int(b)
print("Goblin's HP is Now: " + goblinhp)
opt = input("What do you want do? (punch/kick/heal): ")
if opt == "punch":
punch()
but, in return, it showed these error messages.
Traceback (most recent call last):
File "main.py", line 79 in <module>
punch()
File "main.py", line 76 in punch
print("Goblin's HP is Now: " + goblinhp)
TypeError: can only concatentate str (not "int") to str
what caused these errors, and how can I fix them.
The problem is that you are trying to concatenate a String with an Integer as shown in the error.
TypeError: can only concatentate str (not "int") to str
Try the following
print("Goblin's HP is Now: " + str(goblinhp))
This will convert your integer to a string.
Using f-strings is a good way to avoid these kinds of issues
print(f"Goblin's HP is Now: {goblinghp}")
This approach has two main advantages:
better readability
letting Python handle the necessary conversions automagically behind the scenes.
Corrections below. + needs two strings (for concatenation) or two integers (for addition). Can't add a string and an integer. print automatically prints the str() of each argument, so pass the integer as an argument.
import random
def punch():
b = random.randint(0,100) # this returns an int, so b will be int
goblinhp = 100
goblinhp = goblinhp - b # don't use int(b) here, redundant
print("Goblin's HP is Now:",goblinhp) # use a comma to print string, then int
opt = input("What do you want do? (punch/kick/heal): ")
if opt == "punch":
punch()
I keep getting the same error.
This is probably a simple mistake, I just haven't coded in a while.
#import
import math
#initailse variables
float(x1)=0.0
float(y1)=0.0
float(x2)=0.0
float(y2)=0.0
float(complete_y)=0.0
float(complete_x)=0.0
float(final_decimal)=0.0
float(heading)=0.0
#get input
print("Welcome user!")
print("please enter your coordinates in format x and y including
negatives")
x1=input()
y1=input()
print("please enter the coordinates of your target in the format x and y
including negatives, you can obtain these from the map")
x2=input()
y2=input()
print("please hold for calculation")
#calculate
y2-y1==float(complete_y)
x2-x1==float(complete_x)
y/x==float(final_decimal)
math.asin(a)==float(heading)
#output
print("fire at a heading of", heading, "not including the negative if
there is one")`enter code here`
print("press enter to close the programme")
Results in an error
expected result is a heading in degrees.
My guess is that you are tying to declare the types before assigning values such as :
float(x)=0.0
x = input()
In python, the type is only known at runtime and you cannot declare type of a variable.
If you do :
x = 0.0
x = input()
print(type(x))
You will see x is a string, because you assigned a string with the input method. If you need a float, you need to convert it.
x = float(input())
As a side note,
#calculate
y2-y1==float(complete_y)
This code is valid if y1, y2 and complete_y are declared before, it just returns a Boolean, True or False. And do not assign any values.
If you need to assign value, use a single = such as
complete_y = y2 - y1
You can't do
float(x)=0.0
You're calling a function float on a value x and trying to assign 0.0 to the result of that call, which Python doesn't understand. Python knows the type of 0.0, you don't have to specify that it's a float. Just do
x = 0.0
Also, I'm not sure what you expect your #calculate section to do, but at the moment it won't have any effect on the rest of the program in any way.
I am trying to make a program that can find a definite integral but when i run it I get an error message that i can not figure out even after searching on several websites for the answer. This is my code:
class Intagrals:
def main(self):
Coefficient = input("Coefficeient: ")
Exponet = input("Exponet: ")
X_start = input("X_Start: ")
X_end = input("X_End: ")
self.equation_parts(Coefficient,Exponet,X_start,X_end)
'''
For main to always run: if __name__ == '__main__':
main()
'''
def equation_parts(self,coefficient,exponet,x_start,x_end): #x_start and x_end are the beggining and end valuse to be set for x in the intagral
exponet += 1 #adds one to exponet for equation to be solved correctly
a_over_n_plus_1_x = coefficient/exponet #creates terms before x
def math_of_intagral(self):
solve_for_x = self.a_over_n_plus_1_x * self.x_end
raise_to_power_end_x = solve_for_x ** self.exponet
if self.x_start != 0:
solve_for_start_x = self.a_over_n_plus_1_x * self.x_start
raise_to_power_start_x = solve_for_start_x ** self.exponet
return raise_to_power_end_x - raise_to_power_start_x
else:
return raise_to_power_end_x
intagrals = Intagrals()
Then it displays this error message after I enter some code:
> >>> intagrals.main()
Coefficeient: 1
Exponet: 2
X_Start: 0
X_End: 2
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
intagrals.main()
File "C:/Users/owner/AppData/Local/Programs/Python/Python36-32/intagrals.py", line 15, in main
self.equation_parts(Coefficient,Exponet,X_start,X_end)
File "C:/Users/owner/AppData/Local/Programs/Python/Python36-32/intagrals.py", line 22, in equation_parts
exponet += 1 #adds one to exponet for equation to be solved correctly
TypeError: must be str, not int
Can someone Please help?
Whenever you use the input function in python, it returns a string. To quote the docs (emphasis mine):
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
As you see from the docs, the input() function converts the input to a string and returns it. Thus, you cannot perform operations like += 1 on it as it is a string.
To convert a string to an int, you need to use the int() function. Thus, the line of code will be:
Exponet = int(input("Exponet: "))
This will fix your issue as the int() function will cast the string to an int and then you should be able to perform operations like += on them.
Side Note: Exponet is a wrong spelling, it is Exponent (note the extra n).
You are reading the Exponet from input and that is always a string, when you try to increment it with exponet += 1 it gives that error.
You should modify your input to get an integer ant not a string, so change this line
Exponet = input("Exponet: ")
to this
Exponet = int(input("Exponet: "))
if you use
something = input("Exponet: ")
python takes it always as string. So to convert it into integer using
something = int(input("Exponet: "))
Here when you input Exponet: 2, Python thinks it is a string but when you try to increment it fails to increment the integer value because of you input string.
Your code is missing self. before the a_over... variable that you set in the equation_parts method. Later, you're referring to this variables using self.a_... which causes the AttributeError to be thrown.
I have been working on this code for a while, and this error poped up. And I dont know alot about it...
minimun = raw_input("Minimum length of any give word to be generated: ")
maximun = raw_input("Maximum length of any give word to be generated: ")
maximunWords = raw_input("Maximun number of words to be generated in the diccionary: ")
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYX0123456789'
string = ""
create = open('wordlist.txt', 'w')
print "Creating..."
time.sleep(2)
print "Start Time: ", time.strftime('%H:%M:%S')
for i in xrange(0,maximunWords):
for x in random.sample(alphabet,random.randint(minimun,maximun)):
string+=x
create.write(string+'\n')
string = ""
create.close()
print "End Time: ", time.strftime('%H:%M:%S')
This especific block is givin me this error
for i in xrange(0,maximunWords):
for x in random.sample(alphabet,random.randint(minimun,maximun)):
string+=x
The error says this:
File "ACU-Tool.py", line 62, in <module>
for i in xrange(0,maximunWords):
TypeError: an integer is required
enter code here
The reason you are receiving a TypeError is because maximunWords is not of type integer, but rather of type string. You need some integer for the second parameter in xrange since you need some integer to determine when to "stop" the range.
The problem is that maximunWords isn't an integer; it is a string returned by raw_input(). Obviously, the xrange function needs integer arguments, not strings.
Change the code to convert the user input to integers and the code will work better:
minimun = int(raw_input("Minimum length of any give word to be generated: "))
maximun = int(raw_input("Maximum length of any give word to be generated: "))
maximunWords = int(raw_input("Maximun number of words to be generated in the diccionary: "))
This program is supposed to calculate the number of degrees below 60 on a given day then create a running sum of degrees. count equals the sum of degrees below 60. However, when I run it I get this error:
cool = 60 - temp
TypeError: unsupported operand type(s) for -: 'int' and 'str'
Any ideas on why it's doing this? Thanks!
def cold_days():
temp = eval(input("What is the temperature? "))
count = 0
if temp < 60:
while temp !="quit":
temp = eval(input("What is the temperature? "))
cool = 60 - temp
count = count + heat
print(count)
else:
print("you have no cold days")
You need to turn temp into an int:
...
try:
temp = int(temp)
except TypeError:
# Handle invalid integer
print("%s is not a valid integer." % temp)
sys.exit(1)
...
In Python 3, the input() function always returns a string (this is different from Python 2, and could be the source of the confusion since the Python tutorial you're using might be unaware of Python 3). Since Python is strongly (but dynamically) typed, you can't perform arithmetic calculations using a string and an integer, as your error message shows. You must first convert the temp string into an integer using int():
temp = int(temp)
If temp does not contain something that can be converted to an integer, you will get a ValueError exception. By default, an exception will terminate your program with an informative error message. To handle the exception and take alternative action, your Python tutorial should have a whole chapter on that.
You can just drop the 'eval' since input does return the correct type. Or typecast the temp to int:
temp = int(temp)
I think you need to rethink how you are reading in data. input() returns eval() of whatever text the user types in, so I would expect an error when the user types "quit".
Instead, I suggest using raw_input() which returns text. Then check if it is equal to "quit" before converting to an int.