我想在文本文件

时间:2017-09-11 21:26:13

标签: python

我的任务是创建一个函数,询问用户的姓名,年龄,性别和城市。之后我们必须从python创建一个文本文件,并以这种形式插入用户给出的答案:

   ÂGE : (user answer) ANS
   SEXE : M/F
   VILLE :( user answer)

我决定写这样的代码:

nom=input("Quel est votre nom ?")
age=input(" Quel est votre age ?")
sex=input("Quel est votre sexe ? ")
ville=input("Où résidez-vous ?")


def asv(nom,age,sex,ville):
    n=str(nom)
    a=str(age)
    s=str(sex)
    v=str(ville)

    return(n,a,s,v)

    fichier=open("ASV.txt","w")
    #fichier.write("Âge :" ++ "ans") #This is where I need help
    fichier.close()

我似乎无法理解如何写这个。我做了一些研究,其中大部分讨论了循环,我还没有看到。

1 个答案:

答案 0 :(得分:1)

您只需要使用所需的标签附加变量的字符串形式。例如:

fichier.write("Âge :" + age)
fichier.write("SEXE :" + sex)
...

您从未将输入转换为任何其他值,因此您仍然可以使用字符串形式。你不需要转换它们。仅具有将四个输入值转换为字符串的功能通常是浪费精力。

另外,请确保您使用的是正确的变量。对于您发布的代码,我认为您只需要本地变量:

def asv():
    nom=input("Quel est votre nom ?")
    age=input(" Quel est votre age ?")
    sex=input("Quel est votre sexe ? ")
    ville=input("Où résidez-vous ?")

    fichier=open("ASV.txt","w")
    fichier.write ...
    ...

OP评论后编辑

Puis,雇员没有功能。 Peut-etre ......

def ecriver(nom,age,sex,ville):
        fichier=open("ASV.txt","w")
        fichier.write ...
        ...

# Main program

nom=input("Quel est votre nom ?")
age=input(" Quel est votre age ?")
sex=input("Quel est votre sexe ? ")
ville=input("Où résidez-vous ?")

ecriver(nom,age,sex,ville)

我把剩下的细节留给学生。

相关问题