Python住房资格计算程序字符串转整数错误排查与修复
Fixing Type Conversion Issues in Your Housing Eligibility Program
Hey there! I see exactly what's going on here—your program is doing string concatenation instead of math because some input values aren't being converted to numeric types. Let's fix that step by step.
The Key Problems
- When you pass the
childreninput directly tochildren_age, it's still a string. Sonumber_of_children*50becomes string repetition instead of multiplication. - In the
work_hardfunction,wife_workandhusband_workare read as strings, sowife_work+husband_workconcatenates them (e.g., "1"+"1" becomes "11") before multiplying by 75, which repeats the string 75 times.
Fixed Code
def check_age(age): age = int(age) return 30 * 6 if age >= 30 else 0 def just_married(): sum_married = 0 woman_age = int(input("Please enter the wife age [we know that is not ok ask woman about she's age] : ").strip()) sum_married += check_age(woman_age) husband_age = int(input("Please enter the husband age : ").strip()) sum_married += check_age(husband_age) return sum_married def children_age(number_of_children): return number_of_children * 50 def work_hard(): print("for WIFE - Are you working part-time (0.5) or full-time (1)? : ") wife_work = float(input().strip()) print("for HUSBAND - Are you working part-time (0.5) or full-time (1)? : ") husband_work = float(input().strip()) sum_work = (wife_work + husband_work) * 75 return sum_work def main(): sum_func = 0 print("The following is a program aimed at examining eligibility conditions for participation in the tender Housing for the occupant.") sum_func += just_married() print("How many children over the age of 18 do you have? : ") children = int(input().strip()) sum_func += children_age(children) sum_func += work_hard() program_number = 599 if sum_func > program_number: print(f"you got : {sum_func} points ") else: print(f"sorry, but you need {program_number - sum_func} points to join the program. try next time.") main()
What Changed?
- Children Input Conversion: In
main(), we convert thechildreninput to an integer withint(input().strip())so multiplication works as expected. - Work Status Conversion: In
work_hard(), we convertwife_workandhusband_workto floats (since part-time is 0.5, a non-integer) withfloat(input().strip()). Now adding them gives a numeric sum instead of a concatenated string. - Minor Cleanup: Added line breaks to functions for readability, used
+=where appropriate, and swapped string concatenation in print statements for f-strings (more concise and readable).
Test Run with Your Inputs
If you run the fixed code with your original inputs:
- Wife age: 40, Husband age:50 →
check_agereturns 180 for each, total 360 - 4 children → 4*50=200
- Both working full-time (1+1)*75=150
- Total points: 360+200+150=710
- Output:
you got : 710 points
That's the correct numeric result you were expecting!
内容的提问来源于stack exchange,提问作者eidan66
相关产品推荐
相关产品推荐

