Can someone look over my code and clean it up?
I am trying to make a calculator with multiple inputs to add up. This is a snippet of the code that just needs to be cleaned up and shortened and I am relatively new to python so if anyone wants to clean this up thank you.
#functions
def x():
#needed for the the loop later
x.x = int(input("Type how many numbers you would like to add up: "))
x.xCON = int(input("Please confirm by typing the same number: "))
#welcome to the code
print("Would you like to add up lots of numbers?")
print("If so you came to the right place")
#neaten up
print("________________________________________________")
#run function
x()
#cheack if the numbers are the same if not they have to retype them
if x.x == x.xCON:
#neaten up
print("____________________________________")
#setting veriables for the loops and the list of the numbers
i = 0
nums = []
#while i is not = to the input number(x.x) do the loop
while i != x.x:
#asks for the numbers to be added up
INTnum = float(input("Write the numbers to be added up: "))
#adds the numbers to the list
nums.append(INTnum)
#updates the veriable cheacking how many times the code has been ran
i+=1
#creating new veriables for the next loop
index = 0
ans = 0
#while indxex is not = to the amount to numbers in the list run the code
while index != len(nums):
#veriable nums is now set as the lists index of the veriable index
num = nums[index]
#the ans veriable is eqal to itself + the number that was recorded from the idex
ans = ans + num
#moves the number along one everytime the code is run
index+=1
#gives the rueult of the sum
print("\nThe sum of the numbers is", ans)
#neaten up
print("____________________________________________________")
#what happens if the numbers are not the same sending the bacn to the x() function
else:
print("The numbers were not the same.")
x()
#end of the code
print("\nThank you for using the calculator")
-
1\$\begingroup\$ Welcome to the Code Review site, the current title applies to every question on this site, and makes no attempt to explain what the code does. Please read How do I ask a good question for some advice on how to title the question. \$\endgroup\$pacmaninbw– pacmaninbw ♦2020年10月30日 14:07:19 +00:00Commented Oct 30, 2020 at 14:07
1 Answer 1
Your x
function has a few notable things:
x
is a very poor name. It doesn't give any hints as to what the function is supposed to do. The name of your function should let the reader of your code know what its purpose is. Something likeget_user_input
would be much better.You're associating data with the function object itself; essentially creating static variables. This is not a good idea though. This means that this function can only be called once before you overwrite the previous entered data. In your case here, that may not be a big deal, but it is not a good habit to get into. This will significantly complicate code later when you have functions that you're calling in multiple places in your code. Return the results instead.
You're having the user enter a confirmation, but then you're checking that they match outside of the function. Just check inside the function and loop until they match.
After fixing up those points, I have:
def get_user_input():
while True:
n_numbers = int(input("Type how many numbers you would like to add up: "))
confirmation = int(input("Please confirm by typing the same number: "))
if n_numbers == confirmation:
return n_numbers
else:
print("The numbers were not the same.")
They you can get rid of the else
case at the bottom of your code. You'd then use this function like:
n_numbers = get_user_input()
And use n_numbers
instead of x.x
.
You don't do any error handling anywhere. I find it odd that in your code, you require confirmation to ensure the user didn't typo the number they entered, but you aren't protecting against them typing in nonsensical input (like hello
). If the user types a non-number, you'll get a ValueError
that will crash your program. You may want to consider wrapping calls to int
and float
in a try
/except
to ensure that your program won't crash.
This loop:
nums = []
while i != n_numbers:
INTnum = float(input("Write the numbers to be added up: "))
nums.append(INTnum)
i+=1
Can be cleaned up by using a range
:
nums = []
for _ in range(n_numbers):
INTnum = float(input("Write the numbers to be added up: "))
nums.append(INTnum)
Now you don't need to manually handle i
. This can be further cleaned up by using a list comprehension:
nums = [float(input("Write the numbers to be added up: "))
for _ in range(n_numbers)]
Whenever you find yourself manually handling loop indices like you were with i
, there's likely a better way that handles the looping for you.
The same can be said for this loop:
while index != len(nums):
num = nums[index]
ans = ans + num
index+=1
Note how you never need index
except to access nums
. Just loop over nums
directly:
for num in nums:
ans += num # The same as "ans = ans + num"
If you need to loop over a list, just loop over the list directly.
Really though, that's just sum
:
ans = sum(nums)
Your comments aren't a good use of commenting. A lot of them are simply restating what the code itself says:
#the ans veriable is eqal to itself + the number that was recorded from the idex
ans = ans + num
. . .
#creating new veriables for the next loop
index = 0
If something is already self-explanatory, don't simply restate that in a comment. Your code reads like you're under the impression that every line of code requires a comment, but this isn't true. Ideally, your code itself should be all the explanation the reader needs, but if more explanation is required, note why the code is unreadable or why it's behaving as it is. When half your code is comments that just restate the code, it detracts from the important part: the code.