[英]How can I keep prompting the user for input until the user enters an integer and non-0 value on Python using While loop?
[英]How to validate a string input in python using datetime library and keep prompting user for input until valid input?
我试过使用这个过程:
import datetime
date_string = input()
format = "%Y-%m-%d"
try:
datetime.datetime.strptime(date_string, format)
print("This is the correct date string format.")
except ValueError:
print("This is the incorrect date string format. It should be YYYY-MM-DD")
当我用“2021-3-3”填充 date_string 的输入时,output 是
This is the correct date string format.
但是当我对“2021-03-03”做一点改动时,output 是
This is the incorrect date string format. It should be YYYY-MM-DD
我如何使第二个输入为真。 所以,当我输入“2021-03-03”时,output 也将是
This is the correct date string format.
我也想知道如何提示用户,直到他输入正确的格式,这样当他输入错误的格式或值时,output 是
This is the incorrect date string format, try again fill the
并且,程序不断提示用户输入
此代码适用于我的机器,如果不成功,它会提示用户再次输入。
import datetime
format = "%Y-%m-%d"
while(True):
date_string = input("> ").strip()
try:
datetime.datetime.strptime(date_string, format)
print("This is the correct date string format.")
break
except ValueError:
print("This is the incorrect date string format. It should be YYYY-MM-DD")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.