简体   繁体   English

如果使用用户定义的函数输入数字,如何添加数字

[英]How to add numbers if numbers are input using a user-defined function

Is it possible to add integers if they are inputted using a user-defined function?如果使用用户定义的函数输入整数,是否可以添加整数? Here is my sample code below下面是我的示例代码

def first_num(num1):
    num1 = int(input("Enter first number: "))
    return 

def sec_num(num2):
    num2 = int(input("Enter second number: "))
    return 

print("ARITHMETIC CALCULATOR")
print("----------------")
print("[1] - Addition")
print("[2] - Subtraction")
print("[3] - Multiplication")
print("[4] - Division")
print("----------------")

choice = int(input("Enter your choice: "))
first_num(num1)
sec_num(num2)

if choice == '1':
    sum = first_num(num1) + sec_num(num2)
    print("The sum is: ")

I just wanted to ask if it is possible, and if so, how?我只是想问一下是否可以,如果可以,如何?

Your function needs to return the number you asked for, and you need to assign the result to a variable at the time that you call it.您的函数需要return您要求的数字,并且您需要在调用它时将结果分配给一个变量。 Since you can call a function any number of times, you don't need to define a unique function for each number.由于您可以多次调用函数,因此无需为每个数字定义唯一的函数。

def get_num(label):
    return int(input(f"Enter {label} number: "))


print("ARITHMETIC CALCULATOR")
print("----------------")
print("[1] - Addition")
print("[2] - Subtraction")
print("[3] - Multiplication")
print("[4] - Division")
print("----------------")

choice = input("Enter your choice: ")
num1 = get_num("first")
num2 = get_num("second")

if choice == '1':
    print(f"The sum is: {num1 + num2}")
ARITHMETIC CALCULATOR
----------------
[1] - Addition
[2] - Subtraction
[3] - Multiplication
[4] - Division
----------------
Enter your choice: 1
Enter first number: 31
Enter second number: 11
The sum is: 42

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM