I want to print the double of a number.
If I input 5, why does this print 55:
number = input("Input number \n")
double = number * 2
print(double)
and why does this print 10, as expected:
number = int(input("Input number \n"))
double = number * 2
print(double)
In the second case you convert the input to an integer, which can be multiplied by two to get the expected result. In the first case, you multiply a string (instead of an integer) by two, which results in the string twice, hence '55'.
There is a difference between python2's input() and python3's input() function.
In python2 we had 2 functions, raw_input() for reading input as a string and input() for numeric input.
In python 3 there is no raw_input() but only one method which is input() that by default read as a string.
so if you are trying to input some number you have to typecast it.
num = int(input("Input number \n"))
if you want to evaluate a expression of numbers you can use eval
>>> a = eval(input("Input Number: "))
2+3+4
>>> a
9
Do not use eval on production though!
Related
i am asking the user to input a number as well as if they think their number plus a random integer will be odd or even in the same line but cant get it to work.
I wrote
user, num = input('Enter a number 1-10: ' and '\n odd or even?').split()
Only the 2nd string is asked (odd or even?) when i run the program.
i want it to be formatted as
Enter a number 1-10: \n
odd or even?
How do I take two different types of inputs using one line of code. i want the input from
'Enter a number: '
to be an int and i want the input from
'odd or even' to be a str
Well, you can simply use two lines of input. something like this:
num = int(input('Enter your number: '))
state = input('Odd or Even?')
Remove and it will work
>>> user, num = input('Enter a number 1-10: odd or even? ').split()
Enter a number 1-10: odd or even?10 3
>>> user
'10'
>>> num
'3'
>>>
input() outputs strings. You may have to convert it to int using int(num).
try this line:
user, num = input('Enter a number 1-10:' + '\nodd or even?\n').split()
This question already has answers here:
Sum the digits of a number
(11 answers)
Closed last year.
Consider the following input prompt. I want to output the sum of digits that are inputted.
Example:
two_digit_number = input("Type a two digit number: ") 39
# program should print 12 (3 + 9) on the next line
If I input 39, I want to output 12 (3 + 9). How do I do this?
You can use sum(), transforming each digit to an integer:
num = input("Enter a two digit number: ")
print(sum(int(digit) for digit in num))
maybe like this:
numbers = list(input("Enter number: "))
print(sum(list(map(int, numbers))))
Read digits with input as a whole number of string type
split them with list() in characters in a list
use map() to convert type to int in a list
with sum() you're done.. just print()
Beware of invalid entries! "hundred" or "1 234 567"
you can achieve that like this:
a = input("Type a two digit number: ")
b = list(a)
print(int(b[0])+int(b[1]))
n = (int(input("Enter the two digit number\n")))
n = str(n)
p = int(n[0])+int(n[1])
print(p)
This is one of the many ways for it.
value = 39 # it is your input
value_string = str(value)
total = 0
for digit in value_string:
total += int(digit)
print(total)
new version according to need mentioned in comment:
value = 39
value_string = str(value)
total = 0
digit_list = []
for digit in value_string:
total += int(digit)
digit_list.append(digit)
print(" + ".join(digit_list))
print(total)
You can do that as follows:
two_digit_number = input("Type a two digit number: ")
digits = two_digit_number.split("+")
print("sum = ", int(digits[0])+int(digits[1]))
Explanation:
first read the input (ex: 1+1)
then use split() to separate the input statement into the strings of the input digits only
then use int() to cast the digit from string to int
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,
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
I am currently using Python to create a program that accepts user input for a two digit number and will output the numbers on a single line.
For Example:
My program will get a number from the user, lets just use 27
I want my program to be able to print "The first digit is 2" and "The second digit is 7"
I know I will have to use modules (%) but I am new to this and a little confused!
Try this:
val = raw_input("Type your number please: ")
for i, x in enumerate(val, 1):
print "#{0} digit is {1}".format(i, x)
It was not clear from your question whether you are looking to use % for string substitution, or % for remainder.
For completeness, the mathsy way using modulus operator on ints would look like this:
>>> val = None
>>> while val is None:
... try:
... val = int(raw_input("Type your number please: "))
... except ValueError:
... pass
...
Type your number please: potato
Type your number please: 27
>>> print 'The first digit is {}'.format(val // 10)
The first digit is 2
>>> print 'The second digit is {}'.format(val % 10)
The second digit is 7
Think about the two digit number as though it were a string. It is easier to grab each digit this way. Using str() will change the integer to a string. Modulos allow you to place these strings into your text.
Assuming the user inputs 27 into the variable called num, the code is:
print 'The first digit is %s and the second digit is %s' % (str(num)[0], str(num)[1])
Another way of coding Python:
val = raw_input("Type your number please: ")
for i in list(val):
print i
Note: val is read as string. For integer manipulation, use list(str(integer-value)) instead
two_digit_number = input("Type a two digit number: ")
print("The first digit is " + two_digit_number[0] + " The second digit is " +
two_digit_number[1])
You don't need modules to solve this question.