How to allow strings in a float input? - python

So I'm asking my user to input a number(float)
num=float(input("Please enter a number"))
but I'm also asking the user to enter the value "q" to quit
and since this variable can only take in floats, the program is not letting the user enter the string ("q"), is it possible to do this?

Expect a string and parse it has as a float only if it is not equal to q.
temp = input("Please enter a number")
if not temp == "q":
num = float(temp)

You're trying to automatically cast your input to a float. If you don't want to do this in all cases you should add some if/else logic in here:
input_string = input("Please enter a number")
if not input_string == 'q':
num = float(intput_string)
Or, to be a bit more pythonic you should do a try/except strategy:
input_string = input("Please enter a number")
try:
num = float(input_string)
except ValueError:
if input_string == 'q':
# However you exit
The second is technically more pythonic according to the EAFP principle (https://docs.python.org/2/glossary.html)

Related

Issue in providing special character as input in python [duplicate]

I want to get a string from a user, and then to manipulate it.
testVar = input("Ask user for something.")
Is there a way for testVar to be a string without me having the user type his response in quotes? i.e. "Hello" vs. Hello
If the user types in Hello, I get the following error:
NameError: name 'Hello' is not defined
Use raw_input() instead of input():
testVar = raw_input("Ask user for something.")
input() actually evaluates the input as Python code. I suggest to never use it. raw_input() returns the verbatim string entered by the user.
The function input will also evaluate the data it just read as python code, which is not really what you want.
The generic approach would be to treat the user input (from sys.stdin) like any other file. Try
import sys
sys.stdin.readline()
If you want to keep it short, you can use raw_input which is the same as input but omits the evaluation.
We can use the raw_input() function in Python 2 and the input() function in Python 3.
By default the input function takes an input in string format. For other data type you have to cast the user input.
In Python 2 we use the raw_input() function. It waits for the user to type some input and press return and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting
x = raw_input("Enter a number: ") #String input
x = int(raw_input("Enter a number: ")) #integer input
x = float(raw_input("Enter a float number: ")) #float input
x = eval(raw_input("Enter a float number: ")) #eval input
In Python 3 we use the input() function which returns a user input value.
x = input("Enter a number: ") #String input
If you enter a string, int, float, eval it will take as string input
x = int(input("Enter a number: ")) #integer input
If you enter a string for int cast ValueError: invalid literal for int() with base 10:
x = float(input("Enter a float number: ")) #float input
If you enter a string for float cast ValueError: could not convert string to float
x = eval(input("Enter a float number: ")) #eval input
If you enter a string for eval cast NameError: name ' ' is not defined
Those error also applicable for Python 2.
If you want to use input instead of raw_input in python 2.x,then this trick will come handy
if hasattr(__builtins__, 'raw_input'):
input=raw_input
After which,
testVar = input("Ask user for something.")
will work just fine.
testVar = raw_input("Ask user for something.")
My Working code with fixes:
import random
import math
print "Welcome to Sam's Math Test"
num1= random.randint(1, 10)
num2= random.randint(1, 10)
num3= random.randint(1, 10)
list=[num1, num2, num3]
maxNum= max(list)
minNum= min(list)
sqrtOne= math.sqrt(num1)
correct= False
while(correct == False):
guess1= input("Which number is the highest? "+ str(list) + ": ")
if maxNum == guess1:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess2= input("Which number is the lowest? " + str(list) +": ")
if minNum == guess2:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess3= raw_input("Is the square root of " + str(num1) + " greater than or equal to 2? (y/n): ")
if sqrtOne >= 2.0 and str(guess3) == "y":
print("Correct!")
correct = True
elif sqrtOne < 2.0 and str(guess3) == "n":
print("Correct!")
correct = True
else:
print("Incorrect, try again")
print("Thanks for playing!")
This is my work around to fail safe in case if i will need to move to python 3 in future.
def _input(msg):
return raw_input(msg)
The issue seems to be resolved in Python version 3.4.2.
testVar = input("Ask user for something.")
Will work fine.

Input from keyboard the <enter>

I use Python 3 in Windows. My problem is that I need to find out how can I put in my code the choice that if the user pushes the Enter key the program will continue doing the calculation and when the user types q and pushes the Enter key the program will be terminated.
A simple code is below.
while True:
x = int(input('Give number: '))
y=x*3
print(y)
while True:
user_input = input('Give number: ')
if not user_input.isdigit(): #alternatively if user_input != 'q'
break
x = int(user_input)
y=x*3
print(y)
Assuming you want to calculate while new numbers are entered, the str isdigit function returns True if the string only contains digits. This approach will allow you to handle if the user enters a non-integer like xsd, which will crash the program if you try to cast to int. To only exit if q is entered, you would do if user_input != 'q', but this assumes the user only enters numbers or q.
while True:
s = input('Give number: ')
if s == 'q':
break
y=int(s)*3
print(y)

Python | Expecting type INT, but if STR entered?

I'm asking the user for an integer type input. But if the user accidentally inputs string type, I want it to tell the use they incorrectly answer the question. Like this:
question1 = int(input("Enter a number: "))
if question1 != int:
print("Please enter a number.")
else:
...
Please note I am a beginner, and therefore do not understand expect style coding.
Thank you for your time.
Casting a string to an integer will only work if the string looks like an integer.
Anything else will raise a ValueError.
My suggestion is to catch this ValueError and inform the user appropriately.
try:
question1 = int(input("Enter a number: "))
except ValueError:
print("That's not a number!")
else:
print("Congratulations - you followed the instructions")
You can use str.isdigit() method to check if the input contains digits only
question1 = input("Enter a number: ")
if question1.isdigit():
question1= int(question1)
else:
print("Not a number")

Python does not accept my input as a real number

# Math Quizzes
import random
import math
import operator
def questions():
# Gets the name of the user
name= ("Alz")## input("What is your name")
for i in range(10):
#Generates the questions
number1 = random.randint(0,100)
number2 = random.randint(1,10)
#Creates a Dictionary containg the Opernads
Operands ={'+':operator.add,
'-':operator.sub,
'*':operator.mul,
'/':operator.truediv}
#Creast a list containing a dictionary with the Operands
Ops= random.choice(list(Operands.keys()))
# Makes the Answer variable avialabe to the whole program
global answer
# Gets the answer
answer= Operands.get(Ops)(number1,number2)
# Makes the Sum variable avialbe to the whole program
global Sum
# Ask the user the question
Sum = ('What is {} {} {} {}?'.format(number1,Ops,number2,name))
print (Sum)
global UserAnswer
UserAnswer= input()
if UserAnswer == input():
UserAnswer= float(input())
elif UserAnswer != float() :
print("Please enter a correct input")
def score(Sum,answer):
score = 0
for i in range(10):
correct= answer
if UserAnswer == correct:
score +=1
print("You got it right")
else:
return("You got it wrong")
print ("You got",score,"out of 10")
questions()
score(Sum,answer)
When I enter a float number into the console the console prints out this:
What is 95 * 10 Alz?
950
Please enter a correct input
I'm just curious on how I would make the console not print out the message and the proper number.
this is a way to make sure you get something that can be interpreted as a float from the user:
while True:
try:
user_input = float(input('number? '))
break
except ValueError:
print('that was not a float; try again...')
print(user_input)
the idea is to try to cast the string entered by the user to a float and ask again as long as that fails. if it checks out, break from the (infinite) loop.
You could structure the conditional if statement such that it cause number types more than just float
if UserAnswer == input():
UserAnswer= float(input())
elif UserAnswer != float() :
print("Please enter a correct input")
Trace through your code to understand why it doesn't work:
UserAnswer= input()
This line offers no prompt to the user. Then it will read characters from standard input until it reaches the end of a line. The characters read are assigned to the variable UserAnswer (as type str).
if UserAnswer == input():
Again offer no prompt to the user before reading input. The new input is compared to the value in UserAnswer (which was just entered on the previous line). If this new input is equal to the previous input then execute the next block.
UserAnswer= float(input())
For a third time in a row, read input without presenting a prompt. Try to parse this third input as a floating point number. An exception will be raised if this new input can not be parsed. If it is parsed it is assigned to UserAnswer.
elif UserAnswer != float() :
This expression is evaluated only when the second input does not equal the first. If this is confusing, then that is because the code is equally confusing (and probably not what you want). The first input (which is a string) is compared to a newly created float object with the default value returned by the float() function.
Since a string is never equal to a float this not-equals test will always be true.
print("Please enter a correct input")
and thus this message is printed.
Change this entire section of code to something like this (but this is only a representative example, you may, in fact, want some different behavior):
while True:
try:
raw_UserAnswer = input("Please enter an answer:")
UserAnswer = float(raw_UserAnswer)
break
except ValueError:
print("Please enter a correct input")

How to add up a variable?

I was wondering how I would sum up the numbers they input for n even though it's an input and not int. I am trying to average out all the numbers they input.
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Start now ")
a+=1
In Python 2.x input() evaluates the input as python code, so in one sense it will return something that you can accept as an integer to start with, but may also cause an error if the user entered something invalid. raw_input() will take the input and return it as a string -> evaluate this as an int and add them together.
http://en.wikibooks.org/wiki/Python_Programming/Input_and_Output
You would be better off using a list to store the numbers. The below code is intended for Python v3.x so if you want to use it in Python v2.x, just replace input with raw_input.
print("Enter as many numbers you want, one at the time, enter stop to quit. ")
num = input("Enter number ").lower()
all_nums = list()
while num != "stop":
try:
all_nums.append(int(num))
except:
if num != "stop":
print("Please enter stop to quit")
num = input("Enter number ").lower()
print("Sum of all entered numbers is", sum(all_nums))
print("Avg of all entered numbers is", sum(all_nums)/len(all_nums))
sum & len are built-in methods on lists & do exactly as their name says. The str.lower() method converts a string to lower-case completely.
Here is one possibility. The point of the try-except block is to make this less breakable. The point of if n != "stop" is to not display the error message if the user entered "stop" (which cannot be cast as an int)
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Enter a number: ")
try:
a+=int(n)
except:
if n != "stop":
print("I can't make that an integer!")
print("Your sum is", a)

Categories