have strange problem to cant know it . I will be thankful to help me .......enter image description here
You've to enter integers to convert it to int. You cannot convert "hi" to integer for example. What will be the value of int("hi")? For sure it'll give error. Try adding integers as input. If you're confused, take input in integer format only by writing varodi=int(input(":")) and take 1 as input to break the loop. Change the statement to if varodi==1: then break. Or else just put the input as integer
Related
Hi I am a beginner for python. May I ask how do you write an input prompt that takes a single number as the input, which represents a new row. Thanks
In python, you can use input() to read the input from the keyboard so if you want to use it later you can use a variable to store the input
str_input = input("Enter the string")
so by using the variable str_input you can get the value for later use like for printing etc. for print the value use
print(str_input)
So if you need to read the number as input then you need to typecast because everything in python default as a string so for typecast use
num_int = int(input("Enter the number"))
So by this you can read the num
This question already has answers here:
How to accept the input of both int and float types?
(6 answers)
Closed 5 years ago.
I'm trying to make a factorial calculator.
Input and Expected output:: If the user input is a positive integer, I want the program to give the outcome. And if the user input is not a positive integer(negative integer, float, or string), I want the program to ask for the input again. Also, I want the program to end when the user input is 0.
Problem: Since inputs are always perceived as string data, I am stuck with coding according to the type of input.
It would be of great help if someone would give answers to this problem, as I am studying by myself.
If you want to ensure it's a positive integer, and if you want to keep asking for input as specified in your question, you'll need a few more control structures:
from math import factorial
def get_input():
while True:
try:
inp = int(input("Enter a positive integer> "))
if inp < 0:
raise ValueError("not a positive integer")
except ValueError as ve:
print(ve)
continue
break
return inp
print(factorial(get_input()))
This works by just trying to convert the input to an integer, and retrying if this fails. The continue statement is used to skip past the break. The try/except structure catches the error if it's not an integer, or the error explicitly raised if it's less than 0. It also uses the as feature of except to print a better indication of the error. It's encapsulated in a function to make things easier - I find factorial(get_input()) to be pretty expressive, with the added bonus of being more reusable.
This currently doesn't end when the user input is 0, as 0 is a perfectly valid input for factorial, although it should be easy enough to adapt to this with an if statement.
This program might be used like this:
Enter a positive integer> abc
invalid literal for int() with base 10: 'abc'
Enter a positive integer> 0.2
invalid literal for int() with base 10: '0.2'
Enter a positive integer> -5
not a positive integer
Enter a positive integer> 6
720
By the way, this code works according to EAFP - it just tries to convert to an integer, and handles failure. This is more idiomatic Python than first trying to determine if it could be an integer (LBYL).
If you're using Python 2, you'll need to change input to raw_input.
Check if input is positive integer check this link out along with the link provided by user #cricket_007 above. Combining those two information should get you in the right direction.
Try to think of it as an algorithm problem not as a Python problem, you may find a solution because in general every language has its functions and they all almost the same only with different name.
In python they are a function call isnumeric() and it returns true if every single character is a number or false if it's not.
str.isnumeric()
us it with a statement condition like if
if str.isnumeric()==true // so it's numeric
// what to do!!!!!
the best choice it to use while and if
while true
//read data as string
if str.isnumeric()==true
break; // this to break the while loop
hope this can help you
Python newbie here. I've been messing around with flow control and have come across a situation I don't quite understand related to exceptions.
In the following code I want the user to enter an integer in a given range and, in the case of non-compliance, keep asking them until they give a valid value:
while True:
try:
x = int(raw_input("Pick an integer between 2 and 9. "))
except ValueError:
print "Please enter an integer!"
continue
else:
if 2 <= x <= 9:
print("Your number is {0}.").format(x)
break
else:
print "That's not between 2 and 9!"
continue
As far as I can tell, this code works exactly as I want it to. I've thrown every other type of input I can think of at it and it only lets you exit the loop when an integer from 2-9 is entered. Not even floats are accepted.
My question is, given that int() can be successfully called on floats,
>>> int(2.1)
2
why does this try/except construct raise the exception when the input is a float? If I run the code without the try/except statements and enter anything other than an integer, it throws an error and exits.
I'm running python 2.7 from windows powershell.
This is because raw_input returns a string.
Under the hood, when you call int, it actually calls an objects object.__int__() method. This is different from object to object.
For a float, this truncates a value (Rounds towards 0).
On a string, it tries to parse an int according to https://docs.python.org/3/reference/lexical_analysis.html#integer-literals (Which can't have a .).
The issue here is that you are calling int() on a string that could potentially contain a period. To fix this I would recommend you change the int() to float(). This should fix your problem
x = float(raw_input("Pick an integer between 2 and 9. "))
Not sure what version of Python you are using but if it is Python 3.0 or above you might want to carefully check the print statements in the following clips
except ValueError:
print "Please enter an integer!"
else:
print "That's not between 2 and 9!"
they are not formatted for 3.0 but will probably work ok if you use version 2.x
I think the other answers covered your original problem adequately so I will defer to them.. they know that area better than I.
Good Luck,
Poe
I am having a slight issue with math's .isnan() function in python. Pretty much, I have this code:
import math
diceChoice = raw_input('Which dice will you throw?\n 4 sides\n 6 sides\n 12 sides?\n>')
if math.isnan(float(diceChoice)):
print(str(diceChoice) + ' is an invalid choice')
and if diceChoice isn't a number (eg 'a') it gives me the error:
ValueError: could not convert string to float: a
If I don't convert it to a float, it gives me another error saying that it needs to be a float. I must be doing something wrong as the isnan function would be useless if it only accepts numbers. Can someone please help me
Thanks in advance
The float() function used on any other string other than a decimal number, 'nan', '-inf' or 'inf' (or slight variants of those strings) will throw a ValueError instead, because anything else is not a valid floating point value. math.isnan() only works on the special float value float('nan'), but it is not ever called if float() raises an exception first.
Use exception handling to catch that error instead:
try:
diceChoice = int(diceChoice))
except ValueError:
print(diceChoice, 'is an invalid choice')
I used int() instead because your input requires that the user enters a whole number.
Just to be explicit: float('nan') is a specific floating point value to signify the output of certain mathematical operations that are not an exception. It is never used to signify invalid input.
isnan() is really only used to check if a number doesn't have a finite value. Consider instead doing something like:
if not diceChoice.isdigit():
The error is raised because you attempt to convert a string to an integer with float('a'). Easier to just do the above.
NaN are used to define things that are not numbers in a floating point context like 0/0 or the square root of a negative number for example. You can use isdigit or something else.
How do I convert this number to an integer I can do simple math with?!
(eg. 10.5200 below.)
{"bid":["10.52000000","0.70824000"],"ask":["10.54000000","2.07336000"],"seq":2456916}
I get the following error, and it's driving me mental:
ValueError: invalid literal for int() with base 10: '10.52'
This is what I'm running:
bitfl = json.loads(bitfl)
bid = bitfl['bid']
ask = bitfl['ask']
bidd = bid[0] #edit - this is actually in, as it's a list
askk = ask[0]
print('diff: %i' % (int(bidd[0]) - int(askk[0])))
I don't know WHY it should be so difficult to just accept "10.52" as a string or float or unicode and just convert it to a normal, calculable integer!
Any help MUCH appreciated!
The problem is that you are trying to convert a string containing a non-integer to an integer.
The easiest/best solution is using int(float(yourstring))
Since you receive the data as JSON you should also consider requiring whatever client is providing the data not to use strings for non-string data.
Simply write int(float(bidd[0]))