-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsample_calculation_with_break.py
More file actions
50 lines (41 loc) · 1.35 KB
/
sample_calculation_with_break.py
File metadata and controls
50 lines (41 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
def calculator():
print("Welcome to the sample calculator!")
numbers = []
# Step 1: Collect numbers
while True:
user_input = input("Enter a number (or type 'done' to finish): ").strip().lower()
if user_input == "done":
print ("you finished entering your numbers!!")
break
try:
number = float(user_input)
numbers.append(number)
except ValueError:
print("Invalid input. Please enter a number or 'done'.")
# Step 2: Ensure at least two numbers
if len(numbers) < 2:
print("You need at least two numbers to perform calculations.")
return
# Step 3: Ask for operation
sign = input("Enter a calculation sign (+, -, *, /): ").strip()
if sign not in ['+', '-', '*', '/']:
print("Invalid operation sign.")
return
# Step 4: Perform calculation
result = numbers[0]
for num in numbers[1:]:
if sign == '+':
result += num
elif sign == '-':
result -= num
elif sign == '*':
result *= num
elif sign == '/':
if num == 0:
print("Error: Cannot divide by zero.")
return
result /= num
# Step 5: Show result
print(f"The result of the calculation is: {result}")
# Run calculator
calculator()