重复直到完成
Repeating until done
所以我得到了这段代码,我想让它自己重复,直到用户让他的用户名不以符号或数字开头。
name=name.capitalize()
print(name)
surname= input("surname")
surname=surname.capitalize()
print(surname)
password= input("password")
username= input("username")
first_char = username[0]
if first_char.isalpha():
print('done')
else: print('username must start with a letter')
我还没有测试过这段代码,但似乎您只需要一个简单的 while 循环,如下所示:
surname = input("surname")
while not surname[0].isalpha():
print("surname must start with a letter")
surname = input("surname")
你很接近:
name = input("Name:").capitalize()
print(name)
surname = input("Surname:").capitalize()
password = input("Password:")
username = input("Username:")
while not username[0].isalpha():
print('Done')
选择:
name, surname, password, username = input("Name:").capitalize(), input('Surname:').capitalize(), input('Password'), input('Username')
while not username[0].isalpha():
print('Username must start with a letter')
print('Done')
如果你使用的是 python 3.8,你可以使用 :=
操作符来写这个:
while not (username := input("username: "))[0].isalpha():
print('username must start with a letter')
# do stuff
否则你的选择将是:
(a) 重复一行代码
username = input("username: ")
while not username[0].isalpha():
print('username must start with a letter')
username = input("username: ")
# do stuff
或 (b) 使用 break
:
的无限外观
while True:
username = input("username: ")
if username[0].isalpha():
break
print('username must start with a letter')
# do stuff
所以我得到了这段代码,我想让它自己重复,直到用户让他的用户名不以符号或数字开头。
name=name.capitalize()
print(name)
surname= input("surname")
surname=surname.capitalize()
print(surname)
password= input("password")
username= input("username")
first_char = username[0]
if first_char.isalpha():
print('done')
else: print('username must start with a letter')
我还没有测试过这段代码,但似乎您只需要一个简单的 while 循环,如下所示:
surname = input("surname")
while not surname[0].isalpha():
print("surname must start with a letter")
surname = input("surname")
你很接近:
name = input("Name:").capitalize()
print(name)
surname = input("Surname:").capitalize()
password = input("Password:")
username = input("Username:")
while not username[0].isalpha():
print('Done')
选择:
name, surname, password, username = input("Name:").capitalize(), input('Surname:').capitalize(), input('Password'), input('Username')
while not username[0].isalpha():
print('Username must start with a letter')
print('Done')
如果你使用的是 python 3.8,你可以使用 :=
操作符来写这个:
while not (username := input("username: "))[0].isalpha():
print('username must start with a letter')
# do stuff
否则你的选择将是:
(a) 重复一行代码
username = input("username: ")
while not username[0].isalpha():
print('username must start with a letter')
username = input("username: ")
# do stuff
或 (b) 使用 break
:
while True:
username = input("username: ")
if username[0].isalpha():
break
print('username must start with a letter')
# do stuff