I am trying to create a list where I need to input numbers as strings in one list and I am trying to do it with a while loop.
while input_list[-1] != "":
input_list.append(raw_input())
However when numbers are entered they are returned as u'X', X being the number entered. I cannot perfrom mathematical calculations on these numbers.
I would usually use str() or int() but I cant generalise in this case.
Is there a cleaner way to remove the u' ' prefix than simpley using if statements?
The "u'' prefix" is trying to indicate the type of the value. You have strings here, not numbers. If you want to do math, you need to convert your strings to numbers. If they happen to enter a string that can't be converted to a number, you should tell the user what happened
user_typed = raw_input()
try:
user_number = float(user_typed)
except ValueError:
print "Couldn't convert this to a number, please try again: %r" % user_typed
See also: LBYL and EAFP
Related
#user inputs a number
number = input("Enter number: ")
# 1) changes dot and creates a new string,2) verifies is it a number
if(not number.replace(".","").isnumeric()):
print("Sorry number is not numeric")
Generally replace changes old value with a new one.
isnumeric returns True if and only if every character of the string is a numeric character as defined by Unicode. Periods are not numeric, but many characters that contain or represent numbers, such as ½ or 六, are considered numeric.
First, you probably want isdigit instead, because a lot of the numeric characters in Unicode aren't valid in float numbers. isdigit only returns True if every character is one of the ASCII digits 0-9.
Second, to validate if the input is a float, it's "Better to Ask Forgiveness than Permission": try converting it as a float directly, and see if that fails:
try:
float(number)
except ValueError:
print("Sorry number is not a float")
number = input("Enter number: ")
if(not number.replace(".","").isnumeric()):
print("Sorry number is not numeric")
Replace here change dot, creates a new string and makes isnumeric() to be True for float numbers.
So... I have this primitive calculator that runs fine on my cellphone, but when I try to run it on Windows 10 I get...
ValueError: could not convert string to float
I don't know what the problem is, I've tried using raw_input but it doesn't work ether. Please keep in mind I'm green and am not aware of most methods for getting around a problem like this
num1 = float(input ()) #take a float and store it
chars = input () #take a string and store it
num2 = float(input ())
your code only convert string that are integers like in below statement
num1 = float(input ()) #take a float and store it ex 13
print num1 # output 13.0
if you provide 13 as a input it will give the output as 13.0
but if you provide SOMEONEE as input it will give ValueError
And it is same with the case of raw_input() but the difference is that by default raw_input() takes input as a string and input() takes input as what is provided to the function
I think this is happening because in some cases 'input' contains non-numerical characters. Python is smart and when a string only contains numbers, it can be converted from string to float. When the string contains non-numerical characters, it is not possible for Python to convert it to a float.
You could fix this a few ways:
Find out why and when there are non-numerical characters in your input and then fix it.
Check if input contains numbers only with: isdecimal()
Use a try/except
isdecimal() example:
my_input = raw_input()
if my_input.isdecimal():
print("Ok, go ahead its all numbers")
UPDATE:
Two-Bit-Alchemist had some great advice in the comments, so I put it in my answer.
Im trying to get the user to input the length and width of a rectangle at the same time.
length,width = float (raw_input("What is the length and width? ")).split(',')
When I run the program, however, and enter two variables such as 3,5 I get an error saying that I have an invalid literal for type float().
Well, that's because you're entering two numbers separated by a comma, but splitting that value on a period. Split it on a comma and it should work much better.
First, why does this fail:
float (raw_input("What is the length and width? ")).split(',')
The split(',') splits a string into a sequence of strings. You can't call float on a sequence of strings, only on a single string. That's why the error says it's "an invalid literal for type float".
If you want to call the same function on every value in a sequence, there are two ways to do it:
Use a list comprehension (or a generator expression):
[float(x) for x in raw_input("What is the length and width? ")).split(',')]
Or the map function:
map(float, raw_input("What is the length and width? ")).split(','))
I would use the list comprehension, because that's what the BDFL prefers, and because it's simpler for other things you may want to do like x[2], but it really doesn't matter that much in this case; it's simple enough either way, and you should learn what both of them mean.
You also will probably want to cast to integers:
prompt = "what is the length and width? "
inpt = raw_input(prompt)
length, width = [int(i) for i in inpt.split(',')]
I have a string variable:
str1 = '0000120000210000'
I want to convert the string into an integer without losing the first 4 zero characters. In other words, I want the integer variable to also store the first 4 zero digits as part of the integer.
I tried the int() function, but I'm not able to retain the first four digits.
You can use two integers, one to store the width of the number, and the other to store the number itself:
kw = len(s)
k = int(s)
To put the number back together in a string, use format:
print '{:0{width}}'.format(k, width=kw) # prints 0000120000210000
But, in general, you should not store identifiers (such as credit card numbers, student IDs, etc.) as integers, even if they appear to be. Numbers in these contexts should only be used if you need to do arithmetic, and you don't usually do arithmetic with identifiers.
What you want simply cannot be done.. Integer value does not store the leading zero's, because there can be any number of them. So, it can't be said how many to store.
But if you want to print it like that, that can be done by formatting output.
EDIT: -
Added #TimPietzcker's comment from OP to make complete answer: -
You should never store a number as an integer unless you're planning on doing arithmetic with it. In all other cases, they should be stored as strings
I'm making a game where the "Computer" tries to guess a number you think of.
Here's a couple snippets of code:
askNumber1 = str(raw_input('What range of numbers do you want? Name the minimum number here.'))
askNumber2 = str(raw_input('Name the max number you want here.'))
That's to get the range of numbers they want the computer to use.
print 'Is this your number: ' + str(random.randint(askNumber1, askNumber2)) + '?'
That's the computer asking if it got the number right, using random.randint to generate a random number. The problems are 1) It won't let me combine strings and integers, and 2) Won't let me use the variables as the min and max numbers.
Any suggestions?
It would be better if you created a list with the numbers in the range and sort them randomly, then keep poping until you guess otherwise there is a small possibility that a number might be asked a second time.
However here is what you want to do:
askNumber1 = int(str(raw_input('What range of numbers do you want? Name the minimum number here.')))
askNumber2 = int(str(raw_input('Name the max number you want here.')))
You save it as a number and not as a string.
As you suggested, randint requires integer arguments, not strings. Since raw_input already returns a string, there's no need to convert it using str(); instead, you can convert it to an integer using int(). Note, however, that if the user enters something which is not an integer, like "hello", then this will throw an exception and your program will quit. If this happens, you may want to prompt the user again. Here's a function which calls raw_input repeatedly until the user enters an integer, and then returns that integer:
def int_raw_input(prompt):
while True:
try:
# if the call to int() raises an
# exception, this won't return here
return int(raw_input(prompt))
except ValueError:
# simply ignore the error and retry
# the loop body (i.e. prompt again)
pass
You can then substitute this for your calls to raw_input.
The range numbers were stored as strings. Try this:
askNumber1 =int(raw_input('What range of numbers do you want? Name the minimum number here.'))
askNumber2 =int(raw_input('Name the max number you want here.'))
That's to get the range of numbers they want the computer to use.
print 'Is this your number: ' + str(random.randint(askNumber1, askNumber2)) + '?'