I am doing a python course and one of the exercises is to write a function that adds "Doctor" to a name. The instructions are:
Define function make_doctor() that takes a parameter name
get user input for variable full_name
call the function using full_name as argument
print the return value
My code is:
def make_doctor(name):
full_name = input("Doctor ")
return full_name
print(make_doctor(full_name))
However, I keep getting the below error:
NameError Traceback (most recent call last)
<ipython-input-25-da98f29e6ceb> in <module>()
5 return full_name
6
----> 7 print(make_doctor(full_name))
NameError: name 'full_name' is not defined
Can you anybody help please?
Thanks
You code has lots of issues.
Have the input be outside the function. Pass the input to make_doctor to add "Doctor" to it, and then print that.
Very important side note: Use raw_input() if python2 and input() if python3. dont use input() in python 2 its an expression evaluator rather than a string.
def make_doctor(name):
return "Doctor {}".format(name)
name = raw_input("Enter your name here!!") # if python2
# name = input("Enter your name here!!") # if python3
print(make_doctor(name=name))
In your code the variable full_name is a local variable to the function make_doctor
Try this :
def make_doctor(name):
return "Doctor "+name
full_name = input()
print(make_doctor(full_name))
Related
I thought this was a trivial question but to my surprise, I couldn't find an answer.
Consider I have a factory named Foo. It has a normal field named "name" and another field named user_input for which I want to force the user to pass a value on initialization, and get an error if they don't do so. How can I achieve this?
import factory
class FooFactory(factory.Factory):
name = factory.Faker("name")
user_input = ?
# I want this to work:
foo = FooFactory(user_input="blah blah")
# and this to throw an error:
foo = FooFactory()
The solution would be to use a factory.lazy_attribute:
class FooFactory(factory.Factory):
name = factory.Faker("name")
#factory.lazy_attribute
def user_input(self):
raise ValueError("FooFactory.user_input is required")
>>> FooFactory()
Traceback (most recent call last):
File "...py", line 7, in user_input
ValueError: FooFactory.user_input is required
>>> FooFactory(user_input=42)
{"name": "John Doe", "user_input": 42}
Im looking to create something that I can use to check if a string meets a condition like so:
var = "hello"
check = var.checkconditions()
Im just curious as to if its possible as I have never seen it done before.
How would the function/whatever I need to use be set out?
String is a build in class/object and can not be changed. However you can make a personal new class:
class str_class:
def __init__ (self, str):
self.str = str
def checkconditions(self):
# Enter your conditions
var = str_class('hello')
check = var.checkconditions()
Or you could simply make a funtion that takes the string as input and outputs if the condition is met or not:
def checkconditions(str):
# Enter conditions
var = 'Hello'
check = checkconditions(var)
Edit: From other comments it seems as though it is possible but not recommended.
You can use a Class and then use the method check_conditions.
class Check:
def __init__(self):
pass
def check_conditions(string):
#Do whatever you need in here
print(string)
c = Check
c.check_conditions("hello")
This should hopefully do what you need!
You can't directly add the method to the original type.what you can do is subclass the type like
class mystring(str):
def checkconditions(self):
#condition
and then you can instantiate your new class
var = mystring('hello')
var.checkcondition()
but that's still no too practical, if you want to make it more proper you can do this
import __builtin__
__builtin__.str = mystring
var = str("hello")
check = var.checkconditions()
which achieves most of the effect desired.
Unfortunately, objects created by literal syntax will continue to be of the vanilla type and won't have your new methods/attributes.
var = 'hello'
var.checkconditions()
# Output
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'checkconditions'
"""
I tried using the python help() function to preview the docstring of a function I created but the terminal keeps saying "NameError: name 'functionName' is not defined".
I tried passing parameters into my function but nothing's helped.
def coefficients():
""" Evaluates value of inputs and determines use case for almighty formula function """
def coefficient_of_xsquared():
if a == "" or a == 0 or a == " ":
print (error)
return a
coefficient_of_xsquared()
def coefficient_of_x():
if b == "" or b == 0 or b == " ":
print (error)
return b
coefficient_of_x()
def coefficient_of_one():
if c == "" or c == 0 or c == " ":
print (error)
return c
coefficient_of_one()
Expected: Evaluates value of inputs and determines use case for almighty formula function
Actual:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'coefficients' is not defined
It sounds like the function isn't defined when you are trying to call help.
If the function is defined in a file (e.g. modulename.py), you need to import it into the interactive interpreter before you can use it. If the files is called MODULENAME.py, use from MODULENAME import coefficients before you try to use it.
This question already has answers here:
Why doesn't the main() function run when I start a Python script? Where does the script start running (what is its entry point)?
(5 answers)
Closed last month.
I want to make a script in python and then run it from the command line. The script is called test.py and the command to run it is:
python3 test.py John Jackson
Here is the expected output:
John Jackson
And here is the python script I made:
class person:
def __init__(self, first, last):
self.firstname = first
self.lastname = last
def get_first(self):
return self.firstname
def get_last(self):
return self.lastname
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('first')
parser.add_argument('last')
args = parser.parse_args()
c1 = person(args.first, args.last)
print(c1)
But the problem is when I run the script from the command line using the mentioned command, it returns nothing. Do you know how to fix it and get the expected output?
You defined your main() function but did not call it.
Add this at the end of your script:
if __name__ == "__main__":
main()
See What does if __name__ == “__main__”: do?.
Then, c1 is the person instance, which would print:
$ python3 test.py John Jackson
<__main__.person object at 0x104907ef0>
You need to call get_first() and get_last() to get the correct output:
print(c1.get_first(), c1.get_last())
I am not sure if you are calling your main function while running the script.
Add
if __name__ == "__main__":
main()
And override __str__ function of the person class to print first name and last name while passing class as argument to print.
def __str__(self):
return self.firstname + ' ' + self.lastname
The whole code goes like this
import argparse
class person:
def __init__(self, first, last):
self.firstname = first
self.lastname = last
def get_first(self):
return self.firstname
def get_last(self):
return self.lastname
def __str__(self):
return self.firstname + ' ' + self.lastname
def main():
parser = argparse.ArgumentParser()
parser.add_argument('first')
parser.add_argument('last')
args = parser.parse_args()
c1 = person(args.first, args.last)
print(c1)
if __name__ == '__main__':
main()
Your script is unnecessarily complex, a much (much) simpler way to achieve this is to use the argv property of the sys module then separate the (string) argument using split, like this:
import sys
name = sys.argv[1].split(" ")
if len(name) != 2:
raise ValueError("Invalid first and last name, try using \"John Jackson\" instead.")
[first_name, last_name] = name
print(first_name, last_name)
You don't even need to raise an error:
import sys
name = sys.argv[1].split(" ")
if len(name) == 2:
[first_name, last_name] = name
print(first_name, last_name)
Then when you run the script like this:
python3 filename.py "John Jackson"
You should get the following output:
John Jackson
Good luck.
I want to change the function name according to result obtained from another function but the function definition remains same How can i do this i tried the following example but it didn't work
def f(text):
def x(text):
return text+"example"
name=x(text)
def name(y):
return y
return name
p=f("hi ")
print p("hello")
print p.__name__
OUTPUT
hello
name
But i want the function name p.__name__ as "hi example" not name
You can simply assign to __name__:
def f(text):
def r(y):
return y
r.__name__ = text + "example"
return r
p = f("hi ")
print (p("hello")) # Outputs "hello"
print (p.__name__) # Outputs "hi example"
Note that a function name does not have any influence on the function's behavior though, and does not have any meaning except as a part of the string representation or a debugging aid.