I have a project in python where I want to assign names for my classes in School downtown in the Michigan High School. The classes that I have are '1B, 2B and 3B', and when the user inputs their name and classroom name, their class will be validated to ensure it is correct in the specific format '1,2 OR 3', 'B' - so they cannot write '4B' or '2A' because those classes do not exist.
So far, I have developed this block of code:
while True: # This starts the whole of the while loop.
class_name = str(input("Please enter your class name >>"))
if re.match("1A" "2A" "3A", class_name):
print("Incorrect. Please write your class name again.")
else:
print("Your class name has been accepted")
How can I validate the class_name variable so it can match the classroom names '1A, 2A or 3A?' Thanks,
Taylor Hayward.
Your logic is backwards (and your syntax is wrong, too). You don't want to test for a set of illegal class names (that set is far too large) - you want to test against the set of legal names and repeat if the test fails.
while True: # This starts the whole of the while loop.
class_name = input("Please enter your class name >>") # str() is unnecessary
if class_name not in {"1B", "2B", "3B"}:
print("Incorrect. Please write your class name again.")
else:
print("Your class name has been accepted")
break # Exit the while loop
A regex would also be possible:
if not re.match("[123]B$", class_name):
Note the $ anchor to ensure that the match ends after B, otherwise input like 2BC would be accepted by the regex (re.match() only anchors the match to the start of the string, not the end).
Related
I am trying to avoid using global, instead I created a class. I am having trouble calling the class, instead, I am getting the following error
TypeError: phone.__init__() missing 1 required positional argument: 'NUMBER_INPUT'
Any ideas? Thanks in advance!
class phone:
def __init__(self,NUMBER_INPUT):
self.NUMBER_INPUT = NUMBER_INPUT
def phone_number(self):
"""validate user input of phone number"""
while True:
self.NUMBER_INPUT = input("Please enter your phone number: ")
if re.fullmatch(r"\d{3}-\d{3}-\d{4}" ,self.NUMBER_INPUT):
print("You phone number is: " + self.NUMBER_INPUT)
break
print("Please enter a valid phone number ex. 123-456-5678")
phone().phone_number()
So, I think you neither did read documentation nor watched/read any tutorial about Python classes. So I will explain it here for you.
Class is a "object project". It may have predefined methods, predefined values. It also may have a way to construct these dynamically.
Class object at first need to be instantiated and then initiated. That means that firstly you need to create an instance of a class, then to initiate default values.
Python has 2 methods for this.
__new__() creates a new instance of a class and returns it. It's already realised for every Python class, but there may be special cases for you to override it.
__init__(*args, **kwargs) initiates values of a class. You must define non-static values here or globally in class.
So, creating a class object is achieved in python by calling class like this
A_instance = A(*args, **kwargs)
That in words means create me instance of A with these args and kwargs
So in your code, you are using (actualy overriding) __init__(*args, **kwargs) with args = (NUMBER_INPUT,) and kwargs = None.
Thus you must provide NUMBER_INPUT every time you create an object of phone, like so:
phone1 = phone("123-456-7890")
phone2 = phone("098-765-4321")
You must provide a value for NUMBER_INPUT when calling phone() like phone("123").phone_number().
But it would be better if you will use dummy value for NUMBER_INPUT in constructor like:
class phone:
def __init__(self):
self.NUMBER_INPUT = ""
def phone_number(self):
"""validate user input of phone number"""
while True:
self.NUMBER_INPUT = input("Please enter your phone number: ")
if re.fullmatch(r"\d{3}-\d{3}-\d{4}" ,self.NUMBER_INPUT):
print("You phone number is: " + self.NUMBER_INPUT)
break
print("Please enter a valid phone number ex. 123-456-5678")
phone().phone_number()
I know this is not hard, but I keep getting either an undefined error or different errors, I tried everything I could think of to get the solution. I placed the input variables outside of the code and it worked partially. I'm only 3 weeks or so into my first computer science class. help is appreciated, please & thanks.
# function that prompts the user for a name and returns it
def user():
name = input("Please enter your name: ")
return name
# function that receives the user's name as a parameter, and prompts the user for an age and returns it
def userAge(name):
age = input("How old are you, {}? ".format(name))
return age
# function that receives the user's name and age as parameters and displays the final output
def finalOutput(name, age):
age2x = int(age) * 2
print("Hi, {}. You are {} years old. Twice your age is {}.").format(name, age, str(age2x))
###############################################
# MAIN PART OF THE PROGRAM
# implement the main part of your program below
# comments have been added to assist you
###############################################
# get the user's name
user()
# get the user's age
userAge("name")
# display the final output
finalOutput("name", "age")
You're not storing the values the user supplies, or passing them back to your function calls, here:
user()
userAge("name")
finalOutput("name", "age")
Change the above lines to:
name = user()
age = userAge(name)
finalOutput(name,age)
Correction 1:
Don't pass arguments with double quotes, that means you are passing a string literal to the function not actual value of variable.
for example, if you assign variable name as "Jhon" and you pass it to the function as userAge("name") means you are passing string literal "name" to userAge() not variable value "Jhon".
def printName(name):
print(name)
name = "jhon"
printName("name")
output: name
def printName(name):
print(name)
name = "jhon"
printName(name)
output: jhon
Better assign the return value to some Valerie and pass without double quotes as mentioned by #TBurgis.
Correction 2:
Syntax mistake in print statement. Correct syntax should be
print("Hi, {}. You are {} years old. Twice your age is {}.".format(name, age, str(age2x)))
This question already has answers here:
__str__ returned non-string (type tuple)
(3 answers)
Closed 4 years ago.
I'm still very new to Python, and am struggling with what should be a simple assignment. I have to write code for an 'Employee' class, save the module, import the module into another .py file and then store and display 3 objects of that class. I keep getting a
"TypeError: __str__ returned non-string (type tuple)"
no matter how I rework the code, and it's driving me nuts. Anything I've done wrong, please, explain to me how/why it's wrong, learning this is incredibly important to me!
The following is the code for the Employee class:
class Employee:
def __init__(self,name,id,dept,title):
self.__name = name
self.__id = id
self.__dept = dept
self.__title = title
def set_name(self,name):
self.__name = name
def set_id(self,id):
self.__id = id
def set_dept(self,dept):
self.__dept = dept
def set_title(self,title):
self.__title = title
def get_name(self):
return self.__name
def get_id(self):
return self.__id
def get_dept(self):
return self.__dept
def get_title(self):
return self.__title
def __str__(self):
return 'Name: ',self.__name,'\n','ID Number: ',str(self.__id),'\n','Department: ',self.__dept,'\n','Job Title: ',self.__title
I'm not sure I need the set and/or get name methods, because the three objects I have to store and display are pre-determined (no user input or anything). The preceding code is saved in a file named emp.py. The following code is where I think the problem is, but being a novice I don't know for sure.
import emp
def main():
name = 'Susan Meyers'
id = '47899'
dept = 'Accounting'
title = 'Vice President'
employee1 = emp.Employee(name,id,dept,title)
name = 'Mark Jones'
id = '39119'
dept = 'IT'
title = 'Programmer'
employee2 = emp.Employee(name,id,dept,title)
name = 'Joy Rogers'
id = '81774'
dept = 'Manufacturing'
title = 'Engineer'
employee3 = emp.Employee(name,id,dept,title)
print('Employee 1:')
print(employee1)
print('Employee 2:')
print(employee2)
print('Employee 3: ')
print(employee3)
main()
I've tried this by creating an object (i.e. susan = emp.Employee['Susan',id number,'dept','title'] with the appropriate information where id, dept, title are, but still get the tuple error. What am I doing wrong? I considered storing the information in a list or dictionary, but figured I should stick to the bare-bones basics. I feel so stupid, I've been at this all day! For any and all help, thanks in advance.
EDIT: Fixed the indention errors (weren't present in my code in pycharm, but copying and pasting them here w/o proper proofreading...)
FURTHER EDIT:
When run, I need it to say:
Employee 1:
Name: Susan Meyers
ID Number: 47899
Department: Accounting
Title: Vice President
Employee 2:
Name: Mark Jones
ID Number: 39119
Department: IT
Title: Programmer
Employee 3:
Name: Joy Rogers
ID Number: 81774
Department: Manufacturing
Title: Engineer
**And that's the end of the program, like I said, should be really basic stuff, if this were a list or something, I could knock it out np... But each employee has to be stored as an object of the Employee class. We just covered an incredibly long chapter on Classes and Objects (while I was sick with the flu) so my recall/methods may not be the best.
The error's with the __str__ method itself
def __str__(self):
return 'Name: ',self.__name,'\n','ID Number: ',str(self.__id),'\n','Department: ',self.__dept,'\n','Job Title: ',self.__title
"TypeError: __str__ returned non-string (type tuple)"
This error notifies you that
'Name: ',self.__name,'\n','ID Number: ',str(self.__id),'\n','Department: ',self.__dept,'\n','Job Title: ',self.__title
is a tuple. (This is implicitly constructed from the comma-delimited notation.) However, Python is expecting a str as the return type. Change your return statement so that it returns a string. You can use
return ''.join(['Name: ',self.__name,'\n','ID Number: ',str(self.__id),'\n','Department: ',self.__dept,'\n','Job Title: ',self.__title])
or
return 'Name: {}\nID Number: {}\nDepartment: {}\nJob Title: {}'.format(self.__name, self.__id, self.__dept, self.__title)
or anything as long as it returns a string.
Edit: Clarification on Provided Solutions
The first solution uses the .join() method, which follows this format
<str_to_connect>.join(<iterable_of_str>)
The square brackets used ['Name: ',self.__name, ... self.__title] will pack all your various string arguments into a list. Passing this list into .join() connects it all together into a single str.
The second solution uses the .format() method which follows this format
<str_to_format>.format(<args>...)
You can pass complex formatting into the .format() function, but they generally make use of a {} placeholder, which are then filled with input from the arguments passed.
The essential thing is that both these will return str types.
Further reading: str.join(), PyFormat.
Note: C. Kim's solution in the comments, using %, is also equally valid.
How to add a name for editing in input?
New name
name = input("New your name : ")
print(name)
New your name :
How to add a name for editing ? (edit the name Charles)
something like
edit = "Charles"
name = input("Edit your name : " + edit)
print(name)
Edit your name : Charles
Thank you to help..
If your Python was compiled with readline support, you can actually do it using only the standard library:
import readline
def make_pre_input_hook(default):
def pre_input_hook():
readline.insert_text(default)
readline.redisplay()
return pre_input_hook
readline.set_pre_input_hook(make_pre_input_hook('Charles'))
name = input('Edit your name: ')
print('You are now called {}.'.format(name))
Note that with Python 2, you'd need to use raw_input instead of input.
I don't think there is any way to do this with just the command line. Instead, I suggest providing some default value in parentheses, and using that in case the user does not enter any input. This is also much more common and requires fewer keystrokes from the user in case he wants to change the default (no need to delete).
>>> name = input("Enter name (some default): ") or "some default"
Enter name (some default):
>>> name
'some default'
>>> name = input("Enter name (some default): ") or "some default"
Enter name (some default): foobar
>>> name
'foobar'
Here, the or "some default" has the effect that if the first part of the expression -- the result of input -- is empty, then the second part, i.e. the default value, is used.
How about:
defaultname = 'Charles'
nameprompt = 'Enter your name, or just press Return to accept the default name.\nDefault Name: '+defaultname
name = input(nameprompt)
if name == '':
name = defaultname
![enter image description here][1]i am creating two classes student(base) and detail .Detail is inheriting all the attributes of base .I am initializing the attributes (roll_no,name and class_stud)subclasses of base with students object of subclass created with student.subclasses().Here is the code:
student=type('student',(object,),{})
def getinfo():
for studen in student.__subclasses__():
studen.roll_no=input("enter the roll number")
studen.name=input("enter the name of student")
studen.class_stud=input("enter the class")
def printinfo():
print('roll number ',roll_no,name,class_stud)
detail=type('detail',(student),{'info':getinfo(),'print':printinfo()})
ob=detail()
ob.info
ob.print
I have never seen anyone create Python classes this way, except to see if they could. You have quite a few errors, but this might do what you want (although that is not clear):
student=type('student',(object,),{})
def getinfo(self):
for studen in student.__subclasses__():
studen.roll_no=input("enter the roll number: ")
studen.name=input("enter the name of student: ")
studen.class_stud=input("enter the class: ")
def printinfo(self):
print('roll number ',self.roll_no,self.name,self.class_stud)
detail=type('detail',(student,),{'info':getinfo,'print':printinfo})
ob=detail()
ob.info()
ob.print()
As you can see, your main error was in not passing the object into the methods. Other errors included a missing comma after student when defining detail. See also comments by #abarnert.
This is a horrible way of defining a class in Python.
EDIT:
I have no idea why you are iterating over subclasses, this is probably what you meant for getinfo:
def getinfo(self):
self.roll_no=input("enter the roll number: ")
self.name=input("enter the name of student: ")
self.class_stud=input("enter the class: ")