Validate the user's input of only 0's and 1's - python-3.x

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.

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)

User validation loop for binary input is not recognising input

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: ')

LUA: Reading text after reading number does not work

I am struck with the io.read command in LUA. The example below jumps over the text-read line. That only happens if there is a number input before.
repeat
print("Input number!")
number=io.read("*n")
print("Would you like do to this again? (y/n)")
again = io.read()
until again == "n"
I tried this in two IDEs (repl and ZeroBrane) and it drives me MAAAD!!!
Cany anyone help, please?
Cheers,
Ulrich
Try reading line by line as string and convert string to number using tonumber()
repeat
print("Input number!")
num = tonumber(io.read())
print('Would you like do to this again? (y/n)')
again = io.read()
until again == 'n'
While debugging, I see that second io.read is using the buffer started just after your number ends.
Your code with some more prints
repeat
print("Input number!")
-- num = tonumber(io.read())
num = io.read('*n')
print('you entered-> ' .. tostring(num))
print('Would you like do to this again? (y/n)')
again = io.read()
print('your choise from (y/n)-> ' .. again)
until again == 'n'
output
Input number!
234
you entered-> 234
Would you like do to this again? (y/n)
your choise from (y/n)->
Input number!
234y
you entered-> 234
Would you like do to this again? (y/n)
your choise from (y/n)-> y
Input number!
234234n
you entered-> 234234
Would you like do to this again? (y/n)
your choise from (y/n)-> n
This description is from Programming in Lua: 21.1
The call io.read("*number") reads a number from the current input file. This is the only case where read returns a number, instead of a string. When you need to read many numbers from a file, the absence of the intermediate strings can make a significant performance improvement. The *number option skips any spaces before the number and accepts number formats like -3, +5.2, 1000, and -3.4e-23. If it cannot find a number at the current file position (because of bad format or end of file), it returns nil.
Please apologize for the poor description.

How to use "in" operator for alphabets while looping in python?

I am trying the Following question:
A website requires the users to input username and password to register.
Write a program to check the validity of password input by users.
Following are the criteria for checking the password:
At least 1 letter between [a-z]
At least 1 number between [0-9]
At least 1 letter between [A-Z]
At least 1 character from [$##]
Minimum length of transaction password: 6
Maximum length of transaction password: 12
Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma.
Example If the following passwords are given as input to the program:
ABd1234#1,a F1#,2w3E*,2We3345 Then, the output of the program should
be: ABd1234#1
However for my python code:
values=input("Enter the set of passwords :")
list1=[]
list1=values.split(',')
num1=0
num2=0
num3=0
num4=0
for i in list1:
num1=len(i)
if(num1>=6 and num1<=12):
for z in i:
if (z.isupper()):
num1=1
if(z.islower()):
num2=1
if(z.isdigit()):
num3=1
if(z in ('#','$','#')) :
print(z)
num4=1
if(num1+num2+num3+num4==4):
print(i)
else:
print("passkey failed")
Why I am getting the last passkey as correct despite not passing criteria.
This is happening because your counters never get de-incremented. After the first correct passkey is processed, all will have a value of 1.
Consequent runs will succeed the final if test solely because of that.
Change your code to re-initialize inside the loop:
for i in list1:
num1 = len(i)
num2 = num3 = num4 = 0
# rest stays the same

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!")

Resources