python-3.x 如何将用户输入放入此代码?[duplicate]

yrdbyhpb  于 2022-12-20  发布在  Python
关注(0)|答案(2)|浏览(87)
    • 此问题在此处已有答案**:

How to read keyboard input?(5个答案)
how to get certain words from user input(3个答案)
2天前关闭.

class Student:
    def __init__(self, first, last, age, major):
        self.first = first 
        self.last = last
        self.age = age
        self.major = major
        self.courses = [] 
    
    def profile(self):
        print("Student name", self.first, ' ', self.last)
        print("Student age:", self.age)
        print(f"Major: {self.major}")
        
        
    def enrol(self, course):
        self.courses.append(course)
        print("enrolled ", self.first," in", course)
        
    
    def show_courses(self):
        print(f"{self.first + ''  + self.last} is taking the following courses")
        for course in self.courses:
            print(course)
        
                
s = Student('Sally', 'Harris', 20, 'Biology') # how do I get user input?
    
s.enrol('Biochemistry I')    

s.enrol('Literature')    

s.enrol('Mathematics')

s.show_courses()

基本上,我想问用户's'firstlastagemajor是什么。
我只知道如何在参数括号中输入数据,有没有办法为这些数据编写一个用户输入行?

wecizke3

wecizke31#

您可以通过input()方法执行此操作:

firstName = input("First name: ")
lastName = input("Last name: ")
age = int(input("Age: "))
major = input("Major: ")

s = Student(firstName, lastName, age, major)

注意age是如何被类型转换成整数的,这是因为input()返回一个字符串形式的值。

gupuwyp2

gupuwyp22#

您可以使用脚本中的以下所有指令为Student示例获取和传递输入值:

s = Student(*(input().split(',')))
...
first, last, age, major = input().split(',')
s = Student(first=first, last=last, age=age, major=major)
...
first, last, age, major = input().split(',')
s = Student(first, last, age, major)
...
student_info = input().split(',')
s = Student(*student_info)
...

在运行脚本之后(使用上述每一组指令),您在终端中输入的内容应类似于以下模式:

Sally,Harris,20,Biology

例如,下面的图像是执行此代码的示例:

相关问题