1
\$\begingroup\$

I am new to coding for ~1 week. I know that I learn best by doing, and so I decided to work on a small and simple project while utilizing various online sources to learn as I go.

Anyway, I decided to write a little program that asks the user to input their age and then prompts the user to enter an age they wish to be while providing them with the difference and a few little exceptions along the way.

Since I am still new and am learning on my own, I decided to reach out to this forum and see if I can get any suggestive feedback on how I can improve my code and learn some new techniques. Thank you!

Points of interest:

  • I have it so the code loops back until integers are inputted.

  • The program can be recalled by the user to enter different values.

  • I am still working on making it so that negative values can not be inputted.

The Code:

# This program will prompt you to state your age and then will proceed to
# calculate how long till __ age
# Introduction
print("Hello. ")
# Defining Functions
def main():
 while True:
 try:
 myAge = int(input("Please enter your age: "))
 except ValueError:
 print("I'm sorry, please enter your age as a numeric value.")
 continue
 else:
 break
 def secondV():
 while True:
 try:
 global desiredAge
 desiredAge = int(input())
 print("Do you wish to be " + str(desiredAge) + "?")
 choose()
 except ValueError:
 print("Please enter a numeric value.")
 continue
 else:
 break
 def desiredFuture():
 while True:
 try:
 global desiredAge
 desiredAge = int(input())
 while True:
 if desiredAge < myAge:
 print(
 "Silly, time does not move backwards. Learn how to embrace the future, not fear it.")
 print('Please input an age you wish to be in the FUTURE now...')
 desiredFuture()
 break
 if desiredAge == myAge:
 print("You are already " + str(desiredAge))
 break
 else:
 print("Do you wish to be " + str(desiredAge) + "?")
 choose()
 break
 except ValueError:
 print("Please enter a numeric value.")
 continue
 else:
 break
 def choose():
 global yourWish
 yourWish = input()
 while yourWish.lower() == ("yes" or "y"):
 print("Okay... calculating...")
 import time
 time.sleep(1)
 print()
 print("To be " + str(desiredAge) + ", you would have to wait " + str(desiredAge - myAge) + " years. ")
 print()
 reDo()
 break
 else:
 print("Erm... please input your desired age now:")
 secondV()
 def reDo():
 print('Would you like to try again?')
 runBack = input()
 while True:
 if runBack.lower() in {'y', 'yes'}:
 print()
 main()
 else:
 print("Okay... Goodbye!")
 break
 print("You are " + str(myAge) + ".")
 print("What is your desired age? ")
 desiredFuture()
 choose()
 print()
main()
asked Dec 15, 2020 at 3:31
\$\endgroup\$
1
  • 2
    \$\begingroup\$ The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see How do I ask a good question?. \$\endgroup\$ Commented Dec 15, 2020 at 8:18

2 Answers 2

3
\$\begingroup\$
  1. Use if __name__ == '__main__' paradigm to prevent code execution if your .py file in imported by another python file.
  2. Don't call functions outside function scopes for the same reason as 1. So remove print('hello').
  3. Don't use global variables.
  4. Define functions outside other function scopes (This is not a general guideline but will make this particular code easier to read).
  5. Separate user IO from the core logic of the application. This will make your code more legible and will also help you add fancier UX in the future if you so choose to.
  6. yourWish.lower() == ("yes" or "y") does not do what you think it does. Your code fails if I input 'y'. This is because ("yes" or "y") is evaluated first and becomes ("yes" or "y"). What you are looking for is yourWish.lower() in ("yes", "y")
  7. Follow pep-8 style. So use snake_case for function and variable names not camelCase.
  8. Dont make you users wait needlessly. Remove sleep(1).
  9. Use proper variable names runBack must be try_again.
  10. Don't recurse unnecessarily. Functions are not jump labels. You will blow your stack.
  11. Use f-strings instead of string concatenation.
  12. Don't annoy your users by asking them to confirm simple things.
  13. Use early returns to return from a function with while(True).
  14. Use functions to build up complex behaviors.
  15. Use elif add a second condition.

Here is code with all the suggestions applied

def input_age(message, error_message):
 while True:
 try:
 age = int(input(message))
 return age
 except ValueError:
 print(error_message)
def input_desired_age(current_age):
 
 while True:
 desired_age = input_age(
 message="What is your desired age? ",
 error_message="I'm sorry, please enter your age as a numeric value."
 )
 if(desired_age > current_age):
 return desired_age
 if(desired_age < current_age):
 print("Silly, time does not move backwards. Learn how to embrace the future, not fear it.")
 elif desired_age == current_age:
 print(f"You are already {current_age}")
 print('Please input an age you wish to be in the FUTURE now...')
def display_result(desired_age, age_difference):
 print()
 print(f"To be {desired_age}, you would have to wait {age_difference} years. ")
 print()
def input_try_again():
 print('Would you like to try again?')
 response = input()
 return response.lower() in {'y', 'yes'}
# Defining Functions
def main():
 print("Hello. ")
 while True:
 current_age = input_age(
 message="Please enter your age: ",
 error_message="I'm sorry, please enter your age as a numeric value."
 )
 desired_age = input_desired_age(current_age)
 age_difference = desired_age - current_age
 display_result(current_age, age_difference)
 
 if(not input_try_again()):
 print("Goodbye")
 break
if __name__ == '__main__':
 main()
answered Dec 21, 2023 at 22:19
\$\endgroup\$
1
\$\begingroup\$

You can try this:

import time, sys
# This program will prompt you to state your age and then will proceed to
# calculate how long till __ age
# Introduction
print("Hello. ")
# Defining Functions
def main():
 while True:
 try:
 myAge = int(input("Please enter your age: "))
 except ValueError:
 print("I'm sorry, please enter your age as a numeric value.")
 continue
 break
 def secondV():
 while True:
 try:
 global desiredAge
 desiredAge = int(input())
 print(f"Do you wish to be {desiredAge}?")
 choose()
 except ValueError:
 print("Please enter a numeric value.")
 continue
 break
 def desiredFuture():
 while True:
 try:
 global desiredAge
 desiredAge = int(input())
 while True:
 if desiredAge < myAge:
 print("Silly, time does not move backwards. Learn how to embrace the future, not fear it.")
 print('Please input an age you wish to be in the FUTURE now...')
 desiredFuture()
 break
 if desiredAge == myAge:
 print(f"You are already {desiredAge}")
 break
 else:
 print(f"Do you wish to be {desiredAge}?")
 choose()
 break
 except ValueError:
 print("Please enter a numeric value.")
 continue
 break
 def choose():
 global yourWish
 yourWish = input()
 while yourWish.lower() == ("yes" or "y"):
 print("Okay... calculating...")
 time.sleep(1)
 print()
 print(f"To be {desiredAge} you would have to wait {desiredAge - myAge} years.")
 print()
 reDo()
 break
 else:
 print("Erm... please input your desired age now:")
 secondV()
 def reDo():
 print('Would you like to try again?')
 runBack = input()
 while True:
 if runBack.lower() in {'y', 'yes'}:
 print()
 main()
 else:
 print("Okay... Goodbye!")
 sys.exit("goodbye")
 break
 print(f"You are {myAge}.")
 print("What is your desired age? ")
 desiredFuture()
 choose()
 print()
main()

Use f strings instead of + it's more convenient.

And in the try except, you can just do break at the end, not put it in else. And it doesn't exit, so you can import sys and use sys.exit()

And do import time at the first line.

answered Dec 15, 2020 at 6:49
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.