重复,直到完成

问题描述 投票:0回答:1

所以我有这段代码,我想让它重复,直到用户让他的用户名不以符号或数字开头。

  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')
python repeat goto
1个回答
0
投票

如果你使用的是 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

1
投票

我还没有测试过这段代码,但似乎你只需要一个简单的while循环,就像这样。

surname = input("surname")
while not surname[0].isalpha():
    print("surname must start with a letter")
    surname = input("surname")

0
投票

You are close:

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')
© www.soinside.com 2019 - 2024. All rights reserved.