Issue
I'm trying to write a function that will ask for name, last name and year of birth. Also, it will later print out the initials and the age.
First of all, it doesn't ask for any of it.
Second of all, it doesn't matter what I'll enter it will print the error:
NameError: name "____" is not defined.
I'm using Python 3.
Here is the code:
def userinfo():
name_ = input("Enter your first name: ")
last_ = input("Enter your last name: ")
year_ = input("Enter your year: ")
initials_ = name_[0] + last_[0]
age_ = (2018 - year_)
_info = ("Your initials are ") + (initials_) + (" and you are ") + (str(age_)) + (" years old.")
if (len(name_) > 0 and len(last_) > 0 and len(year_) > 0 and name_.isalpha() and last_.isalpha()):
return (_info)
else:
return ("Error")
Solution
Here is a rectified code with some corrections:
1) Replacing input
with raw_input
(assuming you are using python 2.***
). In case you are using version 3+
, then replace back raw_input
by input
.
2) Replacing year_
by int(year_)
while calculating the age because user input is of type str
.
def userinfo():
name_ = raw_input("Enter your first name: ")
last_ = raw_input("Enter your last name: ")
year_ = raw_input("Enter your year: ")
print (name_)
initials_ = name_[0] + last_[0]
age_ = (2018 - int(year_)) # Correction here
_info = ("Your initials are ") + (initials_) + (" and you are ") + (str(age_)) + (" years old.")
if (len(name_) > 0 and len(last_) > 0 and len(year_) > 0 and name_.isalpha() and last_.isalpha()):
return (_info)
else:
return ("Error")
userinfo()
Output
Enter your first name: Donald
Enter your last name: Trump
Enter your year: 1950
Donald
'Your initials are DT and you are 68 years old.'
Answered By - Sheldore
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.