how to pass many arguments through a command function (do_) - python-3.x

I want to code a simple command that could take 3 arguments for a text adventure game.
Basically at the prompt, I would type 'use key unlock door' and it would run a particular block.
Here is what I coded but it does not work:
def do_use(self, tool, action, object):
if tool == 'key':
if action == 'unlock':
if object == 'door':
print("seems like it works!")
else:
print("nope 1")
else:
print("nope 2")
else:
print("nope 3")
Notes: the rest of the commands work fine. I imported cmd
and the following is the main code:
class Game(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
....
if __name__ == "__main__":
g = Game()
g.cmdloop()
At the prompt, when I type:
>>> use key unlock door
I get the following error message:
TypeError: do_use() takes exactly 4 arguments (2 given)
The code would work if it would print:
seems like it works!
Any help will be appreciated.

Reading that documentation, it looks like all of the commands just take in a single string, and you have to parse the string yourself. Your command is defined as taking 4 arguments (including self), and cmd is calling it with self, input, which is 2. I think could get the result you want with the following:
def do_use(self, user_input):
args = user_input.split()
if len(args) != 3:
print "*** invalid number of arguments"
else:
tool, action, obj = args
# Do the rest of your code here

Related

Learning Wemake-Python-Styleguide: Why do I receive a magic number violation for keyword arguments?

I keep receiving the following error
WPS432 Found magic number: 50
for a function below:
from brain_games.evenodd_game import oe_func
def main():
"""Play even-odd game.
Returns:
game playground.
"""
print('Welcome to the Brain Games!')
return oe_func(min_val=1, max_val=50)
if __name__ == '__main__':
main()
According to WPS, keyword arguments inside a function are excluded from the magic number check (see link below). Since max_val=50 is a keyword argument, why do I receive the above error?
https://wemake-python-stylegui.de/en/latest/pages/usage/violations/best_practices.html

I am new to python coding and i do not understand how to use a variable from another method

Here is what i have tried:
I do not understand how can i use a variable from another method of same class. Also please explain how can i use a variable from a method in different class. I tried searching but could not find a solution. So what i did to pass the test cases is to copy code from calculate_percentage and paste it in find_grade method. It worked but i think this is the worst method. So please tell a possible solution.
Thanks
#!/bin/python3
#Enter your code here. Read input from STDIN. Print output to STDOUT
class Student:
def __init__(self,roll,name,marks_list):
self.roll=roll
self.name=name
self.marks_list=marks_list
def calculate_percentage(self):
length=len(self.marks_list)
sum=0
for i in self.marks_list:
sum+=i
percent=sum/length
return int(percent)
def find_grade(self,percent):
if percent>=80:
return 'A'
elif percent>=60 and percent<80:
return 'B'
elif percent>=40 and percent<60:
return 'C'
elif percent<40:
return 'F'
if __name__ == '__main__':
roll=int(input())
name=input()
count=int(input())
marks=[]
for i in range(count):
marks.append(int(input()))
s=Student(roll,name,marks)
print(s.calculate_percentage())
print(s.find_grade())
i am getting the error:
print(s.find_grade())
TypeError: find_grade() missing 1 required positional argument: 'percent'
Thanks for every one who answered but i found the answer:
i just need to put self.percent
or percent=self.calculate_percentage() to call the method and use the variables
The assumption would be that the marks are x/100 scale while otherwise your percentage will be incorrect.
As said above, you need to pass the variable percent back to the function since it is not known in the class, it is only returned.
print(s.find_grade(s.calculate_percentage()))
or if the percentage is a class variable you can rewrite it into the class like this:
from statistics import mean
class Student2:
def __init__(self,roll,name,marks_list):
self.roll=roll
self.name=name
self.marks_list=marks_list
def calculate_percentage(self):
self.percent=mean(marks)
return int(self.percent)
def find_grade(self):
if self.percent>=80:
return 'A'
elif self.percent>=60 and self.percent<80:
return 'B'
elif self.percent>=40 and self.percent<60:
return 'C'
elif self.percent<40:
return 'F'
percent = int(0)
# test variables
vRoll = 2
vName = 'student'
vCount= 2
vMarks= [100, 75]
# main
if __name__ == '__main__':
roll=vRoll
name=vName
count=vCount
marks=vMarks
s2=Student2(roll,name,marks)
print(s2.calculate_percentage()) # 87
print(s2.find_grade()) # A

Function that to exit from other function

I wanted to create to a function which, when called in other function it exits the previous function based on the first function's input.
def function_2(checking):
if checking == 'cancel':
# I wanted to exit from the function_1
def function_1():
the_input = input("Enter the text: ")
function_2(the_input)
I wanted the code for the function_2 so that it exits from function_1, I know that I can put the if statement in function_1 itself but ill use this to check more than one in input in the same function or even in different function I cant put the if block everywhere it will look unorganized so i want to create a function and it will be convenient to check for more than one word like if cancel is entered i wanted to exit the programm if hello is entered i wanted to do something, to do something its ok but to exit from the current function with the help of other function code please :) if any doubts ask in the comment ill try to give you more info im using python 3.x.x on Windows8.
Why not simply:
def should_continue(checking):
if checking == 'cancel':
return False
return True
def function_1():
the_input = input("Enter the text: ")
if not should_continue(the_input):
return
This is the best solution I think.
Another alternative is to raise an Exception, for example:
def function_2(checking):
if checking == 'cancel':
raise KeyboardInterrupt
def function_1():
the_input = input("Enter the text: ")
function_2(the_input)
try:
function_1()
except KeyboardInterrupt:
print("cancelled by user")

