I am wondering, is there a way to use the input() function inside a user-defined function? I tried doing this
def nameEdit(name):
name = input()
name = name.capitalize
return name
Using input is fine. However, you aren't calling name.capitalize; you're just getting a reference to the method and assigning that to name. [Further, as pointed out by Bob, your function doesn't need a name argument.] The correct code would be
def nameEdit():
name = input()
name = name.capitalize()
return name
or more simply:
def nameEdit():
return input().capitalize()
Are you talking about asking for input from a user from a method? If so then this would be what you're looking for:
def nameEdit():
name = input("Enter your name: ")
name = name.capitalize()
return name
Related
My apologies as I am very new to Python and coding in general but I am trying an exercise on creating functions and formatting all in the same. Here I have a function I wrote for practice. But I can't get it to run correctly. What am doing wrong with creating this function.
My code:
def greeting(name):
name = input("What's your name: ")
return "Hi %s" % name
print(greeting())
The error:
TypeError: greeting() missing 1 required positional argument: 'name'
Thank you for your help. :)
You don't need to give name as a parameter to the greeting function.
Try this:
def greeting():
name = input("What's your name: ")
return "Hi %s" % name
print(greeting())
You don't want to take name as an argument, because you are creating that variable within the function in your call to input()
def greeting():
name = input("What's your name: ")
return "Hi %s" % name
You also do not need to print() the function, because it's return value (a string) is printed by default. If you saved the return value of greeting() into an object, you could then print that object
the_greeting = greeting()
print(the_greeting)
i am new here and i am trying to learn python. i want to create a simple atm program but i also want to try something that i haven't seen yet. i want to take input from user and select one of objects of a class regard to this selection, here is the part of my code
class bankaccount():
def __init__(self,name,money):
self.name=name
self.money=money
def show(self):
print(self.name,self.money)
johnaccount=bankaccount("john",500)
mikeaccount=bankaccount("mike",1000)
sarahaccount=bankaccount("sarah",1500)
selection= input("please write the name: ")
for example i will write john and program should run johnaccount.show is this possible? could you please help about this issue.
Below
class bankaccount():
def __init__(self,name,money):
self.name=name
self.money=money
def show(self):
print(self.name,self.money)
# build the accounts 'DB' (which is just a dict)
# read more here: https://cmdlinetips.com/2018/01/5-examples-using-dict-comprehension/
accounts = {name: bankaccount(name,balance) for name,balance in [("john",500),("mike",1000)]}
user = input("please write the name: ")
account = accounts.get(user)
if account:
account.show()
else:
print(f'no account for {user}')
There is a "hacky" way to do that (see below). Usually you'd rather have a dictionary or list containing all of the accounts and then get the account from there.
For example:
accounts = {
'john': bankaccount("john",500),
'mike': bankaccount("mike",1000)
}
selection = input("please write the name: ")
if selection in accounts:
print(f"Balance: {accounts[selection].show()}")
else:
print("Account not found")
The "hacky" way is to use Python's built-in locals function:
johnaccount=bankaccount("john",500)
mikeaccount=bankaccount("mike",1000)
sarahaccount=bankaccount("sarah",1500)
selection = input("please write the name: ")
account_name = f"{selection}account"
if account_name in locals():
print(f"Balance: {locals()[account_name].show()}")
else:
print("Account not found")
The f"Balance: {accounts[selection].show()}" syntax that I'm using is called f-strings, or formatted string literals.
PS. it's common practice to use CamelCase for class names, e.g. BankAccount, and to use lowercase and underscores for variable names, e.g. john_account.
Suppose I had this class
class employee(object)
def __init__(self,name):
return self.name
def something(self):
pass
...
Leading to
if __name__== "__main__":
name = input("what is your name ")
user1 = employee(name)
user1.something()
...
I want the user1 instance to be the name inputted by the user so that I can have unique instances. How do I go about adding instances based on user input in the main section?
so if I run the program and inputted "tim", the outcome I would want is:
tim.name = "tim"
....
UPDATE
Seems like the above is unclear, let me try to explain using my actual code:
So I have this Spotify API:
class Spotify(object):
def __init__(self,user):
self.client_id = ''
self.client_secret = ''
def client_credentials(self):
pass
def get_header_token(self):
pass
...
In the end,
if __name__== "__main__":
user = input("Enter username ")
user = Spotify(user)
user.request_author()
...
I am trying to get the user variable to the input the user provides, such as if the user inputted "tim123", the user variable would also be tim123.
So I could perform:
tim123.name
Think my mind is going completely blank and there should be an easy solution for this. I am sure this is very unpractical but I don't know how I would do this in case I ever needed to.
Change
return self.name
to
self.name = name
if name== "main":
variable_name = raw_input("Enter variable name:") # User.
enters "tim123"
name = input("Enter Name")
globals()[variable_name] = employee(name)
tim123.name
Based on your comment, it sounds like you are looking for exec() or eval(). Link. My solution would be to do something like:
class employee(object):
def __init__(self,name):
self.name = name
name = input("what is your name ")
exec(f"{name} = employee('{name}')")
(and then you would access joe.name, if the user inputted joe, or bob.name, if the user inputted bob, etc.).
Alternatively, you could use locals() or globals()
Hope this helped!
I'm following the Microsoft introduction to Python course for beginners on edX, I'm having trouble in their second module where they ask you to create function that adds the "Doctor" title to a user inputted name.
This is the advice they provide:
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
create and call make_doctor() with full_name argument from user input - then print the return value
This is what I have so far:
def make_doctor(name):
full_name = print("Doctor" + input().title())
return full_name
print(name)
Would appreciate any help.
Python is an off-side rule language:
Python Reference Manual (link)
Leading whitespace (spaces and tabs) at the beginning of a logical
line is used to compute the indentation level of the line, which in
turn is used to determine the grouping of statements.
In contrast to others such as curly-bracket languages, indentation is (generally) not stylistic, but required in order to group statements. Therefore, your code should look like this:
def make_doctor(name):
return "Doctor" + name
full_name = input()
print(make_doctor(full_name))
def make_doctor(name):
# add the Doctor title to the name parameter
d_name = 'Doctor '+name
# print the return value
print(d_name)
return d_name
# get the user input for the variable full_name
full_name=input('Enter your full name: ')
# pass full_name as an argument to make_doctor function
doc = make_doctor(full_name)
# print return value
print(doc)
def make_doctor(name):
full_name = input()
return full_name
print('Doctor ' + full_name)
I am new to Python, am just learning Classes, and am trying to write a "personal info" program:
This is my code:
class PersonalInfo():
def names(self, name):
name = raw_input("What is your name?")
self.names = name
def addresses(self, add):
add = raw_input("What is your adress?")
self.addresses = add
def ages(self, age):
age = raw_input("What is your age?")
self.ages = age
def numbers(self, number):
number = raw_input("What is your phone number?")
self.numbers = number
PersonalInfo()
def print_names():
info = PersonalInfo()
print "Name:", info.names(name)
print "Address:", info.addresses(add)
print "Age:", info.info.ages(age)
print "Phone number:", info.numbers(number)
print_names()
But when I run it it says this:
NameError: global name 'add' is not defined
Can someone please help me?
There are several issues with your code other than the NameError and I strongly suggest you read more on python classes:
https://docs.python.org/2/tutorial/classes.html
https://www.tutorialspoint.com/python/python_classes_objects.htm
https://en.wikibooks.org/wiki/A_Beginner's_Python_Tutorial/Classes
I'll run you through those issues.
First, the NameError occurs because the add variable was not defined. The same applies to all other arguments you provided in your print statements.
Second, there are issues with the way you define the class methods:
class PersonalInfo():
def names(self, name):
name = raw_input("What is your name?")
self.names = name
Here, you are re-assigning the name variable to the return value of raw_input so there's no sense in setting it as an argument in the first place. Also, by stating self.names = name you are re-assigning the class method to the string that is returned by raw_input!
Third, you have to decide whether you want to provide the information when calling the methods, or using raw_input. Here's a working example of your code, assuming you want to use raw_input
class PersonalInfo():
def names(self):
name = raw_input("What is your name?")
self.name = name
def addresses(self):
add = raw_input("What is your adress?")
self.address = add
def ages(self):
age = raw_input("What is your age?")
self.age = age
def numbers(self):
number = raw_input("What is your phone number?")
self.number = number
def print_names():
info = PersonalInfo()
# Get information
info.names()
info.addresses()
info.ages()
info.numbers()
# After getting the info, print it
print "Name:", info.name
print "Address:", info.address
print "Age:", info.age
print "Phone number:", info.number
print_names()