I’m still learning how to work within classes. I’m trying to get user input from the user using self methods (Training exercises).
Here is my code (I just want to get the user input and display it, but with using methods)
import os
import time
class Programs:
def basicintro(self):
print "Welcome to the BMR Calculator"
time.sleep(1)
def createname(self,name):
self.name = name
def ask(self):
while name == "":
name = raw_input("Name:")
if name != "":
print "Hello", name
time.sleep(1)
else:
print name
def main():
object1 = Programs()
object1.basicintro()
object1.createname()
object1.ask()
raw_input("\n\nPress enter to exit.")
main()
I basically just want to ask the user to input their name and then make their name an object so if i need it later in the program, I can just call it
I’d say that there are a couple of problems in your code:
First you need a good input cycle, I’ll use a simple one:
Let’s put this cycle inside your class:
For what I understand you want to store the name provided by the user as an attribute of of your
Programclass instance, so:Example:
As you can see the method
__init__was called immediatly and placed assigned the empty string toprog.name.If you want to put that example code inside your script, this is how to do it:
If you want, you can put that code inside a function, but what I wanted to show the use of
if __name__ == '__main__':. Information can be found in this well answered question.