简体   繁体   English

为什么我的代码跳到最后而忽略了我的部分代码?

[英]Why does my code skip to the end and ignore parts of my code?

Here is the code: 这是代码:

print "Welcome to the Database!"

print "Simply type the correponding number to start!"

print """

    1. Add a Student...

    2. Search for a Student...

    3. Edit a Student's Information...

    4. Delete a Student...

    5. Exit...
"""

datab = raw_input("What would you like to do?")

if datab == 1:
    dtabs = open("database.txt", "w")
    que = raw_input("What's the student's name?")
    dtabs.write(que)
    dtabs.close()

    ttrgrp = raw_input("Which tutor group do they belog to?")

When I run it in Terminal it prints the what would I like to do but then once an input is taken in the program closes. 当我在Terminal中运行它时,它会打印我想做的事情,但是一旦在程序中输入了内容,它就会关闭。

raw_input() returns a string , but you are comparing against an integer. raw_input()返回一个字符串 ,但是您正在与一个整数进行比较。 Python will not coerce strings when comparing: 比较时,Python不会强制字符串:

>>> '1' == 1
False

Compare against a string here: 与此处的字符串进行比较:

if datab == '1':

as this simplifies validation. 因为这简化了验证。

Everything inside of your if statement is being skipped, as datab will never be equal to 1 in its integer form. if语句中的所有内容都将被跳过,因为datab的整数形式永远不会等于1。 raw_input() will return the value string. raw_input()将返回值字符串。 Change your if statement to accept 1 as a string: 更改您的if语句以接受1作为字符串:

if datab == '1':
    #do something

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM