how to print string variable in python - python

name = input("What is your name: ")
age = int(input("How old are you: "))
year = str((2014 - age)+100)
print(name + " will be 100 years old in the year " + year)
I am trying this code in python, but it is not executing, what corrections needs to be done?

From your question
name = input("What is your name: ")
age = int(input("How old are you: "))
year = str((2014 - age)+100)
print(name + " will be 100 years old in the year " + year)
Your code is just fine, change your input to raw_input for name variable.
NOTE: raw_input returns a string, input tries to run as Python expression.

Related

How would I make an infinite loop in Python until a user inputs otherwise?

To clarify, this is similar to another question but I feel the answer is easier to understand.
I am making a very simple program for saying what year you will turn "x" years old. (It's a practice from Practice Python... Starting to relearn Python after a while) I would like the program to ask the user what age they want to know, and it does so. This works fine, but I do not remember how to have it keep asking until they write "n" and otherwise keep asking. Any ideas?
Thanks for the help! Code Below:
I've tried using a Java-esque loop, but this isn't Java, and I don't know what I'm doing. Up to any ideas.
# Libraries
import time
# Initial Code
name = input("What's your name? ")
print("Thank you " + name + "!")
age = int(input("How old are you? "))
year = int(input("Now, just for clarification, what year is it? "))
new_age = input("Now enter what age you would like to know! ")
print("Thank you! Now, I'll tell you the year you will turn " +new_age+ "!")
time.sleep(3)
print("Great, that calculation will only take a second or so!")
time.sleep(1.5)
math_year = year - age
answer = int(math_year) + int(new_age)
print(name + ", you will turn " + str(new_age) + " years old in " + str(answer) +"!")
time.sleep(3)
# Loop Code
again = input("Would you like to know another age? Y/n ")
if again == 'Y':
new_age = input("Awesome! What age would you like to know? ")
print("Great, that calculation will only take a second or so!")
time.sleep(1.5)
math_year = year - age
answer = int(math_year) + int(new_age)
print(name + ", you will turn " + str(new_age) + " years old in " + str(answer) +"!")
All results work, it just can't loop after the second time.
You can use while instead of if. Whereas if executes its block of code once, while will execute it again and again until the condition becomes false.
# Loop Code
again = 'Y'
while again == 'Y':
new_age = input("Awesome! What age would you like to know? ")
print("Great, that calculation will only take a second or so!")
time.sleep(1.5)
math_year = year - age
answer = int(math_year) + int(new_age)
print(name + ", you will turn " + str(new_age) + " years old in " + str(answer) +"!")
again = input("Would you like to know another age? Y/n ")
As of python 3.8 (so, sometime after late October this year), you'll be able to use the assignment operator := to take care of those first two lines at once:
# Loop Code
while (again := 'Y'):
...
again = input("Would you like to know another age? Y/n ")
hello try something like
while True:
"""
your code
"""
answer = input("again"?)
if answer == 'Y':
continue
elif answer == 'N':
break
else:
# handle other input as you want to
pass

Why does (BDate) is shown as syntax error

enter image description hereenter image description here
I tried everything I can It doesn't work pls help
print ("Enter today's date:")
DateToday = input()
print ("Enter your birthday {yyyy/mm/d)"
BDate = input()
Age = DateToday - BDate
print Age.year
I'm assuming you want just the year for age?
in which case you would do:
datetoday = int(input("Enter the current year: "))
bdate = int(input("Enter your birth year: "))
age = datetoday - bdate
print ("Your age is: " + str(age))
You forgot to add a few brackets and are asking for unnecessary data. This will give how many years old a person is.

How do I find the len() of multiple strings?

I need to find the len() of multiple strings.
current_year = input ("What year is it?")
current_year = int(current_year)
birth_year = input ("What year were you born in?")
birth_year = str(birth_year)
if len(birth_year) != 4:
print ("Please make your year of birth 4 digits long.")
else:
birth_year = int(birth_year)
print("You are " + str(current_year - birth_year) + " years old.")
I would like to include the len() of birth_year.
Use an elif statement to check the current year input.
current_year = input ("What year is it?")
birth_year = input ("What year were you born in?")
if len(birth_year) != 4:
print ("Please make your year of birth 4 digits long.")
elif len(current_year) != 4:
print ("Please make the current year 4 digits long.")
else:
birth_year = int(birth_year)
current_year = int(current_year)
print("You are " + str(current_year - birth_year) + " years old.")
There's no need for birth_year = str(birth_year), since input() always returns a string.
You should probably include try/except code around the calls to int(), so you can print an error if they enter a year that isn't actually a number.
Here is a way to get what you want that is somewhat more dynamic. With this basic function, if a user inputs an inappropriate string, they will be asked to retry. You could even add a line to check if the year was after the current year.
Note that there is a loop in here with an exit that doesn't have a constraint. If you were going to implement this, I'd add a counter as well which would kill the process to prevent infinite loops.
def get_year(input_string):
# Set loop control Variable
err = True
# while loop control variable = true
while err == True:
# get input
input_year = input(input_string + ' ')
# Ensure format is correct
try:
# Check length
if len(input_year) == 4:
# Check Data type
input_year = int(input_year)
# if everything works, exit loop by changing variable
err = False
# if there was an error, re-enter the loop
except:
pass
# return integer version of input for math
return input_year
# set variables = function output
birth_year = get_year('What year were you born? Please use a YYYY format!\n')
current_year = get_year('What is the current year? Please use a YYYY format!\n')
# print output displaying age
print("You are " + str(current_year - birth_year) + " years old.")

String Issue in Python

I would like to understand why one program of mine is giving error and one not where as I am applying same concept for both of them.
The program that is giving error:
greeting = "test"
age = 24
print( greeting + age)
Which is true and it should give error because of incompatible variable types being concatenated. But this same behavior I was expecting from the below code as well where as it is giving proper result. Why is it so?
print("Please enter your name: ")
myname = input()
print("Your name is " + myname)
print("Please enter your age: ")
myage = input()
print("Your age is: " + myage)
print("Final Outcome is:")
print(myage + " " + myname)
By default the input function in Python returns a string type. So when you enter the age, it is not being returned to your program as an int but rather a string. So:
print("Your age is: " + myage)
Actually looks like:
print("Your age is: " + "24")
input() returns a string, even if the user enters a number.

python random numbers and comparison

I'm a new programmer and just starting off with Python. I have the following 2 questions, however, I decided to put them in one post.
When asking to input age, how do I force the program to only accept numbers?
The concept is that after the user has entered their age, the program would pick a random number between 1 and 100 and compare it to the user input, returning either "I'm older than you", "I'm younger than you" or "we are the same age".
# Print Welcome Message
print("Hello World")
# Ask for Name
name = input("What is your name? ")
print("Hello " + str(name))
# Ask for Age
age = input("How old are you? ")
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
random.randint(1, 100)
Try the following
import random
# Print Welcome Message
print("Hello World")
# Ask for Name
name = input("What is your name? ")
print("Hello " + str(name))
# Ask for Age
while True: # only numbers
try:
age = int(input("How old are you? "))
except:
pass
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
t=random.randint(1, 100)
if t==age:
print("we are the same age") #compare ages
if t<age:
print("I'm younger than you")
if t>age:
print("I'm older than you")
Hi you can try this simply.
import random
name = input("What is your name? ")
print("Hello " + str(name))
while True :
try :
age = int(input("How old are you? "))
break
except :
print("Your entered age is not integer. Please try again.")
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
randNumber=random.randint(1, 100)
if randNumber > age :
print("I am older than you")
if randNumber < age :
print("I am younger than you")
else :
print("we are the same age")
Only made few changes to existing code with modifications asked.
import random
# Print Welcome Message
print("Hello World")
# Ask for Name
name = input("What is your name? ")
print("Hello " + str(name))
# Ask for Age
while True:
try:
age = int(input("How old are you? "))
except ValueError:
pass
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
my_random = random.randint(1, 100)
if my_random > age:
print("Im older than you")
elif my_random < age:
print("I'm younger than you")
else:
print("We are the same age")
Includ a try block around the age part. If the user inputs an non-int answer then it will just pass. I then saved the random int that you generated it and compared it to the age to find if the random int was greater than the age.
To answer your first question, use int() as such:
age = int(input("How old are you? "))
This will raise an exception (error) if the value is not an integer.
To answer your second question, you may store the random number in a variable and use it in comparison to the user's age, using conditional statements (if, elif, else). So for instance:
random.seed() # you need to seed the random number generator
n = random.randint(1, 100)
if n < age:
print("I am younger than you.")
elif n > age:
print("I am older than you.")
else:
print("We are the same age.")
I hope this answers your question. You can refer to the official Python docs for more info on conditional statements.
My guess is that you should convert the variable age into integer. For example:
age = input("How old are you?")
age = int(age)
This should work.
The answer to the 1st question.
x = int(input("Enter any number: "))
To force the program to enter number add int in your input statement as above.

Categories

Resources