This code gives an error
print('type a whole number:')
n = input()
if n % 2 == 1:
print('Odd');
else:
print('Even');
I'm assuming there's something special I have to do to variable n in the if statement? I am a beginner to Python.
Here is how to fix it:
n = int(input("type a whole number:"))
Since input() returns a string, you need to convert it to an int first, using int().
You need to convert n to an integer first, in py 3.x input() returns a string.:
n = int(input())
Convert the user input n to an integer first.
i.e. Simply Change :
n = input()
To :
n = int(input())
Also, input() can take a string as an argument, which is printed before taking the input.
So, you can change
print('type a whole number:')
n = int(input())
To
n = int(input('type a whole number:'))
Related
Good day everyone, I would like to ask about this problem which I need to make the outcome only Integers and not string
If I put string in the Input.. it will make error and If i place number it will print the number
example:
num = int(input("Enter number only: ")).split(",")
print(num)
Assuming the user gives a comma-delimited input 7,42,foo,16, you can use a try block to only add numbers, and pass over strings:
nums = []
user_input = input("Enter a series of numbers separated by commas: ")
input_fields = user_input.split(",")
for field in input_fields:
try:
num.append(int(field))
except ValueError:
pass
for num in nums:
print(str(num))
I would do this:
user_input = input("Enter a series of numbers separated by commas: ")
input_fields = user_input.split(",")
int_list = []
for i in input_fields:
int_list.append(int(i)) # you may want to check if int() works.
I'm writing a program that takes in a value from the user, in the console, and I'm casting it to an int like so:
num = int(input("Enter a number: "))
I need my program to work with ints only. This works to convert an actual int entered into the console to an int I can use in the program, but if the user enters a float, like 3.1, then it doesn't cast to an int by truncating or rounding up for example.
How do I get the user to input an int rather than a float? Or how do I convert a floating point input to an int?
You can use a try catch block to ensure they only give you an int:
while True:
try:
num = int(input("Enter a number: "))
#do something with num and then break out of the while loop with break
except ValueError:
print("That was not a number, please do not use decimals!")
When ValueError (when it fails to convert to int) is excepted it goes back to asking for a number which once you get your number you can do things with said number or break out of the loop then and use num elsewhere.
You can use a try except to test if a user input is a whole number. Example code:
while True:
try:
value=int(input("Type a number:"))
break
except ValueError:
print("This is not a whole number.")
This code will loop back to the start if a user inputs something that is not an int.
So int() of a string like "3.1" doesnt work of course. But you can cast the input to a float and then to int:
num = int(float(input("Enter a number: ")))
It will always round down. If you want it to round up if >= .5:
num = float(input("Enter a number: "))
num = round(num, 0)
num = int(num)
You can simply use eval python built-in function. num = int(eval(input("Enter a number: "))).
For converting string into python code and evaluating mathimatical expressions, eval function is mostly used. For example, eval("2 + 3") will give you 5. However, if you write "2 + 3", then u will get only '2 + 3' as string value.
Try:
num = int(float(input("Enter number: ")))
and the float will be rounded to int.
You can also add a try...except method to give error to user if the number cannot be converted for any reason:
while True:
try:
num = int(float(input("Enter number: ")))
print(num)
break
except ValueError:
print("This is not a whole number")
use abs() it returns the absolute value of the given number
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
I wrote some code to check if two input variables contained decimal points as so:
while "." in n:
print()
print("Please enter only integer numbers")
n = input("Please enter the numerator:")
d = input("Please enter the denominator:")
while "." in d:
print()
print("Please enter only integer numbers")
n = input("Please enter the numerator:")
d = input("Please enter the denominator:")
however, I need a way for these loops to be ignored if the decimal is followed by a 0, e.g. 4.0 or 8.0.
Is there a way to do this, or is there a better way to check if the number entered is a decimal? I don't want to make the input a float from the beginning as it also needs to work if the user enters an integer.
The version of python I'm using is 3.5.4.
this the solution you are looking for
while int(float(d)) != float(d) or int(float(n)) != float(n):
other answers won't work for numbers like 8.05
To piggy-back off of #public static void main 's answer,
you can also consolidate your loop.
while ("." in n and ".0" not in n) or ("." in d and ".0" not in d):
n = input("Enter the numerator: ")
d = input("Enter the denominator: ")
Replace this:
while "." in n:
with this:
while "." in n and ".0" not in n:
This makes the code in the loop execute when "." is found in n, but ".0" is not found in n.
Consider comparing them as the actual value types:
while int(float(d)) != float(d) or int(float(n)) != float(n):
I want to test whether a 10 digit number is of 10 length, but whenever the number begins with 0, len() only counts 9.
How can I fix this?
At the moment:
something is a variable made up of numbers, I converted the variable into a string, then made this statement.
if len(something) != 10:
(do something)
My current code:
number = int(input("Enter number: "))
number = str(number)
if len(number) != 10:
print ("Not 10 digits long")
else:
print ("Good")
If I inputted a number with 10 digits it's fine, BUT, when I input a number with 10 digits and starting with zero, the len() function recognizes the number as 9 long. Help plz
Providing yout code, it's because you are casting your input to int, then casting it down to string (input automatic type is str in Python3, if you're using Python2, don't forget to cast as str or using raw_input like hackaholic).
Replace
number = int(input("Enter number: "))
number = str(number)
By
number = input("Enter number: ")
So number will directly be a string. And you can use len() on it. It even works with 0000000000
you forcing it to integer, input take values as string
number = input("Enter number: ")
if len(number) != 10:
print ("Not 10 digits long")
else:
print ("Good")
len function works on string
if you using python 2.x better to use raw_input("Enter Number: ")
Numbers starting with 0 are represented in base 8 (octal numbers) in python. You need to convert them to string to count their digits :
# Not converted
number1 = 0373451234
print "number: "+str(number1)+" digits:"+str(len(str(number1)))
> number: 65950364 digits:8
# Converted
number2 = "0373451234"
print "number: "+str(number2)+" digits:"+str(len(str(number2)))
> number: 0373451234 digits:10