I am very new to python and trying to run a basic program. I am asking for input (name) from user. And when user enters the name, the program is throwing and error. Here is my program
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def get_data(self):
self.name = input("please enter name")
self.age = input("now age")
def print_data(self):
print self.name
print self.age
ajeet = Student("", "")
ajeet.get_data()
ajeet.print_data()
And below is the error
please enter name Apurv
Traceback (most recent call last):
File "/Users/apurvgandhwani/PycharmProjects/bio/AgeClass.py", line 18, in <module>
ajeet.get_data()
File "/Users/apurvgandhwani/PycharmProjects/bio/AgeClass.py", line 8, in get_data
self.name = input("please enter name")
File "<string>", line 1, in <module>
NameError: name 'Apurv' is not defined
Python version my system is using is 2.7.15
I have tried to look into the issue and from what I have read it is the python version issue. I aam supposed to use 3.x version. I installed python3 in my mac. But system is still using the old version. How am I supposed to run the program or change the python version to 3.x.
To change the python version, I have tried adding alias to the bash_profile as
alias python = 'python3'
But still there is the same error coming when I run the my program. How can I solve this?
Probably because you're not loading the .bash_profile
. Try this
source ~/.bash_profile
Also to avert this error in python2 change your input
to raw_input
which accepts strings.
The print lines should be enclosed in a pair of parentheses after print
in Python 3 like this: print()
. Otherwise you will get an error message that says: Missing parentheses in call to 'print'
Also when you enter a name in def get_data(self)
the name is a string so you should either use the str()
function in self.name = str(input("Please enter name: "))
to turn the input name into a string or else enclose the input name in a pair of quotes to make the input name a string that way. That is how to fix the error message: NameError: name 'Apurv' is not defined
when you try to enter Apurv
after where it says please enter name
.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def get_data(self):
self.name = str(input("Please enter name: "))
self.age = input("Please enter age: ")
def print_data(self):
print(self.name)
print(self.age)
ajeet = Student("", "")
ajeet.get_data()
ajeet.print_data()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.