简体   繁体   中英

Can you assign an if statement as a variable and how do you print the result from an if statement when it is a calculation

Hello everyone I am stuck on my homework for python and I have searched the forum and have tried to figure it out for three hours now. I still can't find an answer or figure it out. It might be there but my lack of knowledge may have kept me from seeing it.

I'm using python version 3.2.3.

I cannot figure out how to display the results from the if statement in my print statement. So if the persons age is < 40 it says "you are young" and if the persons age is > 40 it prints "you look great". I easily have it print the first time but then I need it to print at the end where msg is located I cannot figure out how. I included all the code in case I am not explaining this right.

print("Hello", firstname, lastname, "you're", age, "years old", msg)

Thanks for the help in advance and again I apologize if the answer is already here somewhere

# ITP 100 Python Programming
# In Class Challenge September 10, 2012

# Getting users name and age as input
firstname = input("Hello. What is your first name? ")
lastname = input("What is your last name? ")

birthyear = input("What year where you born? ")
birthyear = int(birthyear)

age = 2012 - birthyear
print("\nYou're", age, "years old.")

if age < 40: 
    print("you are young.")

else:
    print("You look great.")


print("Hello", firstname, lastname, "you're", age, "years old", msg) 


input("\n\nPress n to exit")

You can create a variable that stores a string (your statement either "you are young." or "You look great." , or any string you want!) and display it later in your script. You have already assigned strings to variables earlier in your script when you create firstname and lastname .

The problem is, you haven't initialized the variable msg. You can't use it yet, because until the print statement, it hasn't shown up in the program. What you should do is store the "You are young" etc. messages in a variable, such as msg. That way you can access it later.

What about that ?

if age < 40: 
    msg = "you are young."
else:
    msg = "You look great."
print(msg)

Now, you have defined msg and you can use it later in your final print . And now, for an exercise: find a way to do that automatically when the user enters an age: you would define a function that takes a integer birthyear as input and would output a given message depending on the age...

您可以执行以下操作:

print("You " + "are young." if age < 40 else "look great.")

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM