This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Python how to multiply results from input strings [duplicate]
(3 answers)
Closed 2 years ago.
number=input('Enter a number')
total=number*5
print(total)
This code is not print the total please help me.
This print only the number multiple times.
When you input a value, it will be saved as a str value. Instead, typecast the value into an integer using int. Note - when you multiply a string by an integer, it duplicates that value by the integer value.
>>> number=input('Enter a number')
5
>>> print(type(number))
<class 'str'>
>>> total=number*5
>>> print(total)
'55555'
Instead typecast the input using int()
>>> number=int(input('Enter a number'))
5
>>> print(type(number))
<class 'int'>
>>> total=number*5
>>> print(total)
15
If you want to print the number 5 times you got the code correct.
however I think you want to multiply the number by 5.
so convert the number in to integer. Then it will work.
You can check your type of variable by:
print(type(number))
Answer:-
number=input('Enter a number')
number=int(number)
total=number*5
print(total)
or use in single statement.
number=int(input('Enter a number'))
total=number*5
print(total)
Because input function returns str.
It's exmplained in documentation: Built-in functions: input.
>>> num = input("enter a number: ")
enter a number: 13
>>> type(num)
<class 'str'>
You need to cast it to int by int(num).
Since input returns a string you have to convert the string to int:
number = input('Enter a number')
total= int(number)*5
print(total)
When you get input from the user using input() it will save the varaible as a string by default. To remedy this you need to convert the string to int like this:
number = int(input('Enter a number: '))
total = number * 5
print(total)
It's because input returns a string. You need to cast it to int at somewhere. You can try this:
number = int(input('Enter a number'))
total = number*5
print(total)
#Enter a number 3
#15
Related
num = input("Enter Something:")
print(type(num))
for some reason when running this code, or any alternative version even without text (string), it still outputs a string.
<class 'str'>
is there any way to check for all types like expected? e.g str and int
The problem is that input() returns a string, so the datatype of num will always be a string. If you want to look at that string and determine whether it's a string, int, or float, you can try converting the string to those datatypes explicitly and check for errors.
Here's an example of one such check:
def check_user_input(input):
try:
# Convert it into integer
val = int(input)
print("Input is an integer number. Number = ", val)
except ValueError:
try:
# Convert it into float
val = float(input)
print("Input is a float number. Number = ", val)
except ValueError:
print("No.. input is not a number. It's a string")
I got this example here where there's a more thorough explanation: https://pynative.com/python-check-user-input-is-number-or-string/
Here is a solution based on that for your problem specifically:
def convert_input(input):
try:
# Convert it into integer
val = int(input)
return val
except ValueError:
try:
# Convert it into float
val = float(input)
return val
except ValueError:
return input
num = input("Enter Something:")
num = convert_input(num)
print(type(num))
Input always returns string. If you want some other type you have to cast.
For example:
input_int = int(input("Enter something"))
You should know that, the default input is set to return string. To make this clear, do refer to the following example:
>>> number_input = input("Input a number: ")
Input a number: 17
>>> number = number_input
>>> print(type(number))
<class 'str'>
Python defines the number_input as a string, because input is by default a string. And if python recognizes number_input as string, variable number must also be a string, even though it is purely numbers.
To set number as a int, you need to specify the input as int(input("Input a number: ")). And of course, if you want to input float, just change the data type to float input.
But answering your question, you can't print <class 'str'> and <class 'int'> at the same time.
By default when you type input(), python run it as string data-type so you can change or actually limit it by usage of int()
integer_number = int(input("only numbers accepted: "))
This question already has answers here:
Sum the digits of a number
(11 answers)
Closed 3 years ago.
So I am trying to get a user's input and add it's numbers together.
input('Enter number: ')
And then say the user entered 458 then I wanted to add all it's digits up? I have tried using + but it doesn't work. Any solutions?
The problem you probably came across is that you have a string.
>>> answer = input('Enter number: ')
Enter number: 458
>>> print(type(answer))
<class 'str'>
But if you want to add each of the digits up, you'll need to convert each digit to an int. Thankfully, because we have a string here, we can actually iterate through each character in the string (try not to read it as "each digit in the number", because we have a string '458' here with characters '4', '5', '8'.)
>>> total = 0
>>> for character in answer:
... total = total + int(character)
...
>>> print(total)
17
Notice how I convert each character in the string to an integer, then add it to a total integer.
Perhaps this will work:
user_number = input('please enter your number')
sum = 0
for num in user_number:
sum += int(num)
print(sum)
You could convert your input into a list then use list comprehension:
num = input('Enter number: ')
sum([int(i) for i in num])
This question already has answers here:
How to input the number of input in python
(2 answers)
Closed 3 years ago.
I am inserting values in an array but the x = int(input()) is showing eithr EOF error or invalid literal for int() with base 10: '5 4 2 1'
arr = array('i',[])
n = int(input("enter the length of array"))
print(n)
for i in range(n):
x = int(input())
arr.append(x)
Given the error message, you are entering all the numbers on one single line, separated by spaces, then hitting the 'enter' key, so input() returns the string "5 4 2 1", which is indeed not a valid representation of an integer.
Given how your code is written, the simple solution is to just enter one value, hit the 'enter' key, enter the second value, hit the 'enter' key, lather, rinse, repeat... You can make this expectation clearer by passing a prompt string to input(), ie:
for i in range(n):
x = int(input("enter value #{} and hit enter".format(i+1)))
arr.append(x)
Now if you expect your code to be reasonably robust, you want to properly handle wrong user inputs:
def get_integer_input(prompt):
while True:
value = input(prompt).strip()
try:
return int(value)
except ValueError:
print("sorry, '{}' is not a valid integer".format(value))
and then in your code snippet replace all the int(input(...)) calls by a call to this function.
arr=list(map(int,input().split()))
you will get array like this
import array as arr
arr = arr.array('i',[])
n = int(input("enter the length of array"))
print(n)
listt=(list(map(int,input().split())))
for i in listt:
arr.append(i)
print(arr)
input.split() will convert '5 6 7 8' to ['5','6','7','8'] and mapping to int will convert it to [5,6,7,8]
So I'm trying to create a function that allows me to times a users input by 12. However, for example instead of doing 12 x 4 = 64 its gives me 4 12s' e.g. 444444444444
Ive already tried using the return function on its own and Ive tried creating a variable.
Options Ive tried are:
def cube(num):
print("answer =")
return num*12
num1 = input("Enter a number to times by 12: ")
print(cube(num1))
and:
def cube(num):
print("answer =")
answer = num*12
return answer
num1 = input("Enter a number to times by 12: ")
print(cube(num1))
I would expect if input number is 4 i would get 64 but the output is shown as 444444444444
It is because the input is read as a string. If you create string s = 'foo' and do something like this s2 = s*4 then s2 will be equal to foofoofoofoo. To fix your problem convert input to int. So answer = int(num)*12)
When you take in input, you get it as a string first. When you multiply a string, you’ll get repetitions of that string, which is why you’re getting twelve 4s.
You need to convert that input into a number before multiplying it.
Try:
cube(int(num1))
instead.
The function input returns a string, not a number. Multiplying a string by a number repeats the string that many times.
You'll want to convert that string to a number early:
num1 = int(input("Enter a number to times by 12: "))
print(cube(num1))
input("Enter a number to times by 12: ") gets input as string. Python strings allows you to multiply them to a number. The result is a number times repeated string (as you see, 444444444444). If you want to treat input as number, you should convert it to an integer:
num1 = int(input("Enter a number to times by 12: "))
You need to cast the input value to a float or int. input always returns a string.
num1 = float(input('Enter a number to multiply by 12: '))
This will cause a ValueError if you enter something that can’t be converted to a number.
If you need to keep asking for a valid input, I always tend to create a function that does this for me:
def float_input(prompt=''):
while True:
try:
return float(input(prompt))
except ValueError:
print('Invalid Input')
Now replace the input in your code with float_input
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 months ago.
unfortunately raw_input is not doing what I need it to do. What I am trying to do is get totPrimes = whatever I type in at the prompt. If i replace while count < totPrimes with while count < 50 this script works. If I type 50 into the prompt, this script doesnt work, I'm afraid raw_input isn't the function im looking to use? Here is a snippet of my code:
testNum = 3
div = 2
count = 1
totPrimes = raw_input("Please enter the primes: ")
while count < totPrimes :
while div <= testNum :
Do
totPrimes = int(totPrimes)
while count < totPrimes:
# code
raw_input gives you a string you must convert to an integer or float before making any numeric comparison.
You need to cast totPrimes into an int like this:
integer = int(totPrimes)
You just need to convert your raw input in a integer. For your code just change your code as:
testNum = 3
div = 2
count = 1
totPrimes = raw_input("Please enter the primes: ")
totPrimes=int(totPrimes)
while count < totPrimes :
while div <= testNum :
The raw_input function always returns a 'string' type raw_input docs, so we must in this case convert the totPrimes 'string' type to an 'int' or 'float' type like this:
totPrimes = raw_input("Please enter the primes: ")
totPrimes = float(totPrimes)
You can combine them like this:
totPrimes = float(raw_input("Please enter the primes: "))
In order to compare things in python count < totPrimes, the comparison needs to make sense (numbers to numbers, strings to strings) or the program will crash and the while count < totPrimes : while loop won't run.
You can use try/except to protect your program. managing exceptions
For people taking the course "Programming for Everybody" you can take in hours and rate this way. the if/else statement you should try to figure out.
You have to change every number to "hrs" or "rate".
For example: 40*10.50+(h-40)*10.50*1.5 is wrong, 40*r+(h-40)*r*1.5 is right.
Use input then.
Raw input returns string.
input returns int.