Python - sum of two numbers program error [duplicate] - python

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 months ago.
I was just getting into Python programming. I wrote a simple program to calculate sum of two user-input numbers:
a,b = input("enter first number"), input("enter second number")
print("sum of given numbers is ", (a+b))
Now if I enter the numbers as 23 and 52, what showed in the output is:
sum of given numbers is 23 52
What is wrong with my code?

input() in Python 3 returns a string; you need to convert the input values to integers with int() before you can add them:
a,b = int(input("enter first number")), int(input("enter second number"))
(You may want to wrap this in a try:/except ValueError: for nicer response when the user doesn't enter an integer.

instead of (a+b), use (int(a) + int(b))

I think it will be better if you use a try/except block, since you're trying to convert strings to integers
try:
a,b = int(input("enter first number")), int(input("enter second number"))
print("sum of given numbers is ", (a+b))
except ValueError as err:
print("You did not enter numbers")

By default python takes the input as string. So instead of adding both the numbers string concatenation is occurring in your code. So you should explicitly convert it into integer using the int() method.
Here is a sample code
a,b=int(input("Enter the first number: ")),int(input("Enter the second number: "))
print("Sum of the numbers is ", a + b)
For more information check this link
https://codingwithwakil.blogspot.com/2021/05/python-program-to-add-two-numbers-by.html

Related

Why i am unable to use (or) operator on the code given below in python 3.7 [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 months ago.
try:
x = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = "))
y = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = "))
except:
print("Error,Invalid Input")
I know I am wrong, I was just wondering why I am unable to use it. As I am not getting any errors. When I try to put float value inside the input it returns me to my second case, which is Error, Invalid Input. I am using (or) operator so that I can validate integer and float values in one place. (or) the operator should execute the code when one of the conditions is true right? But why cannot we use Or operator with an integer? The code will work if you remove int from the code.
While you can use the or operator to select the the first truthy value between to values (or the latter, if the first one is falsy), it doesn't work in this case because trying to convert into int a string which represents a float value doesn't return a falsy value, it raises an Exception, which is why you go into your except clause
A logically sound way to write your code would be
x = input("Enter Your Number first = ")
try:
num = int(x)
except:
num = float(x)
Not the best way to do it, but it works
Another example:
x = 10/0 or 3 #ZeroDivisionError
x = 0/10 or 3 # x is 3 because 0 is a falsy value
Generally, we use or case to check some conditions. For example if x<3 or x>5: This if block works of both cases. However, in your situation you are trying to get some input from user and using x = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = ")). So, when I enter a value it gets number as string and when you write int(input()) it convert it to integer and assign to x. So OR is not logically suitable for here. What will computer work it this situation? What you want to achieve? If you want take argument as float just write float(input()) because when you enter integer it can be taken as float also.
try:
x = float(input("Enter Your Number first = ")) or int(input("Enter Your Number first = "))
y = float(input("Enter Your Number first = ")) or int(input("Enter Your Number first = "))
except:
print("Error,Invalid Input")
operators = input("Choose operations (*, -, +, /)")
if operators == "*":
print(float(x*y)) or print(int(x*y))
elif operators == "-":
print(float(x-y)) or print(int(x-y))
elif operators == "+":
print(float(x+y)) or print(int(x+y))
elif operators == "/":
print(float(x/y)) or print(int(x/y))
well, i just figured it out,

Create a list of 10 numbers that do not overlap each other and add them up

I'm supposed to write a code that asks users for 10 numbers, create a list with that and then sum them all up. I'm currently able to do that. However, I don't know how to check that the numbers do not overlap each other. If they do, the number is not supposed to be added onto the list.
So I am able to get the program to run such that it asks for a number for 10 times. However, after that, it appears to have a syntax error when producing the sum.
numberList = []
for i in range (0,10):
number= int(input("Please enter a number: "))
numberList.append(number)
total = sum(numberList)
total = sum(numberList)
TypeError: 'int' object is not callable
You can use if condition with "not in", it will only add the new numbers in the list. I am not getting any error doing sum operation. May be there is sum indentation issue please check that.
numberList = []
for i in range (0,10):
number= int(input("Please enter a number: "))
if number not in numberList:
numberList.append(number)
print "List formed: %s" %numberList
total = sum(numberList)
print "Sum of all elements in list: %d" %total
Console:
Please enter a number: 1
Please enter a number: 2
Please enter a number: 3
Please enter a number: 4
Please enter a number: 5
Please enter a number: 1
Please enter a number: 2
Please enter a number: 3
Please enter a number: 4
Please enter a number: 5
List formed: [1, 2, 3, 4, 5]
Sum of all elements in list: 15
Removing duplicates from a python list can be done in a few different ways. The most common for lists that need to keep their order is to convert into an OrderedDict because dictionary keys must be unique it will not create additional keys for duplicate elements.
Because we are finding the sum of numbers, order does not matter so we can use a built-in method set() which converts any iterable in to a set (By nature, must have unique elements).
If you need it to be a list you can convert back to list afterwards:
numberList = list(set(numberList))
reduce, map and filter are some of the most important functions to learn in any programming language. For this use case the reduce() is perfect, it performs a rolling computation.
from functools import reduce
final_sum = reduce((lambda x, y: x + y), numberList)

I can't understand this while loop code with try/except nested in (python)

5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done" : break
print(num)
if num > largest:
largest=num
if num < smallest:
smallest=num
except:
print("Invalid input")
print("Maximum is", largest)
print("Minimum is", smallest)
desired output: my output:
Invalid input 2 ← Mismatch
Maximum is 10 4
Minimum is 2 5
maximum is 5(it prints the last input)
minimum is None
I'm a total beginner at programming and python so if the error is obvious pls break it down as much as you could..thank you so much.
The program will never reach print("Invalid input") since there is no error that could be thrown above. If you were to cast num to an integer with num = int(num) after you've checked if num == "done", then the program would catch invalid inputs like "bob"
input() returns a string, so you need to cast the input to integer with int() before comparing it as a number. Also remove your unnecessary print(num).
So change:
print(num)
to:
num = int(num)
The problem is that you are using strings, not numbers. 10 is a number, it is stored as numeric data and you can do things like compare size, add, subtract, etc. Specifically it is an integer, a number with no decimal places (computers store numbers in a lot of different ways). '10' is a string, a set of characters. Those characters happen to represent a number, but the computer doesn't know that. As far as it can tell it is just text.
What you can do to convert a string to an integer is simply num = int(num). If the number can be converted to an integer, it will be. If it can't, you will get an error. That is why the instructions tell you to use a try/catch block. It will catch this error.
Your question already explains what you want to do
If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message
The explanation of why is that you need int(num) after you check for done, to try converting a string to an integer, and catch exception that happens for non integer inputs
I suggest you remove the try except, type anything but a number and observe the behavior

How to find a specific number from a user inputed list in python [duplicate]

This question already has answers here:
Python - Count elements in list [duplicate]
(7 answers)
Closed 7 years ago.
I want the program to find the number of times a particular number occurs within a list. What am I doing wrong here?
def list1():
numInput = input("Enter numbers separated by commas: ")
numList = numInput.split(",")
numFind = int(input("Enter a number to look for: "))
count = 0
for num in numList:
if num == numFind:
count += 1
length = len(numList)
# dividing how many times the input number was entered
# by the length of the list to find the %
fraction = count / length
print("Apeared",count,"times")
print("Constitutes",fraction,"% of this data set")
list1()
numList isn't a list of numbers, it's a list of strings. Try converting to integer before comparing to numFind.
if int(num) == numFind:
Alternatively, leave numFind as a string:
numFind = input("Enter a number to look for: ")
... Although this may introduce some complications, e.g. if the user enters 1, 2, 3, 4 as their list (note the spaces) and 2 as their number, It will say "Appeared 0 time" because " 2" and "2" won't compare equal.
There are 2 issues with the code, First you are comparing int with str and the second is count / length. In Python when you divide int with int you get an int returned not a float (as expected.) so fraction = flost(count) / length would work for you , also you need to convert all the elements in the list to integers which can be done as :
numList = map(int, numInput.split(","))

Python - Write a for loop to display a given number in reverse [duplicate]

This question already has answers here:
Using Python, reverse an integer, and tell if palindrome
(14 answers)
Closed 8 years ago.
How would I have the user input a number and then have the computer spit their number out in reverse?
num = int(input("insert a number of your choice "))
for i in
That is all I have so far...
I am using 3.3.4
Here's an answer that spits out a number in reverse, instead of reversing a string, by repeatedly dividing it by 10 and getting the remainder each time:
num = int(input("Enter a number: "))
while num > 0:
num, remainder = divmod(num, 10)
print remainder,
Oh and I didn't read the requirements carefully either! It has to be a for loop. Tsk.
from math import ceil, log10
num = int(input("Enter a number: "))
for i in range(int(ceil(math.log10(num)))): # => how many digits in the number
num, remainder = divmod(num, 10)
print remainder,
You don't need to make it int and again make it str! Make it straight like this:
num = input("insert a number of your choice ")
print (num[::-1])
Or, try this using for loop:
>>> rev = ''
>>> for i in range(len(num), 0, -1):
... rev += num[i-1]
>>> print(int(rev))
Best way to loop over a python string backwards says the most efficient/recommended way would be:
>>> for c in reversed(num):
... print(c, end='')
Why make it a number? 'In reverse' implies a string. So don't cast it to int but use it as string instead and just loop over it backwards.
You've got here a variety of different answers, many of which look similar.
for i in str(num)[::-1]:
print i
This concise variation does a few things worth saying in english, namely:
Cast num to a string
reverse it (with [::-1], an example of slicing, a pythonic idiom that I recommend you befriend)
finally, loop over the resultant string (since strings are iterable, you can loop over them)
and print each character.
Almost all the answers use [::-1] to reverse the list -- as you read more code, you will see it more places. I recommend reading more about it on S.O. here.
I hate to do your problem for you since you didn't really try to actually solve it or say what you're specifically having a problem with, but:
num = str(input("..."))
output = [num[-i] for i in range(len(num))]
print(output)
output = input("Insert number of your choice: ")[::-1]
print("Your output!: %s" % output)
In python 3.x+ input is automatically a string, doing [::-1] reverses the order of the string

Categories

Resources