Defining six functions and printing an output in python - python-3.x

So the problem is to define these six functions
def sphereVolume(r):
def sphereSurface(r):
def cylinderVolume(r,h):
def cylinderSurface(r,h):
def coneVolume(r,h):
def coneSurface(r,h):
And the write a program that prompts the user for the values of r and h, call the six functions, and print the results.
I have not tested this code because I am on a computer currently that does not have scite or python, however I've created this code on a notepad.
from math import pi
def sphereVolume():
volume1=((4/3)*pi*r)**3))
return volume1
def sphereSurface():
area1=(4*pi*r**2)
return area1
def cylinderVolume():
volume2=(pi*r**2*h)
return volume2
def cylinderSurface():
area2=(2*pi*r**2+2*pi*r*h)
return area2
def coneVolume():
volume3=((1/3)*pi*r**2*h)
return volume3
def coneSurface():
area3=(pi*r+pi*r**2)
return area3
main():
def main():
r=int (input("Enter the radius:"))
h=int (input("Enter the heights:"))
print ("Sphere volume:",sphereVolume(r),volume1)
print ("Sphere Surface:",sphereSurface(r),area1)
print ("Cylinder Volume:" , cylinderVolume(r,h),volume2)
print ("Cylinder Surface:",cylinderSurface(r,h),area2)
print ("Cone Volume:",coneVolume(r,h),volume3)
print ("Cone Surface:",coneSurface(r,h),area3)
Am I using the functions properly? Or is there a lot that I need to change?

There are many syntax errors in your code:
volume1=((4/3)*pi*r)**3)) (You don't need extra bracket at the end)
main(): (You called this function before you declared it, only call it after you've declared it and given it attributes)
print ("Sphere volume:",sphereVolume(r),volume1)
print ("Sphere Surface:",sphereSurface(r),area1)
print ("Cylinder Volume:" , cylinderVolume(r,h),volume2)
print ("Cylinder Surface:",cylinderSurface(r,h),area2)
print ("Cone Volume:",coneVolume(r,h),volume3)
print ("Cone Surface:",coneSurface(r,h),area3)
At first glance, this may all look right, however for each function you print, you give it a set of arguments that aren't meant to be there (e.g sphereVolume has the argument r). They shouldn't be there because you programmed them NOT to take in arguments, so you should change your functions to take in the arguments, otherwise you get the error:
print ("Sphere volume:",sphereVolume(r),volume1)
TypeError: sphereVolume() takes 0 positional arguments but 1 was given
So your functions should look like this:
from math import pi
def sphereVolume(r):
volume1=((4/3)*pi*r)**3
return volume1
def sphereSurface(r):
area1=(4*pi*r**2)
return area1
def cylinderVolume(r,h):
volume2=(pi*r**2*h)
return volume2
def cylinderSurface(r,h):
area2=(2*pi*r**2+2*pi*r*h)
return area2
def coneVolume(r,h):
volume3=((1/3)*pi*r**2*h)
return volume3
def coneSurface(r,h):
area3=(pi*r+pi*r**2)
return area3
You need to give them a set of arguments to work with, otherwise it's incorrect to put the variable r and h inside the functions, because- in simple terms- they haven't been given permission to be there.
Finally, you need to remove the extra variables you got from your functions that you printed out in main(). As they are local variables you can't access them unless they are returned. I'm guessing what you tried to do is that you wanted for instance in this line
print ("Sphere volume:",sphereVolume(r),volume1)
to print the value of volume1. You've already done that! When you said return volume1 at the end of the function, that meant if ever you print this function elsewhere, the only argument that will be accessed from the function is the one you returned, which in this case is volume1. Do the same likewise for all the other local variables you tried printing out by deleting them.
I've tested this code, but just so you don't have to look at everything I wrote if you don't want to, the fully working code is this:
from math import pi
def sphereVolume(r):
volume1=((4/3)*pi*r)**3
return volume1
def sphereSurface(r):
area1=(4*pi*r**2)
return area1
def cylinderVolume(r,h):
volume2=(pi*r**2*h)
return volume2
def cylinderSurface(r,h):
area2=(2*pi*r**2+2*pi*r*h)
return area2
def coneVolume(r,h):
volume3=((1/3)*pi*r**2*h)
return volume3
def coneSurface(r,h):
area3=(pi*r+pi*r**2)
return area3
def main():
r=int (input("Enter the radius:"))
h=int (input("Enter the heights:"))
print ("Sphere volume:",sphereVolume(r))
print ("Sphere Surface:",sphereSurface(r))
print ("Cylinder Volume:" , cylinderVolume(r,h))
print ("Cylinder Surface:",cylinderSurface(r,h))
print ("Cone Volume:",coneVolume(r,h))
print ("Cone Surface:",coneSurface(r,h))
main()

You need to add arguments to your functions for r and h.
You have an extra paren for:
volume1=((4/3)*pi*r)**3))
You need to fix:
main():

Related

Why print function doesn't work in method: get_details() and None is returned for print(x.increment_odometer)?

class Car:
def __init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.odometer_reading=0
def get_details(self): #SELF allows access of attributes and methods of a class
details=print((f'The make is: {self.make}, the model is: {self.model}, & the year is: {self.year}\n'))
#return details without print function works? i.w. details=rest of the line without print + return details (next line)
def read_odometer(self): #reading the value (default)
print(f'\nReading: {self.odometer_reading}')
def update_odometer(self,mileage):
if mileage>=self.odometer_reading:
print('\nReading has been changed')
self.odometer_reading=mileage
else:
print('\nCan, not change ')
def increment_odometer(self,miles):
self.odometer_reading+=miles
x.get_details() #trying to modify print(x.get_details()) which does work. Why does print need to be supplied here?
#incrementing the odometer
print(x.increment_odometer(50)) #why is this none?
I am learning classes and am confused about some aspects:
Why is "return details" line needed for method get_details()? Normally a simple function call having def f(): print('a') works, hence the confusion.
print(x.increment_odometer(50)) is None. Perhaps a function return needed in increment_odometer() method?
Confusing points having been commented in the code. Please englighten me.
Sincerely.

How to check which function has been returned in python?

I have two methods which take different number of arguments. Here are the two functions:
def jumpMX(self,IAS,list):
pass
def addMX(self,IAS):
pass
I am using a function which will return one of these functions to main.I have stored this returned function in a variable named operation.
Since the number of parameters are different for both,how do I identify which function has been returned?
if(operation == jumpMX):
operation(IAS,list)
elif(operation == addMX):
operation(IAS)
What is the syntax for this?Thanks in advance!
You can identify a function through its __name__ attribute:
def foo():
pass
print(foo.__name__)
>>> foo
...or in your case:
operation.__name__ #will return either "jumpMX" or "addMX" depending on what function is stored in operation
Here's a demo you can modify to your needs:
import random #used only for demo purposes
def jumpMX(self,IAS,list):
pass
def addMX(self,IAS):
pass
def FunctionThatWillReturnOneOrTheOtherOfTheTwoFunctionsAbove():
# This will randomly return either jumpMX()
# or addMX to simulate different scenarios
funcs = [jumpMX, addMX]
randomFunc = random.choice(funcs)
return randomFunc
operation = FunctionThatWillReturnOneOrTheOtherOfTheTwoFunctionsAbove()
name = operation.__name__
if(name == "jumpMX"):
operation(IAS,list)
elif(name == "addMX"):
operation(IAS)
You can import those functions and test for equality like with most objects in python.
classes.py
class MyClass:
#staticmethod
def jump(self, ias, _list):
pass
#staticmethod
def add(self, ias):
pass
main.py
from classes import MyClass
myclass_instance = MyClass()
operation = get_op() # your function that returns MyClass.jump or MyClass.add
if operation == MyClass.jump:
operation(myclass_instance, ias, _list)
elif operation == MyClass.add:
operation(myclass_instance, ias)
However, I must emphasize that I don't know what you're trying to accomplish and this seems like a terribly contrived way of doing something like this.
Also, your python code examples are not properly formatted. See the PEP-8 which proposes a standard style-guide for python.

NameError: name 'setBranchCourse' is not defined

Am calling a function in another function but it keeps telling me that function isn't defined, I have tried my best and read several online still not getting it.
This is the first function, inside this, i want to use "setBranchCourse(request)" in another function which that tells me not defined
#isLogin
def TESTstartcapturing(request):
global r1,r2
print ("come1")
setBranchCourse(request)
print ("come2")
r1,r2=getr1r2(request)
print (r1,r2)
return HttpResponse("done")
This is where am using the "setBranchCourse(request)". Please any way i could get this right?
complete code now.
ef=None
def startcapturing(request):
global ef
print ("startcapturing function start")
if setBranchCourse(request):
ipwebcamurl=request.POST.get('ipwebcamurl')
if ipwebcamurl:
print ("web cam ip set",ipwebcamurl)
request.session['ipwebcamurl']=ipwebcamurl
print ("branch course set")
ef=eigenfaces(request)
if ef:
print ("Training eigenfaces object done")
return HttpResponse("done")
else:
print ("ef not created ef=",ef)
return HttpResponse(status=410)
else:
return HttpResponse("failed")

Python Recrusive Statement Error not Defined

