User validation loop for binary input is not recognising input - python-3.x

new to programming, but I'm working on a binary to decimal converter and I'm trying to make sure that the only input is either a '0' or '1' and not alpha, and not empty ''.
I have figured out logic for not empty and not alpha input , but I can't figure out the logic for the last condition - if 1 not in string or 0 not in string. It works if I enter either 1 or zero, but this isn't what i'm looking. I just want to check that there is only 1's or 0's and then proceed with the rest of the program.
I've spent hours on just this today so any help is appreciated. :)
Thanks in advance :)
def convert_to_decimal(binary_number):
print('\n')
#The binary input to be converted, entered as a string.
binary = input('Please enter binary numbera: ')
while binary.isalpha() or binary == '':
print("Please make sure your number contains digits 0-1 only.a ")
binary = input('Please enter numberb: ')
while binary not in '1' and binary not in '0':
print("Please make sure your number contains digits 0-1 only.x ")
binary = input('Please enter numberc: ')

Here I reworked it a little and its a bit inefficient, but here it is. It is a bit self-explanatory, but basically how it works, is it iterates over the inputString, and checks if each number is a 1 or 0 if not, the continue to ask, otherwise continue.
def isBinary(stringNum):
if len(stringNum) ==0:
return False
for chr in stringNum:
if chr != "0" and chr != "1":
return False
return True
def convert_to_decimal():
print('\n')
#The binary input to be converted, entered as a string.
binary = input('Please enter binary number: ')
while not isBinary(binary):
binary = input('Please enter binary number: ')
The reason yours doesn't work is you say if not in 1 and not in 0, which is wrong. in in this case returns True if the WHOLE string is in the target("0"). Since "10" isn't completely in 1 or in 0, it will ask you again, so you can see why that wouldn't work.

I hate myself for finding the answer, but it works :)
def convert_to_decimal(binary_number):
print('\n')
#The binary input to be converted, entered as a string.
binary = input('Please enter binary numbera: ')
while binary.isalpha() or binary == '':
print("Please make sure your number contains digits 0-1 only.a ")
binary = input('Please enter numberb: ')
while not binary.startswith('0') and not binary.startswith('1'):
print("Please make sure your number contains digits 0-1 only.x ")
binary = input('Please enter numberc: ')

Related

What is the best way to deal with negative integers inputs in a python calculator?

Hello Fellow Developer's and Eng's:
How can I handle these two type's of input 1) when user enter "-0" and 2) When user enter minus symbol "-", within my while loop for adding nonnegative integers.
The program developed functions in the overall design, which is to add non negative integers, but it has a flaw when a user input -0 or -(minus) sign. I want to print('you have entered a negative int or a negative/minus - symbol') when these entries are made by the user.
Currently, the program continues without adding when user submit -0 in the input and there is ValueError when user just submit - symbol.
Please provide feedback.
entry = 0
sum = 0
# Request input from the user
print('This is nonnegative integer addition program. \n',)
while entry >= 0:
entry=int(input('Please enter numbers to add: '))
if entry >=0:
sum+=entry
elif entry<0 or str(entry[0])=='-' or str(entry)=='-0': # -0 nor (first index -(minus) does not work
print('You have entered a negative integer or symbol:', \
entry, ', therefore you have been exited out of the program')
print('total integer input sum =',sum)
As mentioned in the other answer. You convert your value to an int and you can no longer access the characters. I've made the program store the user_input and check that.
entry = 0
sum = 0
# Request input from the user
print('This is nonnegative integer addition program. \n',)
while entry >= 0:
user_input = input('Please enter numbers to add: ')
if '-' in user_input:
print(
'You have entered a negative integer or symbol:',
user_input,
', therefore you have been exited out of the program'
)
break
entry = int(user_input)
sum+=entry
print('total integer input sum =',sum)
In this version I store the input string as user_input and check it for a '-' symbol. I use '-' in instead of user_input[0]=='-' because input that starts with a space can still work with int.
Another thing to note, your if/elif was over specified.
if entry >=0:
sum+=entry
elif entry<0 or str(entry[0])=='-' or str(entry)=='-0':
break
In your second clause entry is guaranteed to be less than zero. So the str(entry[0]) never gets called. Thankfully because it was an error. Your if statement is equivalent to.
if entry>=0:
...
else:
...
Lastly a small point. When you have a set of brackets like in your print statment. You don't need a \ to indicate a line continuation.
print(
"one",
"two"
)
Python recognizes the open (. If you wanted to continue a string you would need it.
print("one \
two")
When you are storing the input as int entry=int(input('Please enter numbers to add: ')) the entry value is 0 because on int the is no -0 so if you want to check if the user input -0 you need to keep it as str.
You can try
entry = 0
sum = 0
print('This is nonnegative integer addition program. \n',)
while int(entry) >= 0:
entry=input('Please enter numbers to add: ')
if entry[0] !='-':
if int(entry) >= 0:
sum+=int(entry)
elif entry[0]=='-' or entry=='-0':
print('You have entered a negative integer or symbol:', \
entry, ', therefore you have been exited out of the program')
entry = -1
print('total integer input sum =',sum)

Validate the user's input of only 0's and 1's

I have to convert an 8-bit binary number to a decimal number. I believe that I have the conversion correct along with validating if the user inputted an 8-bit binary number (no more, no less) but I am stuck on validating the user's input for only 0's and 1's.
Any help would be great. I feel like I am overthinking this but I tried everything.
Here is the code I have:
while True:
binary = input("Please enter a 8-bit binary number: ")
if len(binary) < 8 or len(binary) > 8:
print("Must be an 8 bit binary!")
else:
print(int(binary, 2))
break
Ok, first thing first, you use this line:
if len(binary) < 8 or len(binary) > 8:
it is way more readable to just say:
if len(binary) != 8
Now this is how I would implement your code:
while True:
binary = input("Please enter a 8-bit binary number: ")
for item in binary:
if item not in {'0','1'}:
print("Must only contains 0's and 1's !")
break
if len(binary) != 8:
print("Must be an 8 bit binary!")
else:
print(int(binary, 2))
break
Note that this will check for both validations you expected while providing a relevant insight to the user depending on his particular mistake.
You're checking the length, but not validating the users input. eg,
s = '12345678' is a valid input into your code.
If you really want to validate, you could do something simple like
s1 = '11010101111'
if s1.count('1') + s1.count('0') == len(s1):
print(int(s1,2))
If you're a fan of regexes:
import re
s1='10010011'
print(re.match(r'[10]{8}', s1) is None)
This will match 10010011, but not 110010100 or 12345689 or 12345678.

Numbers Only, Rounding up, and adding

so I am still learning Python so this should be rather easy to answer for some of you experts...
1) How can you make it so only numbers are accepted as an input?
def check_only_digit():
digits = input("Please input a number ")
if digits in "0123456789":
print("Working")
else:
print("Not working")
check_only_digit()
This will print "Working" if the inputted is a number in 0123456789 but only is this order. What I am asking is there any way to make it in any order?
2) How can I make the users digit round UP to the nearest 10?
def round_up():
users_number = input("Please input a number you want rounded ")
answer = round(int(users_number), -1)
print (answer)
round_up()
3) Is there anyway to add a number onto the end of another number? For example for 1+1, instead of equaling 2, can it equal 11?
I would like to thank you all for your responses in advance.
For Answer 1:
def check_Numbers():
number=input("Enter a number: ")
try:
number=int(number)
print("Working")
except(ValueError):
print("Not Working")
For Answer 2:
def rounding_Off():
userNumber=float(input("Enter a floating point number to round off: "))
roundedOff=round(userNumber,-1)
return roundedOff
For Answer 3:
def addNumbers():
number1=input("Enter one number: ")
number2=input("Enter another one: ")
newNumber=number1+number2
return int(newNumber)
#return newNumber <----- This if you want to get your number in string format.

