Repository navigation
Expand file tree
/
Copy pathquestion_2.py
More file actions
90 lines (83 loc) · 2.39 KB
/
Copy pathquestion_2.py
File metadata and controls
90 lines (83 loc) · 2.39 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# Question 2: Simple Calculator Functions (Lesson 4 - Functions)
# Create a calculator using functions for different operations.
# Requirements:
# Create these functions:
# add(a, b) - returns the sum of two numbers
# subtract(a, b) - returns the difference of two numbers
# multiply(a, b) - returns the product of two numbers
# divide(a, b) - returns the quotient, handles division by zero
# Create a main function that:
# Gets two numbers from the user
# Asks which operation to perform
# Calls the appropriate function
# Displays the result
# Create file: question2.py
# Example Output:
# Enter first number: 15
# Enter second number: 3
# Choose operation:
# 1. Add
# 2. Subtract
# 3. Multiply
# 4. Divide
# Enter choice (1-4): 4
# 15.0 ÷ 3.0 = 5.0
# Enter first number: 10
# Enter second number: 0
# Choose operation:
# 1. Add
# 2. Subtract
# 3. Multiply
# 4. Divide
# Enter choice (1-4): 4
# Error: Cannot divide by zero!
#get the first and second input numbers
def input_value():
first = input_validation("Enter first number: ")
if first == None:
return
second = input_validation("Enter second number: ")
if second == None:
return
return first, second
#Validate input to be float
def input_validation(display_str):
while True:
try:
input_str = input(display_str).strip()
input_value = float(input_str)
break
except ValueError:
print("Please enter a valide number")
continue
except KeyboardInterrupt:
print("\nExiting...")
return None
return input_value
#main program
num1, num2 = input_value()
print("Choose operation: ")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Devide")
input_value = input_validation("Enter choice (1-4): ")
output_str = ""
if input_value == 1:
result = num1 + num2
output_str = str(num1) + " +" + str(num2) +" = " + str(result)
elif input_value == 2:
result = num1 - num2
output_str = str(num1) + "- " + str(num2) +" = " + str(result)
elif input_value == 3:
result = num1 * num2
output_str = str(num1) + " * " + str(num2) +" = " + str(result)
elif input_value == 4:
if num2 == 0:
output_str = "Error: Cannot divide by zero"
else:
result = num1/num2
output_str = str(num1) + " / " + str(num2) +" = " + str(result)
else:
output_str = "Invalid Value"
print("\n" + output_str + "\n")