sum of two number using def function in python [duplicate] - python

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 6 years ago.
feed function using raw_input of sys.argv for sum of two number goes just showing in list
def sum_double(a, b):
sum = a+b
if a == b:
sum = sum*2
print sum
return sum
else :
print sum
return sum
sum_double(a = raw_input("a"),b = raw_input("b"))
if we feed input are 1 and 2 then it will showing 12 instead of 3

raw_input returns a string and not a number. With string inputs, + simply concatenates the two strings together.
'1' + '2'
# '12'
If you want to perform numeric operations (such as addition), you need to first convert the output of raw_input to a number using int (for integers) or float (for floating point numbers).
sum_double(a = int(raw_input("a")),b = int(raw_input("b")))

raw_input returns a string ('1' and '2'). Summing them gives you '12'.
In order to sum numbers, not strings, convert the strings to numbers:
sum_double(a = int(raw_input("a")),b = int(raw_input("b")))

Related

How to convert string numbers to list? [duplicate]

This question already has answers here:
How do I parse a string to a float or int?
(32 answers)
Closed 3 years ago.
I have a string of numbers like this
i = '584,569.2,11515,632'
want to convert it to list of number like this.
[584,569.2,11515,632]
You can do it like this:
i = '584,569.2,11515,632'
numbers = list(map(float, i.split(',')))
print(numbers)
Output:
[584.0, 569.2, 11515.0, 632.0]
Also, as Chris A pointed out, if the distinction between int and float is important, you can use is_integer():
numbers = [int(x) if x.is_integer() else x for x in map(float, i.split(','))]
Output:
[584, 569.2, 11515, 632]

Python: string of arguments to arguments [duplicate]

This question already has answers here:
Pass a list to a function to act as multiple arguments [duplicate]
(3 answers)
Convert a string of numbers to a list of integers. Python
(1 answer)
Closed 3 years ago.
In Python I have a string that looks like this:
str = '1,2,3,4'
I have a method that takes four arguments:
def i_take_four_arguments(a, b, c, d):
return a + b + c + d
What do I have to do to string to allow it to be sent to the method?
If you want to perform arithmetic operation, following is one way. The idea is to convert your split string values to integers and then pass them to the function. The * here unpacks the generator into 4 values which are taken by a, b, c and d respectively.
A word of caution: Don't use in-built function names as variables. In your case, it means don't use str
string = '1,2,3,4'
def i_take_four_arguments(a, b, c, d):
return a + b + c + d
i_take_four_arguments(*map(int, string.split(',')))
# 10
str = '1,2,3,4'
list_ints = [int(x) for x in str.split(',')]
This will give you a list of integers, which can be added, pass them to your function

Reverse digits of an integer in Python [duplicate]

This question already has answers here:
Using Python, reverse an integer, and tell if palindrome
(14 answers)
Closed 4 years ago.
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
I am trying to solve the reversing int problem, but following solution failed with the following input.
Input:
1534236469
Output:
9646324351
Expected:
0
In my solution, I am checking whether or not given int is bigger than max or min value, and then checking whether or not it is negative.
My solution
import sys
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x <sys.maxsize-1 or x > -sys.minsize:
if str(x)[0] == '-':
list_mod = list(str(x))
list_mod.pop(0)
list_mod.append('-')
list_mod.reverse()
join_list = ''.join(list_mod[:])
return int(join_list)
else:
return int(str(x)[::-1])
else:
return 0
Try converting the int to string, then reverse and then convert it to int.
Ex:
a = 1534236469
print(int(str(a)[::-1]))
Output:
9646324351
To handle the negative number:
if str(a).startswith("-"):
a = a[1:]
print("-{0}".format(int(str(a)[::-1])))
else:
print(int(str(a)[::-1]))

How to check if result is integer in Python? [duplicate]

This question already has an answer here:
How to check if a numeric value is an integer?
(1 answer)
Closed 7 years ago.
I have simple task to count number, for example:
a = 7
b = 9
result = 0
for _ in (0:100):
result = a / b
b += 1
How I can stop the for loop when result is an integer?
Checking if method is_integer() wasn't meet my expectations.
I have to use Python 2.6
Use % 1. Modular arithmetic returns the remainder, so if you try to divide by 1 and the remainder is 0, it must be an integer.
if result % 1 == 0:
print "result is an integer!"
OR use the method mentioned in this post or this post:
if result.is_integer():
As mentioned in the comments, you can use:
while result % 1 != 0:
to make the loop repeat until you get an integer.
If you're using python 2.6 you could use:
isinstance(result, (int, long))
to check if your result is an integer.
You could use the type method:
if type(a/b) == int:
break
You could also use the while loop approach as suggested by other answers:
while type(a/b) != int:
# your code

Need help to understand code in python [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
first = int(input('first int: '))
second = int (input('second int: '))
result =0
if first and second:
result =1
elif not first:
result =2
elif first or second:
result=3
else:
result=4
print(result)
when I enter 1 and 0, the result is 3. I would appreciate if anyone could add some explanation.
You are using or- it means the statement will return True when it first finds True.
When you say 5 or 9, both 5 and 9 represent truism (as does any non-zero value). So it returns the first - 5 in this case. When you say 9 or 5, it returns 9.
EDIT: k = 1 or 0 would evaluate to True since 1 represents truism. Thus, as per your code, result is 3
In many program languages, the boolean operations only evaluate their second argument if needed for their outcome. These called short-circuit operator. And in python, according the docs, it returns:
x or y : if x is false, then y, else x
x and y : if x is false, then x, else y

Categories

Resources