zoukankan      html  css  js  c++  java
  • MIT python 第二课最后一个例子 求整数的平方数

    上图已经y=0 i=x了,下图只写了x=-4 竟然运行不出来,写全了才行  不知道为神马
    
    
     #前面三个声明仅仅是赋值声明而已

    >>> y=0 >>> x=4 >>> i=x >>> while i>0 SyntaxError: invalid syntax >>> while i>0: y+=x i-=1 print(y) 4 8 12 16 >>> x=-4 >>> while i<0: y+=x i+=1 print(y) >>> >>> y=0 >>> x=-4 >>> i=x >>> while i<0: y+=x i+=1 print(y) SyntaxError: unexpected indent >>> y=0 >>> x=-4 >>> i=x >>> while i<0: y+=x i+=1 print(y) SyntaxError: multiple statements found while compiling a single statement >>> y=0 >>> x=-4 >>> i=x >>> while i<0: y+=x i+=1 print(y) -4 -8 -12 -16 >>>
    
    
    


    求整数的平方数
    1
    >>> y=0 2 >>> x=3 3 >>> itersLeft=x 4 >>> while itersLeft>0: 5 y=y+x 6 itersLeft=itersLeft-1 7 print(y) 8 9 10 3 11 6 12 9
    >>> while itersLeft>0:
        while itersLeft>0:         #while循环没改变变量值会一直循环
            print(y)
    
            
    >>> 
    x应该取个整数,那如果是负整数会怎么样:跳出循环
    >>> x=-4
    >>> while itersLeft>0:
        y=y+x
        itersLeft=itersLeft-1
        print(y)
    
    >>> 
    >>>  #我们知道这个程序是用来求平方数的,按理说我们可以求(-4)²即16,但程序会跳出这个循环,因此提醒:在写代码时,要明白对输入的期望,并思考下如何执行这些期望,这个例子我想确定,在进行测试前我用的是x的绝对值
    我们对x的期望值是x的绝对值
    

    >>> x=abs(-4)

    或写成这样也行:
    >>> x=-4 >>> x=abs(x)

    >>> y=0

    >>> itersLeft=x

    >>> while itersLeft>0:
    y=y+x
    itersLeft=itersLeft-1
    print(y)


    4
    8
    12
    16
    >>>

    >>> x=-4
    >>> tiersLft=abs(x)
    >>> y=0
    >>> while tiersLft>0:
    y=y+x
    tiersLft=tiersLft-1
    print(y)


    -4
    -8
    -12
    -16
    >>>

    >>> abs(x)
    4
    
    >>> x=-4
    >>> x==abs(x)
    False
    >>> x=abs(x)
    >>> x
    4

    >>> x=-2
    >>> x=abs(x)
    >>> y=0
    >>> ite=x
    >>> while ite>0:
    y=y+x
    ite=ite-1
    print(y)
    
    
    2
    4
    
    >>> x=-4
    >>> x=abs(x)
    >>> y=0
    >>> ite=x
    >>> while ite>0:
    y=y+x
    ite=ite-1
    print(y)
    
    
    4
    8
    12
    16

    >>> print(y)

      16
      >>> print(y)
      16
      >>>

  • 相关阅读:
    JAVA编程心得-JAVA实现CRC-CCITT(XMODEM)算法
    自学PHP 环境搭建
    Postfix+Amavisd-new+Spamassassin+ClamAV整合安装
    安装Apache Felix OSGI Framework小记
    C#多线程
    使用maven进行测试设置断点调试的方法
    2016第33周四
    Spring配置文件头及xsd文件版本
    2016第33周二
    web中的重定向与转发
  • 原文地址:https://www.cnblogs.com/hhj187/p/4597487.html
Copyright © 2011-2022 走看看