#This part of the code will only get numbers from user
while True:
#Using while True will allow me to loop and renter if user input is wrong. While True will go above Try Catch
try:
# Using try: and except: will allow to end the program without crash however then need to be indented
# Try goes before the def name
def getNumbers():
num1=int(input("Enter 1st number: "))
num2=int(input("Enter 2nd number: "))
getNumbers()
break# the while will stop when both values are numbers
except:
print("Incorrect input detected, try again")
#This part of the code will add the 2 numbers
def addNums():
What do I put here so that I can use num1+num2
addNums()
def subNums():
What do I put here so that I can use num1-num2
addNums()
I wrote a Calculator program but over there I declared those num1 and num2 as global variables in side getNumbers def. Someone mentioned that is not a good/ideal way which is why I wanted to try this approach.
Thanks in advance.
In order to use global variables inside of a function, use the global keyword:
x = 1
y = 2
def add() :
global x, y
return x + y
EDIT
Actually, your "question" is really unclear. You say you are not willing to use global-variables in your code, but you wrote:
def addNums():
What do I put here so that I can use num1+num2
addNums()
The problem is that num1 and num2 don't exist at this place. If you want to use them, then they are global variables.
As far as I understand, what you want is just a function:
def addNums(x, y):
return x+y
addNums(num1, num2)
I don't know what's your doubt, it's not clear in your post.
Why can't you do in this way (just for e.g, you can make it better):--
Blockquote
def subNums(a, b):
return (a - b)
def addNums(a, b):
return (a + b)
def getNumbers():
while True:
try:
num1 = int(input("Enter 1st number: "))
num2 = int(input("Enter 2nd number: "))
return (num1, num2)
except:
print("Incorrect input detected, try again")
a, b = getNumbers()
print ("sum of %d and %d : %d" % (a, b, addNums(a, b)))
print ("difference of %d and %d : %d" % (a, b, subNums(a, b)))
Hope this will help.
Related
I'm super new to Python and programming in general. I am following an example off of youtube on how to make a simple calculator but I wanted to add my ideas and functionalities. More or less I want to make it very versatile.
This is the part that is not working out for me. I don't know how to make it work using the two methods I created
def main():
while True:
Num1()
num1 = int.num1()
Num2()
num2 = int.num2()
# Executing the specified calculations with the 'Operation' function (row 13)
Operation(num1, num2)
# --> followed by another nested while asking if the user wants to make another calculation
I want the app to read everywhere that if the user types "exit" it will exit, even if it's asking for a number so I created 2 methods to do so because it wasn't working dealing with the loops and user input directly from main()
def Num1():
while True:
num1 = input("What is the first number? ")
if num1.isdigit():
break
elif num1 == 'exit':
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
continue
def Num2():
while True:
num2 = input("What is the second number? ")
if num2.isdigit():
break
elif num2 == "exit":
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
continue
The problem is that I get this error and I get it but I just don't know how to go about it.
Traceback (most recent call last):
File "C:/Users/Albert/PycharmProjects/HelloWorld - First Py'
Apps/SimpleCalculator.py", line 131, in <module>
main()
File "C:/Users/Albert/PycharmProjects/HelloWorld - First Py'
Apps/SimpleCalculator.py", line 109, in main
Operation(num1, num2)
NameError: name 'num1' is not defined
I see few general errors in your code:
You call function Num1() for entering num1, but num1 is the local
variable. So you can see and use it only in Num1() function. Same
with num2. So, I suggest to use Num1 and Num2 but to return the num1
and num2.
I recommend to use 1 function, there is no need to use 2.
Looks like with num1 = int.num1() you want to convert num1() to int. This is wrong. Correct will be something like num1 = int(num1).
This will convert num1 from string to int and save it to num1. But
better to use different names for strings and int's: num1 =
int(num1_str). And when you use bracket num1(), this means you call
num1 function to complete. But num1 is not a function, so it's not
callable.
You use converting strings to int two times. In programming, when you see two code, which is just copy/paste, you better to make a
function for it. Here we have the function, so just insert
converting to int in function.
Don't forget about indentation. This is the most important thing in Python. In other languages, you use something like {} to define
the beginning and the end of some logical block. But in Python, it
all depends on indentation.
So, using this, it can look like this way:
def main():
while True:
# just call NumEntering - one general function for entering numbers,
# and give to it attribute - message for user.
num1 = int(NumEntering("What is the first number? "))
num2 = int(NumEntering("What is the second number? "))
# Executing the specified calculations with the 'Operation' function (row 13)
Operation(num1, num2)
And the function:
def NumEntering(message): # message - this what function get from outer function.
while True:
num_str = input(message) # show given message
if num_str.isdigit():
return int(num_str) # convert to int and return to outer function
elif num_str == 'exit':
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
continue
case sensitivity, you defined Num1() & Num2() not num1() & num2()
There's plenty wrong with your code.
DRY Do not Repeat Yourself. There's no need to have two functions when they do the same thing. Delete Num2 in its entirety. It's useless.
Num1 isn't returning a value. We want the function to ask the user for a number (which it does), exit if the user inputs "exit" (also done) and return the number entered by the user (not done).
Function names start with a lowercase letter and are descriptive. Num1 does neither, so let's change it to ask_number.
All the problems identified above can be fixed by replacing Num1 and Num2 with the following ask_number function.
def ask_number():
while True:
num = input("What is the first number? ")
if num.isdigit():
return int(num) #This line fixes problem 2
elif num == 'exit':
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
Your main method isn't assigning the return value of your function into the variables.
Fix it by replacing your old code
Num1()
num1 = int.num1()
Num2()
num2 = int.num2()
with
num1 = ask_number()
num2 = ask_number()
We're calling the ask_number function twice and assigning its return value to num1 and num2.
The problem was that Num1() and Num2() asked the questions, but didn't do anything with them. Also, the num1 and num2 that were defined were variables local to the function, so you couldn't access them from the main() function. You should have added "return numX" instead of break and assigned Num1() to num1, which allows you to capture the user's input in a variable accessible by the main() function.
This is what your code should have looked like:
import time
def Num1():
while True:
num1=input("What is the first number? ")
if num1.isdigit():
return int(num1)
elif num1 == 'exit':
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
def Num2():
while True:
num2=input("What is the first number? ")
if num2.isdigit():
return int(num2)
elif num2 == 'exit':
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
def Operation(num_1, num_2):
# code for Operation function
pass
def main():
while True:
num1=Num1()
num2=Num2()
Operation(num1, num2)
if __name__=="__main__": main()
Disclaimer: I'd ask for some clarification, but I don't have the SO privileges yet.
Can you make sure your indentation is correct when you're running the program? For instance, your while loops shouldn't be on the same indentation level as your function definitions.
Also, are you functions all in this file SimpleCalculator.py? If so, you will need to have an additional line to call your methods, since right now they're only being declared.
if __name__ == '__main__':
# And the following line will call your main function which you defined previously
main()
Better yet, just remove your main() function and replace it with the more Pythonic syntax:
if __name__ == '__main__':
while True:
Num1()
Num2()
Also, since you're calling Num1() and Num2() and they're handling the inputs, you don't need to set num1 = int.num1() or num = int.num2() (which both give me errors) or the like. If you want to have the values to be returned to the main method for handling, you'll need to do return num1 when you check if num1.isdigit():, and in your main method set firstNumberInput = Num1()
Hope this helps!
It may just be that you have posted your code with omissions but there are several points to address.
The functions Num1 and Num2 do not return anything. Although the value num1 is assigned within the function, it is not accessible outside that function's scope.
int does not have a method "num1" so calling int.num1() should be replaced with int(num1())
Creating 2 nearly identical functions creates a lot more work for yourself and makes the code hard to change, you could create a more general function.
def getnum():
while True:
mynum = input("What is the first number? ")
if mynum.isdigit():
break
elif mynum == 'exit':
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
return mynum
def main():
while True:
num1 = int(getnum())
num2 = int(getnum())
When i run through my calculator, it gives the following results;
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4):3
Enter first number: 1
Enter second number: 5
Invalid! Input
Can anyone explain to me why it is responding with my else if statement, i'v checked the code many times, plus i have copied paste the code directly, as is, after much frustration, yet it yields the same result?
# A simple calculator that can add, subtract, multiply and divide.
# define functions
def add(x, y):
"""This function adds two numbers"""
return x + y
def subtract(x, y):
"""This function subtracts two numbers"""
return x - y
def multiply(x, y):
"""This function multiplies two numbers"""
return x * y
def divide(x, y):
"""This function divides two numbers"""
return x / y
# Take input from the user
print ("Select operation.")
print ("1.Add")
print ("2.Subtract")
print ("3.Multiply")
print ("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid! Input")
You're using Python 2, where input() evaluates what is entered; so when you enter 2, for instance, choice contains the int 2. Try entering '2' into your current code (including the quotes). It'll act as you expect entering 2 to act.
You should use raw_input() on Python 2 and input() on Python 3. If you want your code to be compatible with both, you can use the following code, after which you can always just use input():
try:
input = raw_input # Python 2
except NameError: # We're on Python 3
pass # Do nothing
You can also use the six package, which does this and many other Python 2/3 compatibility things.
In Python 3 input() does what raw_input() does in Python 2, and Python 2's input() is gone.
So I am trying to teach myself python and I am having some problems accomplishing this task. I am trying to read in two integers from the keyboard, but the problem is that they can either be read in on the same line or on two different lines.
Example Inputs:
23 45
or
23
45
Each number should go to its own variable.
Im pretty sure I should make use of the strip/split functions, but what else am I missing? I just really dont know how to go about this... Thanks.
Here is what Im working with, but obviously this version takes the numbers one on each line.
def main():
num1 = int(input())
num2 = int(input())
numSum = num1 + num2
numProduct = num1 * num2
print("sum = ",numSum)
print("product = ",numProduct)
main()
the input terminates on new line (more percisely, the sys.stdin flushes on new line), so you get the entire line. To split it use:
inputs = input("Enter something").split() # read input and split it
print inputs
applying to your code, it would look like this:
# helper function to keep the code DRY
def get_numbers(message):
try:
# this is called list comprehension
return [int(x) for x in input(message).split()]
except:
# input can produce errors such as casting non-ints
print("Error while reading numbers")
return []
def main():
# 1: create the list - wait for at least two numbers
nums = []
while len(nums) < 2:
nums.extend(get_numbers("Enter numbers please: "))
# only keep two first numbers, this is called slicing
nums = nums[:2]
# summarize using the built-in standard 'sum' function
numSum = sum(nums)
numProduct = nums[0] * nums[1]
print("sum = ",numSum)
print("product = ",numProduct)
main()
Notes on what's used here:
You can use list comprehension to construct lists from iterable objects.
You can use sum from the standard library functions to summarize lists.
You can slice lists if you only want a part of the list.
Here I have modified your code.
def main():
num1 = int(input("Enter first number : "))
num2 = int(input("\nEnter second number : "))
if(num1<=0 or num2<=0):
print("Enter valid number")
else:
numSum = num1 + num2
numProduct = num1 * num2
print("sum of the given numbers is = ",numSum)
print("product of the given numbers is = ",numProduct)
main()
If you enter invalid number it prints message Enter valid number.
How do I add numbers in between two numbers the user inputted in Python 2.7. So a person would input 75 and 80 and I want my program to add the numbers in between those two numbers. I am very new to programming and python so any help would be awesome!
This example excludes 75 and 80. If you need to include them replace with print sum(range(n1,n2+1))
n1=input('Enter first number ')
n2=input('Enter second number ')
print sum(range(min(n1,n2)+1,max(n1,n2)))
#DSM is right!
n1=input('Enter first number ')
n2=input('Enter second number ')
print (n2-n1+1)*(n2+n1)/2
to capture user input use number1 = raw_input('Input number'). From there I'm not exactly sure what you mean from adding numbers between the two? If you want 76+77+78+79 in that example
number1 = raw_input('Input number')
number2 = raw_input('Second number')
result = 0
for n in range(int(number1)+1, int(number2)):
result+=n
print result
Here's a quick sample that should handle a few different situations. Didn't go that in-depth since I don't know the scope of the situation. Realistically you should do some form of type-checking and loop until valid input is entered. However this should get you started:
def sumNums(a, b):
total = 0
if a < b:
total = sum(range(a+1, b))
elif b < a:
total = sum(range(b+1, a))
return total
num1 = int(raw_input("First Number: "))
num2 = int(raw_input("Second Number: "))
print sumNums(num1, num2)
However I'm sure there's a more comprehensive way using lists and sum() but it seems like you only need a basic working example.
easy you just go
def add(x,y):
if True:
return add(x, y)
else:
return None
add([1,2,3,4][0], [1,2,3,4][2])
I am trying to get my function to take two arguments, and return their sum. Am I going about this the right way? This is what I have so far:
def my_sum(a, b):
sum = a + b
def main():
a = input(int("enter a number: ", a)
b = input(int("enter a number: ", b)
sum = a + b
return sum
print(" result: ", sum)
main()
So it looks good, but the main problem is that you aren't actually calling your function :) Once you get your two numbers, you can then make the call to your function (which you have properly set up):
def main():
# When you assign variables here, make sure you are putting the int outside
# You also don't need to reference the variable twice
a = int(input("enter a number: "))
b = int(input("enter a number: "))
# Here is where your call goes (try to avoid using variable names that
# are the same as Python keywords, such as sum)
s = my_sum(a, b)
print(" result: ", s)
Now, one other thing you'll have to do is modify your function to return a value. You're already almost there - just add a return (note that since you are just returning the sum of the two numbers, you don't have to assign it to a variable):
def my_sum(a, b):
return a + b
This now means that when you run s = my_sum(a, b), your function will return the sum of those two numbers and put them into s, which you can then print as you are doing.
One other minor thing - when you use the setup you are (with def main(), etc.), you usually want to call it like this:
if __name__ == '__main__':
main()
At this stage, don't worry too much about what it means, but it is a good habit to get into once you start getting into fun stuff like modules, etc. :)
You Have written Wrong coding Style
If you want to do some by using sum method than do this
def my_sum(a, b):
sum = a + b
return sum
def main():
a = int(raw_input("enter a number: "))
b = int(raw_input("enter a number: "))
sum = my_sum(a,b)
print" result: ", sum
main()
I hope this will work as per your requirement.
Regards,
Anil
I am not sure of the purpose of the first function you have defined there (my_sum). However, there are a few things wrong in main as well. The return function always exits the function it is in, and zooms out to a higher level scope. This is very similar to break, except that it returns a value as well. Also, your syntax when you ask for user input is incorrect. It should be:
def main():
a = int(raw_input("Enter a number: "))
b = int(raw_input("Enter a number: "))
return "Result" + (a+b)
main()
Also, if you wanted my_sum to automatically return the sum, you should use return or print:
def my_sum(a, b):
return a + b
doing a print function after return sum won't work because when returning a return value, the execution will exit the scope, the orders should be reversed.
your input function is not implemented correctly.
The correct code should be:
def main():
a = input("enter a number: ")
b = input("enter a number: ")
sum = a + b
print(" result: ", sum)
return sum