Python 3.5.1 Introduction to Python 2.1 Mark Clarkson - While Loop Issue

I'm working my way through this set of tutorials. In section 3.2a - While Loops the following code is supposed to loop until the user enters the target number (7) then display a congratulations message however regardless of what number is entered Python either gives a right answer or a wrong answer, even 7 will sometimes flag a wrong answer. I know there are other ways to perform this sort of task but I would like to get the code from the tutorial working.
targetNumber = 7
guess = input("Guess a number between 1 and 10 ")
while guess != targetNumber:
print("Wrong, try again ")
guess = input("Guess a number between 1 and 10 ")
print("Congratulations - that's right!")
You should convert the target numger to an string before comparison. Also, you should exclude the congratulations message from the loop. I would suggest :
targetNumber = str(7)
guess = input("Guess a number between 1 and 10 ")
while guess != targetNumber:
print("Wrong, try again ")
guess = input("Guess a number between 1 and 10 ")
print("Congratulations - that's right!")
The detail is that input returns a string and if you compare a string to an integer, it will always return false.
Python's input function (or raw_input in Python 2.x) returns a string entered by the user. targetNumber, on the other hand, is an integer. In the Python Interpreter, try:
>>> 7 == "7"
False
You need to cast the user's input to an integer first.
try:
guess = int(input("Please enter a number: "))
except ValueError:
print("That is not a valid number!")

How to verify if input is not a letter or string?

I'm writing a basic program in IDLE with a menu choice with options from 1 to 4.
If a user input anything else then a number, it gives a ValueError: invalid literal for int() with base 10: 'a'
How can I check if the input is not a letter, and if it is, print a error message of my own?
def isNumber (value):
try:
floatval = float(value)
if floatval in (1,2,3,4):
return True
else:
return False
except:
return False
number_choice = input('Please choose a number: 1, 2, 3 or 4.\n')
while isNumber(number_choice) == False:
number_choice = input('Please choose a number: 1, 2, 3 or 4.\n')
else:
print('You have chosen ' + number_choice + '.\n')
This will check if the number is 1,2,3 or 4 and if not will ask the user to input the number again until it meets the criteria.
I am slightly unclear on whether you wish to test whether something is an integer or whether it is a letter, but I am responding to the former possibility.
user_response = input("Enter an integer: ")
try:
int(user_response)
is_int = True
except ValueError:
is_int = False
if is_int:
print("This is an integer! Yay!")
else:
print("Error. The value you entered is not an integer.")
I am fairly new to python, so there might very well be a better way of doing this, but that is how I have tested whether or not input values are integers in the past.
isalpha() - it is a string method which checks that whether a string entered is alphabet or words(only alphabets, no spaces or numeric) or not
while True:
user_response = input("Enter an integer : ")
if user_response.isalpha():
print("Error! The value entered is not an integer")
continue
else:
print("This is an integer! Yay!")
break
This program is having infinite loop i.e. until you enter an integer this program will not stop. I have used break and continue keyword for this.

Resources