Printing only 1's and 0's

Question:

Link to the flowchart i made

I want to make a program that accepts a string of 1’s and 0’s. It should output ‘ is valid’ if and only if the string starts with 1, the second with 0, and the last be 1. The string can be of any length. If the string does not follow the conditions and is composed of letters or special characters, the program should state that is invalid. This is my coded version of this and it prints invalid when i type 101 and when i typed 10 it is valid.

x = str(input('Enter numbers: '))

if x == '10':
   print('string is valid')

else:
   print('Invalid Input')
Asked By: ned

||

Answers:

You can use regex and suit the pattern to your exact needs:

import re

pattern = "10[01]*1$"

s = "101101"

match = re.match(pattern=pattern, string=s)

if match:
    print("valid")
else:
    print("not valid")
Answered By: matszwecja

Here:

x = str(input('Enter numbers: '))

if x.startswith("10") and x.endswith("1"):
   print('string is valid')

else:
   print('Invalid Input')

or

x = str(input('Enter numbers: '))

if x[0] == "1" and x[1] == "0" and x[-1] == "1":
   print('string is valid')

else:
   print('Invalid Input')
Answered By: rafathasan

This is checking that first characters are 1 and 0, checking last one is 1 and the string does contain only 0 or 1 characters.

x = str(input('Enter numbers: '))

if x.startswith('10') and x.endswith('1') and all(letter in '01' for letter in x):
   print('string is valid')

else:
   print('Invalid Input')
Answered By: ErnestBidouille
user_input = input('Enter numbers: ')

if any(x not in '10' for x in user_input):
   print('You must enter a sequence of 1s and 0s only.')
elif user_input.startswith('10') and user_input.endswith('1'):
   print('All is well')
else:
   print('The number entered must start with a 10 and end with a 1')
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.