Home > Mobile >  Printing only 1's and 0's
Printing only 1's and 0's

Time:10-20

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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')
  • Related