How can I print the input values in between a line? - python

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

Related

Python: how to code a "response" based on user input when given multiple options?

I am new to Python and writing a simple program that is basically just an interactive conversation. I am asking the following question:
What is your name?
What is your gender?
What is your favorite color?
What is your birth year?
Do you have any pets?
etc.
The idea is to create as many response variables for each question as I can. For example: for "what is your gender?" if the user enters male, I want the response to be "Nice to meet you dude!", and if the user enters female I want the response to be "Nice to meet you miss!"
I would also like for the question "What is your birth year" to be met with a response that says You're "age"? You are so old!" (or something similar).
Below is what I have so far:
name = input('What is your name? ')
print('Hi ' + name + '!')
gender = input('What is your gender? ')
is_male = True
if is_male:
print('Nice to meet you, dude!')
else:
print('Nice to meet you, miss!')
favorite_color = input('What is your favorite color? ')
print(favorite_color + '? I love ' + favorite_color)
birth_year = input('What is your birth year? ')
age = 2021 - int(birth_year)
print(age + '? You are so old! ')
pets = input('Do you have any pets? ')
Any thoughts?
Thanks in advance!
I've found two bugs. Here, is_male is always True, so you'll always get the "dude" statement. And in case of age, age is int, so you can't concatenate int and str. Instead you can use fstring. Your corrected code:
name = input('What is your name? ')
print('Hi ' + name + '!')
gender = input('What is your gender? ')
if gender.lower()=="male" or gender.lower()=="m":
print('Nice to meet you, dude!')
else:
print('Nice to meet you, miss!')
favorite_color = input('What is your favorite color? ')
print(favorite_color + '? I love ' + favorite_color)
birth_year = input('What is your birth year? ')
age = 2021 - int(birth_year)
print(f'{age}? You are so old! ')
pets = input('Do you have any pets? ')
You have to convert an integer to string using str() when you concatenate a string with an integer.
age = 2021 - int(birth_year)
print('Your ' +str(age) + '? You are so old! ')
So you did most of it but you took an input
gender
but you did not use it
here:
is_male = True
if is_male:
this is_male is always true, you should read the input there instead of hardcoding it and give the user choices here like [M/F]
then you can continue like this
if gender == "M":
You might be looking for the elif statement like the following:
is_male = False
is_female = False
birth_year = input('What is your birth year? ')
age = 2021 - int(birth_year)
if age < 16:
print("Hello youngster.")
elif 16 <= age < 30:
print(r"Don't trust anyone over 30!")
elif 30 <= age < 50:
print("Metallica rules!")
else:
print("Take a nap. You deserve it.")
male_list = ["Bob", "Don","Joshua", "Cary", "Sachith" ]
female_list = ["Linda", "Tina","Janice", "Grace", "Stevie Nicks" ]
name = input('What is your name? ')
if name in male_list:
is_male = True
elif name in female_list:
is_female = True
if is_male:
print(f"Dude! Good to see you again {name}.")
elif is_female:
print(f"Good to see you again {name} my lady.")
else:
print(f'Nice to meet you {name}, we have not met.')
favorite_color = input('What is your favorite color? ')
print(f"{favorite_color} ? I love {favorite_color}")

Python 3 - functions beginners exercise

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()

Python input function, printing

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)

Regarding the string format in python, what does '[%s]' mean?

I saw a line of code:
re.compile('[%s]' % re.escape(string.punctuation))
But I have no idea about the function of [%s]
Could anyone help me please?
Thank You!
It is a string formatting syntax (which it borrows from C).
Example:
name = input("What is your name? ")
print("Hello %s, nice to meet you!" % name)
And this is what the program will look like:
What is your name? Johnny
Hello Johnny, nice to meet you!
You can also do this with string concentation...
name = input("What is your name? ")
print("Hello + name + ", nice to meet you!")
...However, the formatting is usually easier.
You can also use this with multiple strings.
name = input("What is your name? ")
age = input("How old are you? ")
gender = ("Are you a male or a female? ")
print("Is this correct?")
print("Your name is %s, you are %s years old, and you are %s." % name, age, gender)
Output:
What is your name? Johnny
How old are you? 37
Are you a male or a female? male
Is this correct?
Your name is Johnny, you are 37 years old, and you are male.
Now, please, before asking any more questions, see if they exist!

How do you print out the input you put in?

I am writing a piece of code which asks for the users first name then second name and then their age but then i print it out but I'm not sure how to please give an answer.
print ("What is your first name?"),
firstName = input()
print ("What is you last name?"),
secondName = input()
print ("How old are you?")
age = input()
print ("So, you're %r %r and you're %r years old."), firstName, secondName, age
You want to use string.format.
You use it like so:
print ("So, you're {} {} and you're {} years old.".format(firstName, secondName, age))
Or in Python 3.6 upwards, you can use the following shorthand:
print (f"So, you're {firstName} {secondName} and you're {age} years old.")
Use
print ("So, you're %r %r and you're %r years old." % (
firstName, secondName, age))
You might want to consider using %s for the strings and %d for the number, though ;-)
New style string formatting in Python:
print("So, you're {} {} and you're {} years old.".format(firstName, secondName, age))
This is the fixed code:
firstName = input("What is your first name?")
secondName = input("What is you last name?")
age = input("How old are you?")
print ("So, you're " + firstName + " " + secondName + " and you're " + age + " years old.")
It is pretty easy to understand, since this just uses concatenation.
There are two ways to format the output string:
Old way
print("So, you're %s %s and you're %d years old." % (firstName, secondName, age)
New way (Preferred way)
print("So, you're {} {} and you're {} years old.".format(firstName, secondName, age))
The new way is much more flexible and provides neat little conveniences like giving placeholders an index. You can find all the differences and advantages here : PyFormat

Categories