Putting biographical data in order from 4 parameters using python 3.3

陌路散爱 提交于 2019-12-11 07:48:33

问题


I need to create a function called student data, that takes 4 parameters, a name (a string), age (an integer), student number (a string) and whether they are enrolled in CSCA08 (a boolean), and returns a string containing that information in the following format: [student number,name,age,enrolled].

I have written the following code but it doesn't work

def student_data(name,age,number,enrolled):
    name = str()
    age = int()
    number = int()
    enrolled = bol()
    return '['+ 'number'+','+'name'+','+'age'+','+'enrolled'+']'

The code should work as follows:

>>> student_data("Vivian",32,"1234567",False)
`[1234567,Vivian,32,False]'

回答1:


The simplest solution would be this:

def student_data(name, age, number, enrolled):
    return str([name, age, number, enrolled])

The output is:

>>> student_data("Vivian",32,"1234567",False)
"['Vivian', 32, '1234567', False]"

If the ' around the name and number are a problem you could use instead this:

def student_data(name, age, number, enrolled):
    return '[' + ','.join([name, str(age), number, str(enrolled)]) + ']'

The output is then:

>>> student_data("Vivian",32,"1234567",False)    
'[Vivian,32,1234567,False]'



回答2:


This is your current function:

def student_data(name,age,number,enrolled):
 name = str()
 age = int()
 number = int()
 enrolled = bol()
 return '['+ 'number'+','+'name'+','+'age'+','+'enrolled'+']'

It should be:

def student_data(name,age,number,enrolled):
     return '['+str(number)+','+str(name)+','+str(age)+','+str(enrolled)+']'

In Python, you don't need to declare that they are string , int or bool (even if you had, your current code actually overwrites the current value with an empty string/int/bool). However, to make sure that it will be possible to "add" two strings (because you can't str to bool, string to int, etc), use str(var) that turns the var into a string.

As number,name,age and enrolled are variables, you don't need to use quotes.



来源:https://stackoverflow.com/questions/18857723/putting-biographical-data-in-order-from-4-parameters-using-python-3-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!