[英]How to write an input asking the user to type using both letters and numbers?
I am writing a line where I ask the user to input their school ID, which requires both letters and numbers. 我正在写一条线,我要求用户输入他们的学校ID,这需要字母和数字。 How can I do this? 我怎样才能做到这一点? When I input a number as my answer when asked, my program works. 当我被问到时,当我输入一个数字作为我的答案时,我的程序可行 If I type a letter with the number I get the error. 如果我输入一个带有数字的字母,我就会收到错误。 Here is my code thus far using Python 3.6 IDLE: def main():
到目前为止,我的代码是使用Python 3.6 IDLE: def main():
#Introduction
print ("Welcome to my program!\n")
#Variables with starting values waiting for user input
studentid = ""
gpa = 0.0
classnumber = ""
#Prompt for studentID
studentid = eval(input("Please enter your student ID: "))
#Prompt for GPA
gpa = eval(input("Please enter your GPA: "))
#Prompt for classnumber
classnumber = eval(input("Please enter your class information:"))
#display the users information
#StudentID: C100556789
#GPA: 4.0
#Class: COP1000
print ("\nStudent ID:\t", studentid)
print ("GPA:\t", gpa)
print ("Class information:\t", classnumber)
And here is my error: 这是我的错误:
Type "copyright", "credits" or "license()" for more information.
>>> RESTART: C:\Users\Rene Delgado\Documents\School\Fall 2018\School Code\Student Program.py
>>> main() Welcome to my program!
Please enter your student ID: C100556789 Traceback (most recent call
last): File "<pyshell#0>", line 1, in <module>
main() File "C:\Users\Rene Delgado\Documents\School\Fall 2018\School Code\Student Program.py", line 18, in main
studentid = eval(input("Please enter your student ID: ")) File "<string>", line 1, in <module> NameError: name 'C100556789' is not
defined
input
returns a string that the user inputs, which is what you want already. input
返回用户输入的字符串,这是您想要的。 You should not use eval
to evaluate the string as a Python expression, which would generate an error for an input with letters because Python would interpret it as a variable name that does not exist. 您不应该使用eval
将字符串计算为Python表达式,这会为带有字母的输入生成错误,因为Python会将其解释为不存在的变量名称。 Simply remove calls to eval
and your code would work: 只需删除对eval
调用,您的代码就可以运行:
#Prompt for studentID
studentid = input("Please enter your student ID: ")
#Prompt for GPA
gpa = input("Please enter your GPA: ")
#Prompt for classnumber
classnumber = input("Please enter your class information:")
Note that if you want to treat gpa
as a number for numeric operations, you should also convert the input to a floating number with float()
: 请注意,如果要将gpa
视为数字运算的数字,还应使用float()
将输入转换为浮点数:
gpa = float(input("Please enter your GPA: "))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.