How can I have one function calling another function (as its argument)? - python

def GetAge():
age = int(input("Please enter your age: "))
return age
def DetermineAge():
if age < 2:
print("Stage of Life: A Baby")
elif age < 4:
print("Stage of Life: A Toddler")
elif age < 13:
print("Stage of Life: A Kid")
elif age < 20:
print("Stage of Life: A Teenager")
elif age < 65:
print("Stage of Life: An Adult")
elif age >= 65:
print("Stage of Life: An Elder")
else:
print("Mistakes were made, please restart the program and try again.")
age = GetAge()
DetermineAge()
Trying to remove age out of age = GetAge how do I do that with my function? I already define age in my function and return it I only want my main code to say GetAge() and DetermineAge()

Change DetermineAge to take age as an argument:
def DetermineAge(age):
# rest of function is the same
and then the caller can pass the value as an argument directly instead of needing the variable age to be defined in the caller's own scope:
DetermineAge(GetAge())
Alternatively, you could have DetermineAge call GetAge() itself:
def DetermineAge():
age = GetAge()
# rest of function is the same
and then the caller can just do:
DetermineAge()
If you wanted the function itself to be an argument, you could also do that:
def DetermineAge(get_age_func):
age = get_age_func()
# rest of function is the same
DetermineAge(GetAge)

You can use a decorator function that takes a function as an argument and calls it with #, like this
def DetermineAge(func):
def wrapper(*args, **kwargs):
age = func(*args, **kwargs)
if age < 2:
print("Stage of Life: A Baby")
elif age < 4:
print("Stage of Life: A Toddler")
elif age < 13:
print("Stage of Life: A Kid")
elif age < 20:
print("Stage of Life: A Teenager")
elif age < 65:
print("Stage of Life: An Adult")
elif age >= 65:
print("Stage of Life: An Elder")
else:
print("Mistakes were made, please restart the program and try again.")
return age
return wrapper
#DetermineAge
def GetAge():
age = int(input("Please enter your age: "))
return age
age = GetAge()

Related

I want to make this age_alarm function return nothing when I put str

def age_alarm(age):
print(f"you are {age} years old")
if age < 18:
print("you cannot buy alcohol")
elif age==18:
print('Congratulation. Now you can have it')
elif type(age) is not int:
return None
else:
print('enjoy your drink')
age_alarm(18)
age_alarm('d')
I want to return nothing when I use age_alarm('sth') but it keeps return you are d years old
what should I do?
In your code print() is always called inside age_alarm.
If you don't want the function to print anything in case a string is passed in, you need to add a check and return before the print anything.
For example:
def age_alarm(age):
if type(age) is not int:
return None
print(f"you are {age} years old")
if age < 18:
print("you cannot buy alcohol")
elif age==18:
print('Congratulation. Now you can have it')
else:
print('enjoy your drink')
age_alarm(18)
age_alarm('d')
prints
you are 18 years old
Congratulation. Now you can have it
def age_alarm(age):
if not isinstance(age,int): #checks if age isn't an integer.
print(f"{age} is not an actual age")
return # if age isn't an int it will return None
print(f"Your age is: {age}")
if age < 18:
print("You cannot buy alcohol.")
elif age == 18:
print("Now you can buy alcohol.")
else:
print("Enjoy your drink.")
return True
def age_alarm(age):
print(f"you are {age} years old")
if type(age) is not int:
return None
else:
if age < 18:
print("you cannot buy alcohol")
elif age==18:
print('Congratulation. Now you can have it')
age_alarm(18)
age_alarm('d')

Python - Basic Coding

