Learn python with socratica [My notes] - part 9- If/Then/Else

Lesson 11

写代码当时候,避免不了的就是循环结构,如果到flag条件,则执行,如果到跳转条件,则跳转到另一个块继续执行。关键词:if,else,then。下面举一个if-then的例子[ipython 不能运行整个代码文件,所以没有输入输出的实验效果,建议在]:

    # collect string / test length
    
    input = raw_input("Please enter a test string: ")
    
    if len(input)<6: #注意冒号和缩紧
        print("Your string is really short.")
        print("please enter a string with at least 6 characters")

将代码保存为python 文件if_then.py,使用命令行执行:

    >>> python if_then.py
    > Please enter a test string:ace # for example
        Your string is too short.
        Please enter a string with at least 6 characters.
        
    > Please enter a test string:mission # this will return true, so no if.

下面我们开始一段新的代码:

    # Prompt user to enter number / test if even or odd
    
    input = raw_input("Please enter an integer:")
    number = int(input)
    
    if number % 2 == 0:
        print("Your number is even.")
    else:
        print("Your number is odd.")

将代码保存为python 文件if_then_2.py,使用命令行执行:

    >>> python if_then_2.py
    > Please enter an integer: 17
        Your number is odd.
    >>> python if_then_2.py
    > Please enter an integer: 50
        Yout number is even.

下面我们做一个小实验:三角形的判断。

    # Scalene triangle: All sides have different lengths.
    # Isosceles triangle: Two sides have the same length.
    # Equilateral triangle: All sides are equal.
    
    a = int(raw_input("The length of side a = "))
    b = int(raw_input("The length of side b = "))
    c = int(raw_input("The length of side c = "))
    
    if a != b and b != c and a != c:
        print("This is a scalene triangle.")
    elif a == b and b == c: # elif = else if
        print("This is an equilateral triangle.")
    else:
        print("This is an isosceles triangle.")

将代码保存为python 文件if_then_3.py,使用命令行执行:

    >>> python if_then_3.py
    > The length of side a = 3
    > The length of side b = 4
    > The length of side c = 5
    This is a scalene triangle.

这个实验就是已知三条边的长度,判断三角型的类型:等边三角形,等腰三角形。if/then/else的这种循环结构,需要在实际使用中慢慢掌握。

Youtube source:
https://www.youtube.com/watch?v=bY6m6_IIN94&list=PLi01XoE8jYohWFPpC17Z-wWhPOSuh8Er-

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IndexFziQ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值