I'm trying to make a simple function where python would calculate age depending on your year input. I've tried several ways and I haven't had luck atm.
ps. sorry, I'm a newbie at this.
ame = input(" Enter your name: ")
age = input(" When were you born?: ")
print("Hello " + name + "! You are " + input (2021 - age)
import datetime
# get the year so it works all the time.
year = datetime.datetime.today().year
name = input(" Enter your name: ")
birth_year = input(" When were you born (year) ?: ")
# calclute the age
age = year - int(birth_year)
print("Hello " + name + "! You are ", age)
There are other ways to print which might look more clean:
print(f'Hello {name}! You are {age}')
or
print("Hello {0}! You are {1}".format(name, age))
To make it a function:
import datetime
def age_cal(birth_year):
# get the year so it works all the time.
year = datetime.datetime.today().year
return year - int(birth_year)
if __name__ == "__main__":
name = input(" Enter your name: ")
birth_year = input(" When were you born (year) ?: ")
age = age_cal(birth_year)
print("Hello {0}! You are {1}".format(name, age))
Here is what you can do: convert age to integer, then subtract it from 2021.
ame = input(" Enter your name: ")
age = input(" When were you born (year) ?: ")
print("Hello " + name + "! You are ",2021- int(age))
Let’s go through the code sample you provided line-by-line.
name = input(" Enter your name: ")
This line creates a variable called name and assigns it to the return value of the built-in function input.
age = input(" When were you born? ")
This does the same, but for the variable age. Note that this stores a string (some characters) not an int. You’ll probably want to convert it, like this:
age = int(age)
Next, you’re trying to print:
print("Hello " + name + "! You are " + input (2021 - age)
But to figure out what to print, Python has to evaluate the return of input(2021-age). (Remember in your code that age was a string; you can’t subtract strings and ints).
You’ve got another problem here- you’re prompting and waiting for input again, but you don’t need to. You’ve already stored the user’s input in the age and name variables.
So what you really want to do is:
print("Hello, " + name + "! You are " + 2021 - age )
Now, if you wanted to be a little more concise, you could also do:
print(f"Hello, {name}! You are {2021 - age}")
You can convert input to int and format your print statement, like below.
name = input("Enter your name: ")
age = int(input("When were you born? (year): ")) # convert input to int
print("Hello {}! You are {} years old".format(name, (2021-age))) # format output
You can make a simple function with datatime like this:
from datetime import date
name = input(" Enter your name: ")
year = int(input(" When were you born?: "))
def calculateAge(year):
today = date.today()
age = today.year - year
return age
print("Hello " + name + "! You are " + str(calculateAge(year)))
This isn't a function for that you have to use def anyway this is the code
Code-
from datetime import date
todays_date = date.today()
name = input(" Enter your name: ")
dob = int(input(" When were you born?: "))
print("Hello " + name + "! You are " + todays_date.year - dob)
Related
name = input(enter name)
age = input(age)
print(“My name is print(name). I’m print(age) years old.”)
Nobbie experiment.
Beginner level task.
And the above query came to my mind.
name = input("enter name: ")
age = input("age: ")
print(f"My name is {name}. I am {age} years old")
Study and try to understand Keshav V. answer using f-strings, this is the "modern" approach and will serve you well time after after time.
A more long handed approach would be to rewrite your program like this (as a stepping stone to understanding the f-string format)..
name = input("enter name ")
age = input("age ")
print("My name is", name, "I’m", age, "years old.")
Notice that print will accept as many items as you want to print and place them on the same line.
You could also use f-string formatting once you have capture the input in name and age variable.
print(f"My name is {name}. I'm {age} years old")
My name is laura. I'm 18 years old
You can simply use python f-strings.
name = input('Enter your name ')
age = input ('Enter your age ')
print(f'My name is {name}. I\'m {age} years old.')
If you also want you can go with the format function.
or this
name = input('Enter your name ')
age = input ('Enter your age ')
print('some text' + name + 'also some text')
good luck at programming,
You can also try string formatting.
name = input('Enter your name ')
age = input ('Enter your age ')
print('My name is {}. I\'m {} years old.').format(name,age)
More About String Formatting
Would be a good idea to take some time to read a Python book.
name = input("enter name")
age = input("age")
print( f"My name is {name}. I'm {age} years old.")
You can use a formatted string for this:
def name_and_age(name, age):
return f"My name is {name} and I'am {age} years old"
print(name_and_age('Max', 35))
#output: My name is Max and I'am 35 years old
Python 3, functions.
There is the following exercise:
Write a function that asks the user to enter his birth year, first name and surname. Keep each of these things in a variable. The function will calculate what is the age of the user, the initials of his name and print them.
for example:
John
Doh
1989
Your initials are JD and you are 32.
Age calculation depends on what year you are doing the track,
you should use input, format etc.
the given answer is:
def user_input():
birth_year = int(input("enter your birth year:\n"))
first_name = input ("enter your first name:\n")
surname = input ("enter your surname:\n")
print ("your initials are {1}{2} and you are {0} years old". format(first_name[0], surname[0],2021-birth_year))
when I run this the terminal stays empty,
hope you could help,
thank you in advance!
Make sure to call your function, so that it gets executed:
def user_input():
birth_year = int(input("enter your birth year:\n"))
first_name = input("enter your first name:\n")
surname = input("enter your surname:\n")
print("your initials are {1}{2} and you are {0} years old".format(first_name[0], surname[0], 2021-birth_year))
# Call it here
user_input()
The terminal stays empty is because you did not call the function to execute it.
def user_input():
birth_year = int(input("Please enter your birth year: "))
surname = input("Please enter your surname: ")
first_name = input("Please enter your first name: ")
print("\n\nYour initials are {1}{0} and you are {2} years old".format(first_name[0], surname[0], 2021-birth_year))
# remember to call the function
user_input()
Small change:
You can use the DateTime module to change the year rather than the hardcoded year value.
from datetime import date
def user_input():
birth_year = int(input("Please enter your birth year: "))
surname = input("Please enter your surname: ")
first_name = input("Please enter your first name: ")
print("\n\nYour initials are {1}{0} and you are {2} years old".format(first_name[0], surname[0], date.today().year-birth_year))
# remember to call the function
user_input()
Hello I got some stuck in my code and I tried but I still don't know how to fix it. Here it's my code.
def staff_info (name):
print ("So you are " + name + ", years old. ")
name = input ("Type your name: ")
confirm_info = input ("So you have " + name + ". Confirm that? (Yes/No) ")
if confirm_info == "Yes":
print ("Okay so I have few more question for you. ")
else:
confirm_info == "No"
change_info = input ("So what do you want to change? ")
if change_info == "name":
name_change = input ("Type the name you want to change: ")
name = name.replace (name_change) #error here
...
else:
...
print ("So you are " + name + ", " + age + " years old. You have over " + result_experience1 + " with code.")
If you could explain it and give me a command to solve it, I'd appreciate it. My adventure with Python beginning last week from now. Thanks you.
Thereplace method takes two mandatory parameters:
The substring you want to replace
The new value
So, change this
name = name.replace (name_change)
to
name = name.replace(name, name_change)
More here
You can try this:
def staff_info(name):
print("So you are " + name + ", years old. ")
name = input("Type your name: ")
confirm_info = input("So you have " + name + ". Confirm that? (Yes/No) ")
if confirm_info == "Yes":
print("Okay so I have few more question for you. ")
elif confirm_info == "No":
change_info = input("So what do you want to change? ")
if change_info != name:
name_change = input("Type the name you want to change: ")
new_name = name_change.replace(name, name_change)
print("New Name = ", new_name)
else:
print("...")
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
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")
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.'
This seems to be thrown from declaration of main().
Check the main function whether you used double underscore( __ ) or triple underscore( ___ ).
the correct synax is if __name__ == '__main__':
Hope this helps! Cheers!
I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on this code for 2weeks now and I have tunnel vision and cannot work it out:
Basically our assignment was to get to grips with Object-Oriented Programming. We unfortunately have to use "get" and "set" which I've learnt a lot of people dislike, however, as per our tutor we have to do it like that. We were told tp create a program whereby the user is presented with a screen with 3 options. 1. adding a student. 2. viewing a student and 3. removing a student.. within my AddStudent function I have to ask the user to enter fname Lname age degree studying id number (these are the easy bits) and also module name and grade for each module, I have managed to create a loop whereby it will ask the user over and over to enter modules and corresponding grades and will break from said loop when the user enters -1 into the modulname field. However, when trying saving it to a list named students[] ... (which is at the very top of my code above all functions, to apparently make it global) it saves all input from the user re: age name etc but when it comes to saving module names and grades it only saves the last input and not the multiple inputs I need it to. I am unsure if it is within my AddStudent function where it isn't saving or within my ViewStudent function: Both are below (remember I HAVE to use the GET and SET malarky) ;)
students[] # Global List
def addStudent():
print
print "Adding student..."
student = Student()
firstName = raw_input("Please enter the student's first name: ")
lastName = raw_input("Please enter the student's last name: ")
degree = raw_input("Please enter the name of the degree the student is studying: ")
studentid = raw_input("Please enter the students ID number: ")
age = raw_input("Please enter the students Age: ")
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
student.setFirstName(firstName) # Set this student's first name
student.setLastName(lastName)
student.setDegree(degree)# Set this student's last name
student.setGrade(grade)
student.setModuleName(moduleName)
student.setStudentID(studentid)
student.setAge(age)
students.append(student)
print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system."
........................
def viewStudent():
print "Printing all students in database : "
for person in students:
print "Printing details for: " + person.getFirstName()+" "+ person.getLastName()
print "Age: " + person.getAge()
print "Student ID: " + person.getStudentID()
print "Degree: " + person.getDegree()
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
your problem is that the module is a single variable you keep changing. instead, make it a list.
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
should be something like
modules = []
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
modules.append((moduleName, grade))
add a new variable to student which is "Modules" and is a list.
and then modules will be a list of tuples which are (moduleName, grade) and to display them, change the line in viewstudent from:
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
to:
for module, grade in person.getModules():
print "Module: " + module
print "Grades: " + grade
It seems you need something like this:
modules = {}
while True:
module_name = raw_input("Please enter module name: ")
if module_name:
grade = raw_input ("Please enter students grade for " + module_name +": ")
modules[module_name] = grade
Modules is a dictionary ("hash map" in other languages), each mod name is key and grades are values, or you could also do it with tuples, wherever floats your boat.
Instead of checking for -1 as a stop condition you check if is true, in python anything empty is evaluated to false.