如何使用random.choice将用户输入随机连接到存储在数组中的字符串

问题描述 投票:-3回答:2

我需要编写一个程序,为学生自动生成唯一的用户名。用户名长度必须为六个字符。该程序应生成并显示学生用户名列表。该程序将询问要生成多少个用户名。对于每个用户名,将输入学生名字的前三个字母,然后将其与下面列表中的随机结尾相结合:Ing,end,ax,gex,goh对于名字为David的学生,技术人员将进入DAV。该程序将通过RANDOMLY将Dav添加到其中一个结尾来生成用户名。例如 - 达文。

这就是我到目前为止所有这一切,如果有人知道如何使用random.choice将学生的前3个字母随机组合到存储在数组中的结尾,我将非常感激。谢谢!

我的代码到目前为止:

#Initialising the variables
usernames=0
usernameEndings=["ing", "end", "axe", "gex", "goh"]
studentsName=""
#Getting inputs
usernames=int(input("How many ``usernames are to be generated?"))
#proccess
for counter in range(0,usernames):
    studentsName = str(input("Please enter the first three letters of students name."))
        while len(str(studentsName)) <3 or len(str(studentsName)) >3:
        studentsName= str(input("ERROR, please re-enter the first three letters of students name."))
python loops validation random pseudocode
2个回答
0
投票

我在您的代码中进行了一些小的样式调整,纠正了缩进错误,并添加了您缺少的行。如果不需要存储用户名,程序可以依次打印出每个用户名:

import random

#Initialising the variables 
usernames = 0
usernameEndings = ["ing", "end", "axe", "gex", "goh"]
studentsName = ""
#Getting inputs
usernames=int(input("How many usernames are to be generated?"))
#process
for counter in range(0,usernames):
    studentsName = str(input("Please enter the first three letters of students name."))
    while len(str(studentsName)) != 3:
        studentsName = str(input("ERROR, please re-enter the first three letters of students name."))
    print('Your username is {}'.format(studentsName[:3] + random.choice(usernameEndings)))

输出:

How many usernames are to be generated?2
Please enter the first three letters of students name.ali
Your username is aligoh
Please enter the first three letters of students name.bob
Your username is bobaxe

0
投票

非常感谢所有人帮助我真的很感激。它帮助我完成了我的项目。这是我放在一起的代码。

#Initialising the variables
usernames=0
usernameEndings=["ing", "end", "axe", "gex", "goh"]
studentsName=""

#Getting inputs
usernames=int(input("How many usernames are to be generated?"))

#proccess
for counter in range(0,usernames):
    studentsName = str(input("Please enter the first three letters of students name."))
    while len(str(studentsName)) != 3:     
        studentsName= str(input("ERROR, please re-enter the first three letters of  students name."))
    import random
    print((str(studentsName))+random.choice(usernameEndings))

#end of program    
© www.soinside.com 2019 - 2024. All rights reserved.