I'm working on a code problem where first I have to take input integer N and then take input of string of length N in python3.
2 Answers
You just need to use input to get the user input. You can put this inside a while-loop, so it keeps asking until a valid input is given. For the string you use input as well, there you could keep asking if the string given is not the right length, or just truncate the input.
# Ask for a number
while True:
try:
n = int(input("Enter number: "))
break
except ValueError:
print("Invalid input")
# Just truncate the input
value = input(f"Enter string of length {n}: ")[:n]
# Keep asking until right length
while True:
value = input(f"Enter string of length {n}: ")
if len(value) == n:
print("Valid answer")
break
print("Invalid input")
1 Comment
V2K
Thank you very much for your help.
n = int(input()and thens = input()[:n]