I was trying to solve a simple python code it run successfully but it fails all the test cases. Can anyone help what mistake I'm doing.
def print_full_name(first_name, last_name):
first_name = 'Ross'
last_name = 'Taylor'
print(f'Hello {first_name} {last_name} ! You are welcome.')
if __name__ == '__main__':
first_name = input()
last_name = input()
print_full_name(first_name, last_name)
The code you supplied does not contain a test so the question is a little confusing.
If you are asking why your inputs do not end up in the print statement.
The following is the answer:
Your method parameters are overridden inside the method by the following lines, this is referred to as hard coding the values.
first_name = 'Ross'
last_name = 'Taylor'
In order to print out what you send via inputs, you need to use the parameters to form the string.
Essentially the two lines above are the problem, as they always populate the sting.
try the following:
def print_full_name(first_name, last_name):
# Create a string using the method parameter values
result = f'Hello {first_name} {last_name} ! You are welcome.'
print(result)
if __name__ == '__main__':
# Assign a value to first_name
first_name = input('first_name: ')
# Assign a value to last_name
last_name = input('last_name: ')
# Call the method passing in the values set above
print_full_name(first_name, last_name)
Related
class print_values:
def __init__(self,username,user_email,displayname):
self.name= username
self.email=user_email
self.DisplayName=displayname
def printing_content(self):
print(f"UserName: {self.name}\n"
f"UserEmail: {self.email}\n"
f"UserDisplayName:{self.DisplayName}\n")
user_one={'username':'userone',
'useremail':'userone#gmail.com',
'displayname':'User One'}
user_two={'username':'usertwo',
'useremail':'usertwo#gmail.com',
'displayname':'User Two'}
user_three={'username':'userthree',
'useremail':'userthree#gmail.com',
'displayname':'User Three'}
users_list=['user_one','user_two','user_three']
obj_name=print_values(user_one['username'],user_one['useremail'],user_one['displayname'])
obj_name.printing_content()
It's working fine, as am getting output as below
UserName: userone
UserEmail: userone#gmail.com
UserDisplayName:User One
Here am only using user_one dict, i want to do the same for multiple dict.
I have tried adding the dict names in list and try to loop through them, like below
for item in user_list:
obj_name=print_values(item['username'],item['useremail'],item['displayname'])
obj_name.printing_content()
But am getting below error
obj_name=print_values(item['username'],item['useremail'],item['displayname'])
TypeError: string indices must be integers
Any one do let me know what am i missing or anyother idea to get this done.
Thanks in advance!
This is because in users_list=['user_one', 'user_two', 'user_three'] you enter the variable name as a string.
class print_values:
def __init__(self,username,user_email,displayname):
self.name= username
self.email=user_email
self.DisplayName=displayname
def printing_content(self):
print(f"UserName: {self.name}\n"
f"UserEmail: {self.email}\n"
f"UserDisplayName:{self.DisplayName}\n")
user_one={'username':'userone',
'useremail':'userone#gmail.com',
'displayname':'User One'}
user_two={'username':'usertwo',
'useremail':'usertwo#gmail.com',
'displayname':'User Two'}
user_three={'username':'userthree',
'useremail':'userthree#gmail.com',
'displayname':'User Three'}
users_list=[user_one,user_two,user_three] # edited
obj_name=print_values(user_one['username'],user_one['useremail'],user_one['displayname'])
obj_name.printing_content()
for item in users_list:
obj_name=print_values(item['username'],item['useremail'],item['displayname'])
obj_name.printing_content()
Explanation
Your users_list=['user_one', 'user_two', 'user_three'] is a string containing the variable names as the string. When you loop on user_list
for item in user_list:
Here item is not the user_one, or user_two as a variable but these are as the string means 'user_one', or 'user_two', so when you try to get values like item['username'], here you got the error because the item is not a dictionary or json or ..., but it is a string here, you can get the only provide an integer inside these brackets [], like 1, 2, 3, 4,..., ∞.
I hope you understand well. Thanks.
Don't make a dictionary for every user.
Use this code
class Users:
def __init__(self) -> None:
self.userList = []
def addUser(self, user):
self.userList.append(user)
class User:
def __init__(self, username, email, name) -> None:
self.username = username
self.email = email
self.name = name
def __str__(self) -> str:
return f"Username = {self.username}\nEmail = {self.email}\nName = {self.name}\n"
users = Users()
users.addUser(User("username1", "email1", "name1"))
users.addUser(User("username2", "email2", "name2"))
# First way of printing
for user in users.userList:
print(user) # Printing user directly prints the formatted output
# Because I have changed the magic `__str__` method in user class
# You can return anything('string data type only') in __str__ it will print when you print the class object.
# Second way of printing.
for user in users.userList:
print("Username = " + user.username)
print("Email = " + user.email)
print("Name = " + user.name)
print() # for adding one extra line
I tried to write a script that replaces Hotmail address with Gmail if found in the input, but there is something wrong with the function I think. There is no syntax error but the result just does not output the replaced Gmail domain but the same Hotmail one.
old_email = "hotmail.com"
new_email = "gmail.com"
email = input("Enter email: ")
def replace_domain(email, old_email, new_email):
if "#" + old_email in email.endswith:
index = len(old_email)
new = email[:-index]+ "#" + new_email
return new
return email
a = email
print(a)
Here's the fixed code and then I'll explain what I've changed:
old_email = "hotmail.com"
new_email = "gmail.com"
email = input("Enter email: ")
def replace_domain(email, old_email, new_email):
if email.endswith("#" + old_email):
index = len(old_email)
new = email[:-index] + new_email
return new
return email
a = replace_domain(email, old_email, new_email)
print(a)
First: There was no call to the function. I've added that to the penultimate line.
Second: endswith is a function. I've therefore changed that line so that the function is called with the old email domain.
Third: The # was being output twice, because it isn't removed in the :-index part and then a new one is added immediately afterwards.
I would also make some recommendations:
Fourth: a is not a descriptive variable name, which makes the code harder to read. Similarly, index and new are not ideal variable names. Words like new are best avoided as variable names, because they can easily clash with built-in names.
Fifth: I would consider changing the variable name old_email to old_domain instead. Same with new_email. This is a better match for the contents of that variable.
Example output:
Enter email: robson#hotmail.com
robson#gmail.com
Another example output:
Enter email: robson#aol.com
robson#aol.com
The problem is getting that when I give the user input value to as an argument, it takes as a string and gives an error.
class Employee():
def details(self,name=[]):
print(
"Name of Employee is:",name[0],
"\nSalary of Employee is:",name[1],
"\nPost of Employee is:",name[2],
"\nLocation of Employee is:",name[3]
)
harry = ["Harry",10000,"Engineer","Gurgoan"]
manish = ["Manish",20000,"Manager","Noida"]
e = Employee()
f = input("Enter name to get details:")
e.details(f)
if I use e.details(harry) and don't use input function it works fine. but I want to get detail of harry by using the input function.
When you create an object from the Employee class and then call from it details function, e object - does not know about your lists that you define before object creation
I am not sure what your code is doing, but I think you meant something like this:
class Employee:
def __init__(self):
self.workers_data = {
"harry": ["Harry", 10000, "Engineer", "Gurgoan"],
"manish": ["Manish", 20000, "Manager", "Noida"],
}
def details(self, name):
print(
"Name of Employee is: {}\nSalary of Employee is: {}\nPost of Employee is: {}\nLocation of Employee is: {}".format(
*self.workers_data[name]
),
)
e = Employee()
f = input("Enter name to get details:")
e.details(f)
This is because your string can be less than 4 symbol’s, and when you call name[3] it returns error. Also if you want to get words from input, you can split it by space’s: input().split()
If you need to get info about name, try to use dictionary:
harry = ["Harry",10000,"Engineer","Gurgoan"]
manish = ["Manish",20000,"Manager","Noida"]
Names = {"Harry": harry, "Manish": manish}
e = Employee()
f = input("Enter name to get details:")
e.details(Names[f])
Just use eval at the last line to completely fix the problem
I tested & it worked just now
e.details(eval(f)) # eval the string
eval makes string as variable name
Edit:
But use it at your own risk user can run anything with this method
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I am trying to incorporate a regex check for user input in my class. I want a scenario where users can't proceed to enter their name until they enter a valid email address. The current code i have isn't working as expected.
I suppose a while-loop is in order here but i am struggling to implement that in this class. Any assistance is much appreciated.
class test:
def __init__(self):
self.email = input("Enter your email: ")
email_check = re.search(r'[\w.-]+#[\w.-]+.\w+', self.email)
if email_check:
print ('email valid')
else:
print ('email not valid')
self.email = input("Enter your email: ")
sys.exit(0)
self.name = input("Enter your name: ")
You can do it like this.
while True:
self.email = input ("Enter email:")
if valid_email:
break
Substitute valid_email with your way of validating the email address.
You may also be interested in Python check for valid email address? for ways to validate an email address.
First of all - you should not implement any activity of this kind into __init__ method, as one is intended for object fields initialization first place. Consider dedicated 'check_email' method, or whatever name applies best.
Now, regarding your case:
class test:
def __init(self):
# whatever initialization applies
pass
def init_emails():
emails = []
proceed = True
# if you really in need of do/while loop
while proceed:
email = self.input_email()
# your logic for input
if email is not None:
emails.append(email)
# invalid input or cancel
else:
proceed = False
return input
def input_email(self):
value = input('Enter your email:')
# TODO: validate/check input
return proper_value
class test:
def __init__(self):
self.email = self.get_name()
def get_name(self) :
while True:
x = input("Enter your email: ")
if (re.search(r'[\w.-]+#[\w.-]+.\w+', x)) :
return x
This script functions as described, in the end printing the name and email. If you need to use python2.7, use raw_input instead of input. I used for i in range instead of while True to avoid an endless loop.
#!/usr/bin/env python3
import re
import sys
class Test(object):
def __init__(self):
self.email = None
self.name = None
def get_email(self):
for i in range(3):
email = input('Enter your email: ')
if re.search('[\w.-]+#[\w.-]+.\w+', email):
return email
print('Too many failed attempts!')
sys.exit(1)
def get_name(self):
for i in range(3):
name = input('Enter your name: ')
if name:
return name
print('Too many failed attempts!')
sys.exit(1)
def initialize(self):
self.email = self.get_email()
self.name = self.get_name()
print('"{}" <{}>'.format(self.name, self.email))
if __name__ == '__main__':
t = Test()
t.initialize()
Instead of input, try to use raw_input. Like this:
self.email = raw_input("Enter your email:")
There'll be no error anymore.
Hope this helps.
So I'm writing a script to keep track of my correspondence.
It takes the name of someone who emailed me, looks for its associated 'Friend object' in a shelved dictionary of Friend instances (or creates itself a new instance and stores it in the dictionary), then appends the current time to that instance's list of timestamps.
So for example, if the script runs with 'John Citizen' as the input, it finds the key 'John Citizen' in the dictionary, gets the instance associated with that key, goes to that instance's list and appends to that list a timestamp.
This is all working as I want it to, except for the appending.
Here's the friend object:
class Friend():
def __init__(self, name):
self.name = name
self.timestamps = []
def add_timestamp(self, timestamp):
self.timestamps.append(timestamp)
Here's the global function that processes the input into a name string. (The input comes from AppleScript and is always in this format:
Input: "First [Middles] Last <emailaddress#email.com>"
def process_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("sender", help="The output from AppleScript")
args = parser.parse_args()
full_name = args.sender
## gets just the name
words = full_name.split(' ')
words.pop()
full_name = ' '.join(words)
## takes away all the non alpha characters, newlines etc.
alpha_characters = []
for character in full_name:
if character.isalpha() or character == " ":
alpha_characters.append(character)
full_name = ''.join(alpha_characters)
return full_name
And then here's the script handling that full_name string.
## Get the timestamp and name
now = datetime.datetime.now()
full_name = process_arguments()
## open the shelf to store and access all the friend information
shelf = shelve.open('/Users/Perrin/Library/Scripts/friend_shelf.db')
if full_name in shelf:
shelf[full_name].add_timestamp(now)
shelf.close
else:
shelf[full_name] = Friend(full_name)
shelf.close
I've tried to debug it and full_name in shelf evaluates to True and the problem is still happening.
I just can't seem to get that self.timestamps list to populate. I would really appreciate any help!
You need to extract, mutate and store the object back in the shelf to persist it.
e.g
# extract
this_friend = shelf[full_name]
# mutate
this_friend.add_timestamp(now)
# re-add
shelf[full_name] = this_friend
shelf.close()
You can see an example of this in the python docs.
The other option is pass the writeback parameter as True to shelve.open and it will allow you to write to the keys directly.
#paulrooney answered this.
Objects in the shelf need to be removed from the shelf, assigned to a name, mutated (to add time stamp), then put back in the shelf. This code works fine.
shelf = shelve.open('/Users/Perrin/Library/Scripts/friend_shelf.db')
if full_name in shelf:
this_friend = shelf[full_name]
this_friend.add_timestamp(now)
shelf[full_name] = this_friend
print shelf[full_name].timestamps
shelf.close
else:
shelf[full_name] = Friend(full_name)
this_friend = shelf[full_name]
this_friend.add_timestamp(now)
shelf[full_name] = this_friend
shelf.close