Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

python - Conditional Statements and multiple functions

My task is to:

  1. Define a function check_age that takes age as a parameter.
  2. If the age is at least 18, you return a string allowed.
  3. If the age is anything else, you return a string not allowed.
  4. You define a function enter_scrollbar.
  5. You ask the user for his / her name "What is your name? ", and assign the input value to a variable.
  6. You ask the user for his / her age "How old are you? ", and assign the input value to a variable.
  7. You call the function check_age() and give it the age as a parameter (inside the parenthesis). The returned string of the the function is stored in a new variable (i.e. legal).
  8. You print a personalized message to the user about if he / she is allowed to drink. Your output should look similar to Welcome _____. You are __________ to drink beer.
  9. Call the function enter_scrollbar() to run your code.

This is my code so far:

def check_age(age):
    """This function checks wether the person is allowed to drink based on age."""
    if age >= 18:
        return "allowed"
    else:
        return "not allowed"

def enter_scrollbar():
    """This function checks for name and age."""
    name = input("What is your name? ")
    age = int(input("How old are you? "))
    
check_age(age)
message = f"Welcome {name}. You are {legal} to drink beer."
enter_scrollbar()

I think I am having some trouble calling the functions or defining them. I get this error message:

NameError: name 'age' is not defined
question from:https://stackoverflow.com/questions/65885783/conditional-statements-and-multiple-functions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that your not defining age out of the funtion. You need to return name and age and set them to a variable, if that makes sense. Try this:

def check_age(age):
    """This function checks wether the person is allowed to drink based on age."""
    if age >= 18:
        return "allowed"
    else:
        return "not allowed"

def enter_scrollbar():
    """This function checks for name and age."""
    name = input("What is your name? ")
    age = int(input("How old are you? "))

    return name, age

name, age = enter_scrollbar()
 
legal = check_age(age)
message = f"Welcome {name}. You are {legal} to drink beer."
print(message)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...