I am trying to make a cosine law calculator in python - python

I am trying to write a program that takes side "a" and side "b" and angle "C". Then it will output side "c".
I am getting an int error and I don't know whats wrong
Here is my code:
import math
def triangle():
a=input("Enter side a:")
b=input("Enter side b:")
angle=input("What is the angle:")
side=(a**2)+(b**2)
rest=(2*(a*b))(math.cos(angle))
done=side-rest
end=math.sqrt(done)
print end
triangle()

It might because you missed a "*" in:
rest=(2*(a*b))(math.cos(angle))
it should be:
rest=(2*(a*b)) * (math.cos(angle))

Your problem is this line:
rest=(2*(a*b))(math.cos(angle))
You are missing a * operator:
rest=(2*(a*b))*(math.cos(angle))
You've also got some excessive use of parenthesis:
rest = 2 * a * b * math.cos(angle)
The cause of the problem is that python thought you were trying to invoke the result of the expression (2*(a*b)). However that is an int, and it is not a callable object.

Related

Beginner Python surface calculation of a hut

I'm trying to make a program to calculate the surface area of ​​a shack with a pitched roof. I've only been in this class for 2 weeks and I'm a bit overwhelmed. The program should ask the user via console for the values ​​and then calculate the values ​​using the definition.
I'm not asking for the entire code at all. But I don't understand how I can calculate inputs using a definition and then print them. this is my code so far:
import math
def floorspace(a,b):
G = 0
G = a*b
return (G)
#main program
a = int(input("enter the length of the floor!"))
b = int(input("Enter the width of the floor!"))
print(floorspace, G)
You don't need to import math as basic multiplication is already included. You also don't need to initialize a variable before you assign it so I removed the
G = 0
G = a*b
lines and replaced it with a simple
return a*b
You don't need brackets around a return statement, just a print statement.
The final two issues are that you're printing incorrectly and you used the wrong function parameters. You would need to pass in the same number of parameters that are in the function declaration (so in this case, 2). Pass in a and b from the user inputs into your floorspace() function and then call print(). The code should work now!
def floorspace(a,b):
return a*b
#main program
a = int(input("enter the length of the floor!"))
b = int(input("Enter the width of the floor!"))
print(floorspace(a,b))
in your code print(floorspace,G) G is not defined you must write your it like this print(floorspace(a,b))

Hollow square function with two inputs?

I've been struggling to create a function that can put out a default hollow square of 5x5 but then also take in 2 inputs.
Here's the question:
create a charsqr.py function that when imported will result in the following:
Program:
def main():
charsqr()
charsqr(4)
charsqr(3,'#')
main()
Result:
*****
* *
* *
* *
*****
****
* *
* *
****
###
# #
###
Here's my code:
def charsqr(chars,sym):
if type(chars) = int and type(sym)=str:
print(str(sym)*chars)
for i in range(chars-2):
print(str(sym)+" "*(chars-2)+str(sym))
print(str(sym)*chars)
else:
print("*"*5)
for i in range(5):
print("*"+" "*3+"*")
print("*"*5)
I've been fiddling around with the if statement as I've been getting "missing 2 positional arguments" error. I know how to create a hollow square, just not sure how to get the program to print the default square and then a square with the given "chars" without needing a "sym".
Any feedback is appreciated ! :)
You're complicating this way too much, a simple:
def draw_square(size=5, edge="*", fill=" "):
hollow = size - 2 # just so we don't calculate the hollow part each time
print(edge * size) # top part
for _ in range(hollow): # iterate until the last line
print(edge + fill * hollow + edge) # middle part
print(edge * size) # bottom part
Should do the trick. You can even change the 'hollow' part to some character.
You apparently want a function that uses an asterisk if no character is stated, and uses size 5 if no size is stated. That is what default parameters are for in Python:
def charsqr(chars=5, sym='*'):
Then calling charsqr() is the same as charsqr(5, '*'), and calling charsqr(4) is the same as charsqr(4, '*'). Calling charsqr(3, '#') uses no defaults.
Note that the code you show has bad indentation and will give a syntax error. Indent the lines of your function (everything but the def line). Also replace the = symbols in your if line with ==. With those three changes, your code works and gives the desired output.

How can I pass user input in the form of a variable to a lambda function in python?

so I'm kind of new to programming and I was looking for some help. I'm making a graphing calculator and would like to have the user enter an equation using x such as (x + 3) or (x^2 + 3x + 4). I recently found out about the lambda function and was wondering if there was a way to pass a variable to it in order to get plot points with the user's equation. I plan on using a for loop to keep passing new values into the equation. If you have any other suggestions on how to go about completing my graphing calculator please do not hesitate to inform me. My code so far is only a way for the user to navigate through my program. Here is my code:
def main():
while True:
response = menu()
if response == "1":
print("enter an equation in the form of mx + b")
equation = (input())
print(coordinates(equation))
elif response == "2":
print("enter a value for x")
x = input()
print("enter a value for y")
y = input()
elif response == "0":
print("Goodbye")
break
else:
print("please enter '1' '2' or '0'")
def menu():
print("Graphing Calculator")
print("0) Quit")
print("1) Enter an equation")
print("2) Plot points")
print("Please select an option")
response = input()
return response
"""def coordinates(equation):
f = lambda x: equation
"""
if __name__ == "__main__":
main()
I get that I'm answering your question twice. But this time, I'm gonna show you something pretty freaking cool instead of just fixing your code.
Enter: Sympy. Sympy is a module of the Numpy package that does symbolic manipulation. You can find some documentation here.
Great, another module. But what does it do?
Sympy keeps equations and expressions as symbols instead of variables. Go ahead and import sympy or pip install it if you don't have it. Now, let's build an evaluation unit for that monovariate equation coordinate finder. First, let's make sure python knows that x is a sympy symbol. This is important because otherwise, python treats it like a normal variable and doesn't hand control over to sympy. Sympy makes it easy to do this, and even supports making multiple symbols at once. So go ahead and do x, y, z = sympy.symbols("x y z"). Now, let's ask for the function.
def make_an_equation(raw_equation = ""):
if raw_equation == "": #This allows for make_an_equation to be used from the console AND as an interface. Spiffy, no?
raw_equation = raw_input("Y=")
#filter and rewrite the equation for python compatibility. Ex. if your raw_equation uses ^ for exponentiation and XOR for exclusive or, you'd turn them into ** and ^, respectively.
expr = eval(filtered_equation)
return expr
Ok, you've got a thing that can make an equation. But... You can't quite use it, yet. It's entirely symbolic. You'll have to use expr.subs to substitute numbers for x.
>>> my_expression = make_an_equation("x**2") #I'm assuming that the filter thing was never written.
>>> my_expression
x**2
>>> my_expression.subs(x,5)
25
See how easy that is? And you can get even more complex with it, too. Let's substitute another symbol instead of a number.
>>> my_expression.subs(x,z)
z**2
Sympy includes a bunch of really cool tools, like trig functions and calculus stuff. Anyways, there you go, intro to Sympy! Have fun!
So... I went ahead and reviewed your whole code. I'll walk you through what I did in comments.
def main():
while True:
response = raw_input("Graphing Calculator\n0) Quit\n1) Enter an equation\n2) Plot points\nPlease select an option\n>>>")
#I removed menu() and condensed the menu into a single string.
#Remember to use raw_input if you just want a string of what was input; using input() is a major security risk because it immediately evaluates what was done.
if response == "1":
print("Enter an equation")
equation = raw_input("Y=") #Same deal with raw_input. See how you can put a prompt in there? Cool, right?
finished_equation = translate_the_equation(equation)
#This is to fix abnormalities between Python and math. Writing this will be left as an exercise for the reader.
f = coordinates(finished_equation)
for i in xrange(min_value,max_value):
print((i,f(i))) #Prints it in (x,y) coordinate pairs.
elif response == "2":
x = raw_input("X=? ")
y = raw_input("Y=? ")
do_something(x,y)
elif response == "0":
print("Goodbye")
break
else:
print("please enter '0', '1', or '2'") #I ordered those because it's good UX design.
coordinates = lambda equation: eval("lambda x:"+ equation)
#So here's what you really want. I made a lambda function that makes a lambda function. eval() takes a string and evaluates it as python code. I'm concatenating the lambda header (lambda x:) with the equation and eval'ing it into a true lambda function.

