I'm making a calculator on Python 3.4. The calculator will ask the user to enter a number. I want to restrict this so they can only enter a number (which I am fine about) or to press the 'C' key to clear the calculator. I seem to be getting stuck with allowing the C as well as any integer. Anyone suggest any way of going about this?
Thanks
You could use this code, assuming the user shall be able to enter numbers consisting of several digits like 1337, but no decimal points. Inputs being mixed of digits and "C" are invalid, "C" only gets detected if the input contains only the letter "C" and nothing else. Leading and trailing whitespaces are ignored.
def get_input():
inp = input("Enter a number or 'C' to clear: ").strip()
if inp.upper() == "C":
return "C"
if inp.isdigit():
return int(inp)
else
return None
This function will return the entered number as integer, or the string "C", or None if the input was invalid.
Assuming you're taking in the user inputs one by one:
import string
allowed = string.digits+'C'
if input in allowed:
doSomethingWith(input)
Is this what you're looking for?
Related
I am currently working on the pseudocode of a project and it has just come to mind that, while I have a way of checking if User Input is strictly numerical, I have no idea of how to check if the input is strictly Alphabetical.
For Example:
def valueCheck_Int(question):
while (True):
try:
return int(input(question))
except:
question = "That is not a valid integer, try again: "
def main():
userInput = valueCheck_Int("Enter an integer: ")
print(userInput)
main()
This piece of code checks if the user's input is strictly numerical, and will only break the loop until the user has entered an integer.
Is there any possible way to do this, but with string input being alphabetical, with no numbers at all?
The str type in Python have methods for checking it, you don't need try, except at all.
These methods called isnumeric and isalpha.
isnumeric - If a string is a number, it'll return True, otherwise return False.
isalpha - If a string is alphabetical, it'll return True, otherwise return False.
Code Example:
string = 'alphabetical'
if string.isnumeric():
print('String is numeric!, it contains numbers and valid for integer casting!')
elif string.isalpha():
print('String is alpha!, it contains alphabetical letters.')
How to get a irrational number as a user input in python? Like squared root of 2
something like :
Irrational_Number = float(input("ENTER a Irrational Number : "))
>>> ENTER a Irrational Number : (USER INPUT)
and then user put a Number like N-th root of K (i mean the number in this format not the exactly this kind of String) " Pi " , " e " or " Phi " in command Line.
How User Can do this Directly in command line python (3.8)
I searched this question everywhere but there is nothing about that...
First of all, you're casting your input to a float, so to be precise (which is important if we're bandying around terms like Irrational Number) then we have to highlight the assumption that were talking about approximations to Irrational Numbers here.
That done, there's a few ways you can explore a solution:
The first would be to define a namespace in which you map string names to numeric equivalents - a simple dict could do the trick, like:
numbers_as_words = { "e",2.718281828459045
"pi",3.141592653589793
"phi",1.618033988749895
"sqr2",1.4142135623730951
"feet_to_meters",0.3048
"lbs_to_kg",0.453592
"miles_to_kilometers",1.60934
"gallons_to_litres",3.78541 }
I've padded that out with some non-irrational place-holders too, in case you wanted to embed some simple conversion type logic.
Then, you'd need to take your input as a string, perform a simple replace function on the string to resolve any matching strings, and viola , you've got a mixed numeric/string input method.
def replace_names_and_return_float(user_input, mapping):
for k,v in mapping.items():
user_input = user_input.replace(k,str(v))
return float(user_input)
Irrational_Number = replace_names_and_return_float(input("ENTER a Irrational Number : "), numbers_as_words )
Then it's just up to you to maintain that numbers_as_words dictionary to contain all the substitutions you want to recognise. That could get tedious, but it ought to be enough to get you started.
If you find some official list of irrational number approximations, you might be able to download it, and construct a numbers_as_words mapping as an automated process, but I've not Googled that just now.
Please find below code snippet:
import re
g = input("Enter your irrational number : ")
if g=='pi':
g=math.pi
elif "root" in g:
root=float(re.search('[0-9]+', g).group())
number=float(re.search('(\d+)(?!.*\d)', g).group())
g=number**(1/float(root))
print(g)
Advantage of using this would be:
There is no manual value inserted
You can build it for every symbol present in math lib
Can be extended for other operations as well
New to Python (2.7). I'm trying to collect a user input that can either be an int or string (I'm assuming this is possible, though I'm not 100% sure). When I get to the statement that I've posted below, any number I enter prints the 'Invalid input' message and prompts me for a user input again, even if it's within the range I want it to be. Entering 'q' still works properly and returns if entered.
I've tried changing that first if statement to read (0 <= collectEyesBlade <= 9) ... with no luck either.
while True:
collectEyesBlade = raw_input(
"\nEnter desired blade number: ")
if collectEyesBlade in [range(0,9)]:
break
elif collectEyesBlade.lower() == 'q':
return
else:
print "\nInvalid input. Enter value between 0 and 9, or 'q' to quit"
continue
Since raw_input returns a str, start with the comparison that uses another string. Then, try to convert it to an int. Finally, if that succeeds, try the integer comparision.
while True:
collectEyesBlade = raw_input("\nEnter desired blade number: ")
if collectEyesBlade.lower() == 'q':
return
try:
collectEyesBlade = int(collectEyesBlade)
except ValueError:
print "\nInvalid input. Enter value between 0 and 9, or 'q' to quit"
continue
if collectEyesBlade in range(0,9):
break
if collectEyesBlade in [str(x) for x in range(0,9)] - this should work since collectEyesBlade is a string so we need to compare it to a string
You've hit at two of the little quirks of Python. One: a range is itself an iterable, but it's possible to put an iterable inside of another iterable.
In other words, your statement
if collectEyesBlade in [range(0,9)]:
is checking to see whether collectEyesBlade is an item in the list, which has only one item: a range iterable. Since you're not entering a range iterable, it's failing.
You can instead say
if collectEyesBlade in list(range(0,9)):
which will turn the range iterable into an actual list, or just
if collectEyesBlade in range(0,9):
Either should do what you intend.
However, as another answerer has mentioned, that's only half the problem. If your input were actually possibly integer type, the above would be sufficient, but you're asking for a string input. Just because the input is a "1" doesn't mean it's not a string one.
There are a couple of options here. You could do a try-except converting the string input into an integer, and if it fails because the string can't be converted into an integer, move on; or you could convert the range/list of numbers to compare to into strings.
I created a function to receive odd digits from a 7 digit code and then add them to a list named 'oddDigitList', but for some reason I get a run-time error when I run the code.
# A function used to add odd digits from a variable to the 'oddDigitList' list, which will be used to calculate the 8th digit of the GTIN-8 code
def formOddDigitList(variable):
# The 'for' loop gets values from digit #1 to digit #7 in twos
variable = str(variable)
for i in range(0,8,2):
variable[i]
# The digits in the 'variable' argument are added to the 'oddDigitList' list
# The digits are converted into integers so that they can be used to calculate the 8th digit of the GTIN-8 product code)
oddDigitList.append(int(variable[i]))
return variable
And here is the error message I got:
oddDigitList.append(int(variable[i]))
ValueError: invalid literal for int() with base 10: 'N'
Can someone please explain why my code is wrong and provide a a correct version of my function.
Thank you guys for trying incredibly hard to answer my question and I do realise that I did need to add more to my function so that you guys knew in which the context of the function was for. Here is my teacher's solution, which completely fixes the problem that occurred:
oddDigitList = []
# A function used to add odd digits from a variable to the 'oddDigitList' list, which will be used to calculate the 8th digit of the GTIN-8 code
def formOddDigitList(variable):
# The 'for' loop gets values from digit #1 to digit #7 in twos
for i in range(0,8,2):
# The digits in the 'variable' argument are added to the 'oddDigitList' list
# The digits are converted into integers so that they can be used to calculate the 8th digit of the GTIN-8 product code)
oddDigitList.append(int(variable[i]))
return variable
# A function used as an input to assign boundaries/extremes to variables as well as enforcing 'try' and 'except' loops so that the user cannot crash the program by inputting a random number
def assignBoundariesToInput(number, text):
while True:
try:
variable = input(text)
if len(variable) != number:
raise ValueError
# This statement keeps looping until the user inputs the suitable data type
except ValueError:
print("Please input a/an", number, "digit number")
else:
break
return variable
gtin7OrGtin8 = str(input("Would you the like program to:\n\n a) Calculate the GTIN-8 product code from a seven digit number\n b) Check the validity of an eight digit GTIN-8 code\n c) Exit\n\nPlease enter your designated letter: ")).lower()
if gtin7OrGtin8 == "a":
gtinput7 = assignBoundariesToInput(7, "Enter the 7-digit code: ")
formOddDigitList(gtinput7)
print(oddDigitList)
else:
pass
As I said before, I am deeply sorry for not adding the additional detail to help you guys resolve the bug. In the future I will ensure to always add context into the problem to help the community answer any problems that occur to me.
I'm guessing this is what you want:
def formOddDigitList(number):
"""
A function used to add odd digits from a variable to the 'oddDigitList' list,
which will be used to calculate the 8th digit of the GTIN-8 code
"""
oddDigitList = []
string = str(number)
# get values for only the odd digits from digit #1 to digit #7
for i in range(0, 7, 2):
# The digits in the 'string' variable are added to the 'oddDigitList' list
# The digits are converted into integers so that they can be used to calculate the product code
oddDigitList.append(int(string[i]))
return oddDigitList
print(formOddDigitList(9638507))
RETURNS/PRINTS:
[9, 3, 5, 7]
For GTIN-8, I assume you want the odd digits to multiply them by a constant and add them to the even digits. All of which could be done by a single function.
I am trying to do some simple Python, which allows the user to enter a 6 digit number into the command line; my code then needs to check the values of the first and sixth digit of the number entered.
The value entered is stored in a variable named uinumber, I then check using an if statement to check if the values at these locations match. As shown below:
if uinumber[1] == 5 and uinumber[6] == 0:
This doesn't seem to do anything. I have also tried converting the number entered to a string and then doing the check as show below, but this causes the same issue.
uinumber_string = str(uinumber)
if uinumber_string[1] == 5 and uinumber[6] == 0:
This seems to cause the same issue; what is the right way to do this?
Thanks!
You're right about needing to cast the inputted number to a string, but you then need to compare it to a string as well.
Additionally, since you mentioned a 6-digit number, the correct indices are probably [0] and [5] and not [1] and [6], as sequences in Python (and most other programming languages) are zero-indexed.
And on one last note, you wrote uinumber[6] by accident instead of uinumber_string[6].
uinumber_string = str(uinumber)
if uinumber_string[0] == "5" and uinumber_string[5] == "0":
# Do something