I am new to coding in Python. I am trying to make my code so that if I enter the age a series of text will be printed. However, my code only works if i follow it line by line. For example, when i input the age 2000+ immediately nothing will happen. I need to first input an integer less than 12, followed by an integer over 2000.
print('Please input name')
if input() == 'Alice':
print('Hi, Alice.Please input age')
if int(input()) < 12:
print('You are not Alice, kiddo.')
elif int(input()) > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif int(input()) == 100:
print('You are not Alice, grannie.')
elif 12 < int(input()) < 99:
print('You are Alice!.')
var = input('Please input name ')
if var == 'Alice':
var = int(input('Hi, Alice.Please input age '))
if var < 12:
print('You are not Alice, kiddo.')
elif var > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif var == 100:
print('You are not Alice, grannie.')
elif 12 < var < 99:
print('You are Alice!.')
else:
print ("Invalid Name")
This code works because it asks one time and tries to see if some conditions are true, instead of asking each time.
Here I wrote code for your understanding purpose. Take new variable, so that no need to repeat input() method several times. Also, Age validation code keeps inside the first condition and it will be executed when the 1st condition will be true.
print('Please input name')
var = input()
if var == 'Alice':
print('Hi, Alice.Please input age')
var = input()
try:
if int(var) < 12:
print('You are not Alice, kiddo.')
elif int(var) > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif int(var) == 100:
print('You are not Alice, grannie.')
elif 12 < int(var) < 99:
print('You are Alice!.')
except Exception as ex:
print('Invalid Data: Error: ' + ex)
else:
print ("Invalid Name")
Every time you go to another branch in you if you are asking user to enter another age! Instead do the following:
age = int(input())
if age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif age == 100:
print('You are not Alice, grannie.')
elif 12 < age < 99:
print('You are Alice!.')
print('Please input name')
if input() == 'Alice':
print('Hi, Alice.Please input age')
age = int(input()) # take input and assign it on a variable
if age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif age == 100:
print('You are not Alice, grannie.')
elif 12 < age < 99:
print('You are Alice!.')
input is invoked every time when followed by (). So the multiple input()'s in the if elif's are not necessary.
store the result of input() like age = int(input()), then use age in the if and elif parts instead.
The input() function returns a string. Quoting the docs (emphasis mine):
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
So, in each if when you call input(), you have to enter a new string. Thus, you have to first enter an integer below 12.
To fix this problem, you need to store the original input in a variable. Now, as the docs say, input() returns a string. So, either you can cast (using int()) the integer in each case, by doing:
if int(age) < 12:
and storing the variable as a string.
Though, unless you do not have any specific reason to keep the age as a string, I'd recommend you to convert the string while storing the age in the variable in the first place:
age = int (input())
In this case, age will have an int.
Hopefully, this is what you are looking for:
while True:
name = input("Please ENTER your name: ")
if name == "Alice":
print("Hi Alice!")
break
print("Sorry, your name isn't correct. Please re-enter.")
age = False
while age != True:
age = int(input("Please ENTER your age: ")
age = True
if age < 12:
print("You're not Alice, kiddo.")
age = False
elif age > 2000:
print("Unlike you, Alice is not an undead, immortal vampire.")
age = False
elif age == 100:
print("You're not Alice, Granny!")
age = False
else:
print("You are Alice!")
age = True

How to use a conditional test to exit a while loop?

First a little about the program itself:
A conditional test begins the while loop (I have to use a conditional test to begin and end the loop, No flags and no break statements)
Asks for users age (user input)
Depending on the user input, it prints out different answers
My problem is that I want the program to end if the user input is 'quit'. The user input will besides 'quit' always be an int, because the program checks the users age.
This is my code:
prompt = "\nPlease enter your age to see the price for a ticket. \nEnter 'quit' when done: "
age = ""
while age != "quit":
age = input(prompt)
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age > 3 and age < 12:
print("Ticket is $10")
else:
print("Ticket is $15")
This is the error i get when i put 'quit' as the input:
Please enter your age to see the price for a ticket. Enter 'quit' when done: quit
Traceback (most recent call last): File "while_loops.py", line 60, in <module>
age = int(age) ValueError: invalid literal for int() with base 10: 'quit'
Many thanks in advance for your time and effort! Best regards HWG.
Check for quit before you try to convert to int. Run in an infinite loop and break out of it when you read the input quit.
prompt = "\nPlease enter your age to see the price for a ticket. \nEnter 'quit' when done: "
while True:
age = input(prompt)
if age == "quit":
break
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age > 3 and age < 12:
print("Ticket is $10")
else:
print("Ticket is $15")
Alternative which meet added criteria
not use 'break' or a variable as a flag
Using an exception
while ageStr != "quit":
ageStr = input(prompt)
try:
age = int(ageStr)
if age < 3:
print("Your ticket is free.")
elif age > 3 and age < 12:
print("Ticket is $10")
else:
print("Ticket is $15")
except ValueError:
pass
Using continue.
Note: this is bad as you specify and check for "quit" twice in the code and the control flow is overly complicated.
prompt = "\nPlease enter your age to see the price for a ticket. \nEnter 'quit' when done: "
age = ""
while age != "quit":
age = input(prompt)
if age == "quit":
continue
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age > 3 and age < 12:
print("Ticket is $10")
else:
print("Ticket is $15")
while True:
age = input("\nPlease enter your age to see the price for a ticket. \n Enter 'quit' when done: '"
if age == 'quit':
break
# continue with the rest of your code
Just check to see if the input is 'quit', if so, break out of the infinite loop.

Convert variable from int to str in a while loop? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I'm going through the book Python Crash Course and ran into a little hiccup on one of the exercises. Basically it asks you to create a while loop that tells the user to input their age and it will return the price of a ticket based on their age. This is supposed to repeat until the user types 'quit'. Pretty simple, except I'm confused as to how I would go from converting the input from an integer (their age) to a string ("quit"). I get the error: "invalid literal for int() with base 10: 'quit'" whenever I try to type quit. This is what I have so far:
age_prompt = "\nWrite in your age: "
age_prompt += "\nType 'quit' to exit "
while True:
age = int(input(age_prompt))
if age < 3:
print("Your ticket is free.")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
if age == 'quit':
break
You would need to test if the variable was "quit" before converting to an integer (because "quit" obviously isn't a number, so Python rightly complains).
Here's how you could do it:
while True:
age = input(age_prompt)
if age == 'quit':
break
try:
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
except ValueError:
print("Invalid input. Please enter a valid number or 'quit'")
age_prompt = "\nWrite in your age: "
age_prompt += "\nType 'quit' to exit "
while True:
try:
age = input(age_prompt)
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
except ValueError:
if age == 'quit':
break
Check to see if it is an int. If not, check if it is 'quit'
User input is received as a string from the call to input(). In your example, you are directly converting the output of input() into an integer:
age = int(input(age_prompt))
Once you have converted the input to an integer, you can no longer compare the integer to the string "quit" as they are not directly comparable. You can process the input string before converting to an integer.
# read user input as a string
user_input = input(age_prompt)
if user_input == "quit":
quit()
elif user_input == SOME_OTHER_COMMAND:
other_command()
else:
# try to convert input into an integer
try:
age = int(user_input)
except ValueError:
print "Input '%s' is invalid!"
quit()
if age < 3:
...
Try this:
age_prompt = "\nWrite in your age: "
age_prompt += "\nType 'quit' to exit "
while True:
age = raw_input(age_prompt)
if age == 'quit':
break
else:
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
you would have to use seperate variables (or exceptions - without example)
while True:
ui = input(age_prompt)
if ui == 'quit':
break
age = int(ui)
if age < 3:
print("Your ticket is free.")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")

How do i print an output if the value entered is not an integer

I am trying to do two things here.
I want to print "value entered is not a valid age" if the input is not a number in this code:
age = float(input (' enter your age: '))
if 0 <age < 16:
print "too early for you to drive"
if 120 >= age >= 95:
print 'Sorry; you cant risk driving'
if age <= 0:
print 'Sorry,' ,age, 'is not a valid age'
if age > 120:
print 'There is no way you are this old. If so, what is your secret?'
if 95 > age >= 16:
print 'You are good to drive!'
Also, how can I repeat this program once it is done?
You could check whether input is a valid digit with isdigit method of str. For multiple times you could wrap your code to a function and call it as much as you want:
def func():
age = input (' enter your age: ')
if age.isdigit():
age = float(age)
if 0 <age < 16:
print "too early for you to drive"
if 120 >= age >= 95:
print 'Sorry; you cant risk driving'
if age <= 0:
print 'Sorry,' ,age, 'is not a valid age'
if age > 120:
print 'There is no way you are this old. If so, what is your secret?'
if 95 > age >= 16:
print 'You are good to drive!'
else:
print "value entered is not a valid age"
func()
For make this code runnig every time you should add a loop , like while loop , and add a break whenever you want end this loop or add a condition for example run 10 times,and if you want check the input is float , you can add a try section:
counter = 0
while counter < 10:
age = raw_input (' enter your age: ')
try :
age = float(age)
if 0 <age < 16:
print "too early for you to drive"
if 120 >= age >= 95:
print 'Sorry; you cant risk driving'
if age <= 0:
print 'Sorry,' ,age, 'is not a valid age'
if age > 120:
print 'There is no way you are this old. If so, what is your secret?'
if 95 > age >= 16:
print 'You are good to drive!'
counter -= 1
except ValueError:
print "value entered is not a valid age"
It is also a good idea to arrange your cases in order, to make it easier to see what is happening (and to make sure you didn't leave an unhandled gap):
while True:
age = input("Enter your age (or just hit Enter to quit): ").strip()
if not age:
print("Goodbye!")
break # exit the while loop
try:
# convert to int
age = int(age)
except ValueError:
# not an int!
print("Value entered is not a valid age")
continue # start the while loop again
if age < 0:
print("Sorry, {} is not a valid age.".format(age))
elif age < 16:
print("You are too young to drive!")
elif age < 95:
print("You are good to drive!")
elif age <= 120:
print("Sorry, you can't risk driving!")
else:
print("What are you, a tree?")

Categories

Resources