加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 如果条件,for循环内部

发布时间:2020-12-20 11:42:54 所属栏目:Python 来源:网络整理
导读:print "Select the action you want to perform(A or B)"print "(A) uppper case"print "(B) count number of lines"option = raw_input("Enter your option(A or B):")if option.upper() == "A": for line in x: line = line.upper() print lineelif option
print "Select the action you want to perform(A or B)"
print "(A) uppper case"
print "(B) count number of lines"

option = raw_input("Enter your option(A or B):")

if option.upper() == "A":
    for line in x:
        line = line.upper()

    print line


elif option.upper() == "B":
    for line in x:
        line = line.upper()
        count = count + 1
    print "total lines:",count

else:
    print "incorrect option"
    exit()

当用户输入A时,它只打印大写的一行(最后一行)而不是250行.

计数完美.

附:我还没有提交用于输入要打开的文件名的代码的第一部分.

解决方法

只需将您的print语句缩进为:

if option.upper() == "A":
    for line in x:
        line = line.upper()

        print line

在Python中,缩进起着非常重要的作用,通过缩进print语句(就像它在给定的代码中一样),解释器会在for循环之外考虑它,并且它将在完成执行for循环后仅执行一次.

为了在for循环的每次迭代中执行printstatement,你需要在for循环的范围内缩进它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读