Python - turn some of the words in list/str to dots. len(list)?

I've started learning Python last week on codecademy and Google etc. but got stuck and couldn't find the answer anywhere so signed up on stackoverflow.com looking for your support.
I'm trying to build a program that only takes first 5 letters of any name and the remainder of the letter(s) to be shows as blank dot(s). e.g.
Adrian: "Adria."
Michael: "Micha.."
Alexander: "Alexa...." etc.
I tried to "fix" it with the "b" variable but that just prints three dots "..." regardless of how long the name is.
This is what I've got so far:
def namecheck():
name = raw_input("Name?")
if len(name) <=5:
print name
else:
if len(name) >5:
name = name[0:5]
b = ("...")
print name + b
namecheck()
I'm a total newbie so I apologise for any wrong spacing here, thank you for your support and patience.
As an alternative to sequence multiplication (one which is somewhat more self-documenting, and hopefully less confusing to maintainers), just use str.ljust to do your padding:
def namecheck():
name = raw_input("Name?")
# Reduce to first five (or less) characters, then pad with .s to original length
# with str.ljust
print name[:5].ljust(len(name), '.')
print name[:5] + '.' * (len(name) - 5) works fine, it's just a bit arcane (and also involves more temporary values, though in practice, the lack of actual method calls makes it faster on CPython).
you can try to use the function replace().
name = 'abcdefg'
name.replace(name[5:], '.' * len(name[5:]))
output: 'abcde..'
name='randy12345'
name.replace(name[5:],'.' * len(name[5:]))
output: 'randy.....'
name[5:] means get all the element starting 6 (5+1 because it start with 0)
'.' * len(name[5:] then this code count it and multiply it by dot
name.replace(name[5:],'.' * len(name[5:])) then use replace function to replace the excess element with dots
The most concise way I can think of:
def namecheck():
name = raw_input("Name?")
print(name[0:5] + '.' * (len(name) - 5))
namecheck()
Try something like this:
def namecheck():
name = raw_input("Name?")
if len(name) <= 5:
print name
else:
print name[0:5] + '.' * (len(name)-5)
namecheck()

Square root function in Python - what's wrong with it?

I literally just started learning Python this week. (I will be a computer science fresher in a month!)
Here's a function I wrote to compute the square root of x.
#square root function
def sqrt(x):
"""Returns the square root of x if x is a perfect square.
Prints an error message and returns none if otherwise."""
ans = 0
if x>=0:
while ans*ans <x:
ans = ans + 1
if ans*ans == x:
print(x, 'is a perfect square.')
return ans
else:
print(x, 'is not a perfect square.')
return None
else: print(x, 'is a negative number.')
But when I save it and type sqrt(16) into the Python shell, I get an error message.
NameError: name 'sqrt' is not defined
I'm using Python 3.1.1.
Is there something wrong with my code?
Any help would be appreciated.
Thanks
UPDATE
Okay, thanks to you guys I realized I hadn't imported the function.
And when I tried to import it, I got an error because I saved it in a generic My Documents file instead of C:\Python31. So after saving the script as C:\Python31\squareroot.py, I typed into the shell (having restarted it):
import squareroot
And got a NEW error!
>>> import squareroot
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import squareroot
File "C:\Python31\squareroot.py", line 13
return ans
SyntaxError: 'return' outside function
Meaning there WAS a bug in my original code! I'm going to look at some of the suggested corrections below right now. If you've spotted anything else, say. Thanks :)
UPDATE 2 - IT WORKED!!!!!!!!!!
Here's what I did.
First, I used a cleaned up version of code kindly posted by IamChuckB. I made a new script with this in it (changed the function name from sqrt to sqrta to differentiate):
def sqrta(x):
"""Returns the square root of x if x is a perfect square.
Prints an error message and returns none if otherwise."""
ans = 0
if x>=0:
while ans*ans <x:
ans = ans + 1
if ans*ans == x:
print(x, 'is a perfect square.')
return ans
else:
print(x, 'is not a perfect square.')
return None
else:
print(x, 'is a negative number.')
And, importantly, saved it as C:\Python31\squareroota.py (Again, added an "a" at the end to differentiate between this the other, failed, file.)
Then I reopened Python shell and did this:
>>> import squareroota
Nothing happened, no error, great! Then I did this:
>>> squareroota.sqrta(16)
And got this!
16 is a perfect square.
4
Wow. I know this might seem like playing with ABC blocks in school but it honestly blew my mind. Thank you very much everyone!
Yes I believe you have to actually import your function into the shell.
from yourfile import sqrt
Be careful. I think if you're in the shell and you make changes, you have to reimport your function for those changes to show up. As delnan mentions below you can reload
your file after changeing it..
Firstly, your loop will always end on its first iteration since you essentially have if (...) return else return. Try this instead:
def sqrt(x):
"""Returns the square root of x if x is a perfect square.
Prints an error message and returns none if otherwise."""
ans = 0
if x >= 0:
while ans * ans <= x:
if ans * ans == x:
print(x, 'is a perfect square.')
return ans
ans = ans + 1
print(x, 'is not a perfect square.')
return None
else: print(x, 'is a negative number.')
But note that Python offers a built-in power operator:
def sqrt(x):
return x ** 0.5
To answer your question specifically, you will have to import your function. If the file in which this is written is sqrt.py, to use this function in another file you would need from sqrt import sqrt.
The NameError means that your python shell does not recognize the function. You probably forgot to import the script.
Assuming that you saved your file as myscript.py (in the same directory as where you start your python shell), you have to use:
import myscript
for the functions defined inside to be available. Note that you'll have to call myscript.sqrt in order to run your function sqrt: it is only available in the myscript namespace.
An alternative is to type from myscript import sqrt: in that case, you make your myscript.sqrt available in the namespace as sqrt. Be careful that you don't overwrite a builtin function with this from ... import ......
Here's your original code, just cleaned up so it will run. The problem with it as originally formatted was with indentation.
The while block should be indented one level (4 spaces) deep to denote it is in the def block for the function sqrt.
Having the if/else blocks inside of the while statements means that check is done each pass through the loop; therefore, the first time through when ans is only equal to one, that test will be done, your output with be printed and a value returned. We need to change this. Several of the other answers give more straight-forward ways to phrase this in python but, in keeping as close to the code you've written as possible, all you actually have to do is move the if block and the else block out of the while block. Code is shown below:
def sqrt(x):
"""Returns the square root of x if x is a perfect square.
Prints an error message and returns none if otherwise."""
ans = 0
if x>=0:
while ans*ans <x:
ans = ans + 1
if ans*ans == x:
print(x, 'is a perfect square.')
return ans
else:
print(x, 'is not a perfect square.')
return None
else:
print(x, 'is a negative number.')
Sample input and output are shown:
In:
sqrt(9)
Out:
9 is a perfect square.
In:
sqrt(8)
Out:
8 is not a perfect square.
EDIT: In my opinion, Python is a great first language. When I was first starting off with it, I found the MIT OpenCourseWare class very useful. One very important note: the class is taught using Python 2.x instead of 3.x so some of the given code won't work right for you. Even if you don't watch all the video lectures, the assignments they give are of a reasonable difficulty and the reading assignments reference some excellent python learning materials.
The Udacity CS101 class also offers a good, directed introduction to programming in Python (and also uses Python 2.x) but I only worked through about half of the assignments there. I'd still recommend taking a look at it, however.

Categories