python基础-----------条件语句,循环语句

Posted A学无止境A

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python基础-----------条件语句,循环语句相关的知识,希望对你有一定的参考价值。

一、Python语句判断

Python条件语句是通过一条或多条语句执行结果(True或False)来决定执行的代码块,执行逻辑和shell一样,只是格式有些区别
可以通过下图简单了解语句的执行过程

Python程序语言指定任何非0和非空(null)值为true,0或者null为false.

if 判断条件:
    执行语句……
else:
    执行语句……

二、if条件判断

用法:类似shell,也有if嵌套
if 判断条件1:
执行语句1……
elif 判断条件2:
执行语句2……
elif 判断条件3:
执行语句3……
else:
执行语句4……

示例:
- Example4,狗的年龄计算判断

age = int(input("请输入你家狗狗的年龄:"))
print("")
if age <= 0:
    print("狗狗还没出生")
elif age == 1:
    print("相当于14岁的人")
elif age == 2:
    print("相当于22岁的人")
elif age > 2:
    human = 22 + (age -2)*5
    print("对应人类年龄:",human)
### 退出提示
input("点击enter键退出"

- Example 登录案例

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import getpass

username = input(‘请输入用户名: ‘)
password = input(‘请输入密码: ‘)
#假如不显示密码
#password = getpass.getpass(‘请输入密码: ‘)

if username == ‘admin‘ and password == ‘admin‘:
    print(‘登录成功!‘)
else:
    print(‘登录失败!‘)

- Example 猜数字

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import random

answer = random.randint(1, 100)
counter = 0

while True:
    counter += 1
    number = int(input(‘请输入一个数字: ‘))
    if number < answer:
        print(‘小了‘)
    elif number > answer:
        print(‘大了‘)
    else:
        print(‘恭喜你猜对了!‘)
        break

print(‘你总共猜了%d次‘ % counter)
if counter > 7:
    print(‘建议你回去再念一遍小学吧~‘)

- Example 计算月收入实际到手收入

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

"""
输入月收入和五险一金计算个人所得税
"""
salary = float(input(‘本月收入: ‘))
insurance = float(input(‘五险一金: ‘))
diff = salary - insurance - 3500

if diff <= 0:
    rate = 0
    deduction = 0
elif diff < 1500:
    rate = 0.03
    deduction = 0
elif diff < 4500:
    rate = 0.1
    deduction = 105
elif diff < 9000:
    rate = 0.2
    deduction = 555
elif diff < 35000:
    rate = 0.25
    deduction = 1005
elif diff < 55000:
    rate = 0.3
    deduction = 2755
elif diff < 80000:
    rate = 0.35
    deduction = 5505
else:
    rate = 0.45
    deduction = 13505
tax = abs(diff * rate - deduction)

print(‘个人所得税: ¥%s元‘ % tax)
print(‘实际到手收入: ¥%.2f元‘ % (salary - insurance - tax))

2.1 if多条件判断

当if有多个条件时可使用括号来区分判断的先后顺序,括号中的判断优先执行,此外 and 和 or 的优先级低于>(大于)、<(小于)等判断符号,即大于和小于在没有括号的情况下会比与或要优先判断。

num = 9
if num >= 0 and num <= 10:    # 判断值是否在0~10之间
    print (‘hello‘)
# 输出结果: hello
 
num = 10
if num < 0 or num > 10:    # 判断值是否在小于0或大于10
    print (‘hello‘)
else:
    print (‘undefine‘)
# 输出结果: undefine
 
num = 8
# 判断值是否在0~5或者10~15之间
if (num >= 0 and num <= 5) or (num >= 10 and num <= 15):    
    print (‘hello‘)
else:
    print (‘undefine‘)
# 输出结果: undefine

三、while循环

While 语句时还有另外两个重要的命令continue,breadk来跳过循环,continue用于跳过该次循环,break则用于退出循环,此外“判断条件”还可以是个常值,表示循环必定成立,具体用法如下:

while循环用法:
while 条件:
代码块(循环体)
执行流程:
1. 判断条件是否为真. 如果真. 执行代码块
2. 再次判断条件是否为真......
3. 当条件为假.执行else 跳出循环. 循环结束

示例:Example1

count = 0
while (count < 9):
    print(count,"The count is:"),count
    count = count + 1
print(‘Good bye!‘)

0 The count is:
1 The count is:
2 The count is:
3 The count is:
4 The count is:
5 The count is:
6 The count is:
7 The count is:
8 The count is:
Good bye!

3.1 其他场景示例

While 语句时还有另外两个重要的命令continue,breadk来跳过循环,continue用于跳过该次循环,break则用于退出循环,此外“判断条件”还可以是个常值,表示循环必定成立
具体用法如下:

count = 0
while (count < 9):
    count = count + 1
    if count%2 > 0: # 非双数时跳过输出
        continue
    print(count)
print(‘Good bye!‘)

count = 0
while (count < 9):
    count = count + 1
    if count > 4:	# 当count大于4跳出循环.
        break
    print(count)
print(‘Good bye!‘)
  • 无限循环
var = 1
while var == 1:
    num = input(‘Enter a number ‘)
    print("You enterd:",num)
print("Good bye!")

You enterd: 
Enter a number
You enterd: 
Enter a number
You enterd: 
Enter a number
You enterd: 
Enter a number
You enterd: 
Enter a number
  • 循环使用else语句
count = 0
while count < 5:
   print (count, " is  less than 5")
   count = count + 1
else:
   print (count, " is not less than 5")

0  is  less than 5
1  is  less than 5
2  is  less than 5
3  is  less than 5
4  is  less than 5
5  is not less than 5
  • 简单语句组
flag = 1
while (flag): print (‘Given flag is really true!‘)
print("Good bye!")

四、for循环

Python for循环可以便利任何序列的项目,如一个列表或者一个字符串
for循环用法:

示例:
for letter in ‘python‘:
    print(‘当前字母:‘,letter)

fruits = [‘banana‘,‘apple‘,‘mango‘]
for fruits in fruits:
    print (‘当前水果:‘,fruits)

print("Good bye!")

# 当前实例运行结果为:

当前字母: p
当前字母: y
当前字母: t
当前字母: h
当前字母: o
当前字母: n
当前水果: banana
当前水果: apple
当前水果: mango
Good bye!

4.1 通过序列索引迭代

以下实例我们使用了内置函数len()和range()函数len()返回列表的长度,即元素的个数,range返回一个序列的数

示例:
fruits = [‘banana‘,‘apple‘,‘mango‘]
for index in range(len(fruits)):
    print (‘当前水果:‘,fruits[index])

print("Good bye!")

当前水果: banana
当前水果: apple
当前水果: mango
Good bye!

五.PASS语句

Python pass是空语句,是为了保持程序结构的完整性
Pass不做任何事情,一般用作占位语句
最小的类
Python语言pass语句语法格式如下

    pass

# Example
for letter in ‘python‘:
    if letter == ‘h‘:
        pass
        print (‘这是pass块‘)
    print("当前字母:",letter)
print("Good bye!")

# 上面实例运行结果为:
当前字母: p
当前字母: y
当前字母: t
这是pass块
当前字母: h
当前字母: o
当前字母: n
Good bye!
  • Exapmle最小的类
class MyEmptyClass:
	pass
  • Example1 打印一个质数
for num in range(10,20):
    for i in range(2,num):
        if num%i == 0:
            j=num/i
            print("%d 等于%d * %d" % (num,i,j))
            break
    else:
        print(num)

10 等于2 * 5
11
12 等于2 * 6
13
14 等于2 * 7
15 等于3 * 5
16 等于2 * 8
17
18 等于2 * 9
19
  • Example2 计算1000以内被7整除的前20个数
count = 0
for i in range(0,1000,7):
    print(i)
    count += 1
    if count >= 20:
        break
  • Example3 给定一个不超过5位的正整数,判断其有几位,依次打印个数,十位数,百位数,千位数.万位数

  • 打印等腰三角形

rows = 10
for i in range(0, rows):
    for k in range(0, rows - i):
        print ("*",end="") #注意这里的",",一定不能省略,可以起到不换行的作用
        k += 1
    i += 1
    print ()
  • 打印空心菱形
rows = 10
for i in range(rows):
    for j in range(rows - i):
        print(" ", end=" ")
        j += 1
    for k in range(2 * i - 1):
        if k == 0 or k == 2 * i - 2:
            print("*", end=" ")
        else:
            print(" ", end=" ")
        k += 1
    print ("
")
    i += 1
    #  菱形的下半部分
for i in range(rows):
    for j in range(i):
        #  (1,rows-i)
        print(" ", end=" ")
        j += 1
    for k in range(2 * (rows - i) - 1):
        if k == 0 or k == 2 * (rows - i) - 2:
            print("*", end=" ")
        else:
            print(" ", end=" ")
        k += 1
    print("
")
    i += 1





















以上是关于python基础-----------条件语句,循环语句的主要内容,如果未能解决你的问题,请参考以下文章

python中的单向循环链表实现

python基础-----------条件语句,循环语句

python小白之路(控制语句二)

[python基础]条件和条件语句

python基础之条件循环语句

Python基础-条件语句(判断)