Python 3.6编程需求:编写命令行程序收集两个完整地址输入
Python 3.6 Program to Collect and Print Two Full Addresses
Hey there, here's a clean, straightforward implementation that checks all your boxes. We'll use a helper function to avoid repeating code for both addresses, and make sure street numbers and zip codes are stored as numerical types:
def get_address(address_number): """Collects and returns a single address as a dictionary""" print(f"\n--- Enter Address {address_number} ---") name = input("Full Name: ") # Convert street number to integer street_number = int(input("Street Number: ")) street_name = input("Street Name: ") city = input("City: ") state = input("State: ") # Convert zip code to integer zip_code = int(input("ZIP Code: ")) # Return address as a dictionary for easy storage and access return { "name": name, "street_number": street_number, "street_name": street_name, "city": city, "state": state, "zip_code": zip_code } # Collect both addresses address1 = get_address(1) address2 = get_address(2) # Print the stored addresses in a readable format print("\n--- Stored Addresses ---") print(f"Address 1:\n{address1['name']}\n{address1['street_number']} {address1['street_name']}\n{address1['city']}, {address1['state']} {address1['zip_code']}") print("\nAddress 2:\n{name}\n{street_number} {street_name}\n{city}, {state} {zip_code}".format(**address2))
Key Details:
- Helper Function:
get_address()handles collecting a single address, so we don't write duplicate code for the two entries. It returns a dictionary, which is a clean way to group related address data. - Numerical Types: We use
int()to convert the street number and zip code input from strings to integers, fulfilling the requirement to store them as numerical types. - Readable Output: The printed addresses are formatted like standard mailing addresses for clarity.
- Python 3.6 Compatibility: All syntax used here works perfectly in Python 3.6 (f-strings are supported in 3.6+, which we use for some print statements; the
format()method is also included as an alternative if you prefer it).
Optional Robustness Add-On:
If you want to handle cases where a user might enter non-numeric values for street number or zip code, you could add a try-except block to catch ValueError and prompt the user again. For example:
while True: try: street_number = int(input("Street Number: ")) break except ValueError: print("Please enter a valid number for street number.")
This would make the program more resilient to user input errors, but it's optional based on your needs.
内容的提问来源于stack exchange,提问作者program123
相关产品推荐
相关产品推荐