python3 Execute a function when command line arg is TRUE

I have two functions, (1) running a demo analysis and (2) custom function that is read through a file. I would like to pass a command line argument for the user to select either the demo function or custom function as true or false. No other values needs to be passed. I am not sure what I should add within the function to accept the arg.parse
def demo()
print("This is demo function")
def custom()
print("This is custom function")
def main():
parser = argparse.ArgumentParser(description="Argument Parser is boolean to run Pipeline'")
parser.add_argument("--demo", help='Demo data to show an example')
parser.add_argument("--custom", help='Specify custom analysis, sql query is read from userquery.sql')
args = parser.parse_args()
if args.demo == True:
demoanalysis()
elif args.custom == True:
customanalysis()
else:
print("Don't do anything")
However when I run the script, it goes straight to the third option.
python script.py --demo True --custom False
Don't do anything
I understand something needs to be passed to each function to accept the boolean arguments but unsure how to do it. Any suggestions. Thanks.
I guess, you can use action="store_true" argument (more in the docs):
def main():
parser = argparse.ArgumentParser(description="Argument Parser is boolean to run Pipeline'")
parser.add_argument("--demo", action="store_true", help='Demo data to show an example')
parser.add_argument("--custom", action="store_true", help='Specify custom analysis, sql query is read from userquery.sql')
args = parser.parse_args()
if args.demo: # need no comparison with True, because demo is True or False itself
demoanalysis()
elif args.custom:
customanalysis()
else:
print("Don't do anything")
Edit: If there's no keyword in command line argument, store_true creates False values by default.
Usage examples:
python demo_script.py --demo # prints "This is demo function"
python demo_script.py --custom # prints "This is custom function"
Hope it helps!
You can also build a function to check whether the argument you passed to the function is valid:
def main():
parser = argparse.ArgumentParser(description="Argument Parser is boolean to run Pipeline'")
# Here you add a type definition to your arguments
parser.register('type', 'bool', (lambda x: str(x).lower() == "true") )
parser.add_argument("--demo", type="bool", help='Demo data to show an example')
parser.add_argument("--custom", type="bool", help='Specify custom analysis, sql query is read from userquery.sql')
args = parser.parse_args()
if args.demo:
demoanalysis()
elif args.custom:
customanalysis()
else:
print("Don't do anything")

Defining six functions and printing an output in python

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():

Resources