I am trying to test each input then return that the number is cleared then do the math. For Example is a user inputs N instead of a number I want it to output that its not a number whereas if the user inputs 1 then I want it to move to the next function asking for a power then do the same thing and if that passes then goes to the final section which output the answer to the problem.
The program passes both the errors for the non number areas yet when it get to very last function it is telling me base nor power are defined.
Code is written in some Python2 and some Python3. All works fine though. I use python3 mostly.
[Test Picture/Error Msg][1]
# Below we are creating the recursive statement to do the math for us. We are calling Base and Power
# from the main function where the user Inputs the numbers.
def pow(base, power):
if power == 0:
return 1
if power == 1:
return base
else :
return base * pow(base, power - 1)
def determineBase():
while True:
try:
base = int(input ('Please Enter A Base: '))
except ValueError:
print("Please use whole numbers only. Not text nor decimals.")
continue
else:
return base
def determinePower():
while True:
try:
power = int(input ('Please Enter A Power: '))
except ValueError:
print("Please use whole numbers only. Not text nor decimals.")
continue
else:
return power
def main():
determineBase()
determinePower()
pow(base,power)
print("The answer to",base,"to the power of", power,"is", pow(base,power),".")
main()
def main():
determineBase()
determinePower()
pow(base,power)
Here, neither base nor power are defined. What you meant instead was to store the result from those function calls and pass those then:
def main():
base = determineBase()
power = determinePower()
pow(base, power)
The issue isn't inside the recursive function, it's inside your main function.
The problem is arising due to the fact that you are passing base as an argument to the pow() function without defining the variable base first (the same would subsequently be true for power).
In other words you need something along the lines of:
def main():
base = determineBase()
power = determinePower()
pow(base,power) #this line could probably be removed
print("The answer to",base,"to the power of", power,"is", pow(base,power),".")
As currently, you're not storing the values of these two functions.

How do i get a variable from a function?

So I am a total noob at python so im sorry if im not being specific enough.
I am writing a tic tac toe program and the hardest thing is getting to switch turns
so i wrote a function to do this but i cant get the "turn" variable which belongs to another function. Im sorry if im being moronic but this is the best i can explain it. Thanks for your Time :)
BTW here is the code
x="X"
o="O"
EMPTY=" "
TIE="TIE"
NUM_SQUARES=9
def display_instruct():
print(
"""
Welcome to the greatest challenge ever
Tic
Tac
Toe
the board is as shown
0|1|2
------
3|4|5
-----
6|7|8
Prepare as teh game is about to start
""")
def yesno(question):
response=None
while response not in ("y","n"):
response=input(question).lower()
return response
def asknum(question, low, high):
response=None
while response not in range(low,high):
response=int(input(question))
return response
def pieces():
go_first=yesno("Do you want the first move")
if go_first=="y":
print("then take the first move you will need it")
human=x
computer=o
turn=x
return computer, human
else:
print ("Ok i shall go first")
computer=x
human=o
turn=x
return computer, human
def new_board():
board=[]
for square in range(NUM_SQUARES):
board.append(EMPTY)
return board
def display_board(board):
print ("\n")
print (board[0],"|",board[1],"|",board[2])
print ("----------")
print (board[3],"|",board[4],"|",board[5])
print ("----------")
print (board[6],"|",board[7],"|",board[8])
def legal_moves(board):
moves=[]
for square in range(NUM_SQUARES):
if board[square]==EMPTY:
moves.append(square)
return moves
def winner(board):
WAYS_TO_WIN=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6))
for row in WAYS_TO_WIN:
if board[row[0]]==board[row[1]]==board[row[2]]!=EMPTY:
winner=[row[0]]
return winner
if EMPTY not in board:
return TIE
return None
def human_move(board,human):
legal=legal_moves(board)
move=None
print (legal)
while move not in legal:
move=asknum("Where will you move",0,NUM_SQUARES)
return move
def computer_move(board,computer,human):
board=board[:]
BEST_MOVES=(4,0,2,6,8,1,3,5,7)
print ("I shall take square number", end=" ")
for move in legal_moves(board):
board[move]=computer
if winner(board)==computer:
print(move)
return move
for move in legal_moves(board):
board[move]=human
if winner(board)==human:
print(move)
return move
board[move]=EMPTY
for move in BEST_MOVES:
if move in legal_moves(board):
print (move)
return move
def next_turn(turn):
if turn==x:
return o
else:
return x
def congrat_winner(the_winner,computer,human):
if the_winner!=TIE:
print(the_winner, "WON")
else:
print ("Its a ttie")
if the_winner==computer:
print ("I WON HA HA IN YO FACE")
elif the_winner==human:
print ("NO IT CANNOT BE")
elif the_winner==TIE:
print ("you were lucky this time")
def curturn(turn,computer,human):
if turn==x and move!="" and move!=" ":
turn=o
elif turn==o and move!="" and move!=" ":
turn=x
def main():
display_instruct()
computer, human=pieces()
turn=x
board=new_board()
display_board(board)
curturn(turn,computer,human)
while not winner (board):
display_board(board)
if turn == human:
move=human_move(board,human)
board[move]=human
else:
move=computer_move(board,computer,human)
board[move]=computer
display_board(board)
turn=next_turn(turn)
the_winner=winner(board)
congrat_winner(the_winner,computer,human)
main()
Functions look like this (simplified):
def functionname(parameter1, parameter2=foo):
code that does stuff
return value
If you in your function want to access a variable from the calling function, you pass it in as a parameter. If you from the calling function want to access a variable from the function you call, you return it.
You can also use global variable (which you do, I see) and that is a Bad Idea, as it will make your program messy and hard to debug. So avoid that if you can (although in a small program like this, it's not a disaster, so don't bother now).
If you want to access variables from completely different places, you probably want to look into object-oriented programming, with classes and stuff.

Resources