Bootstrap

小白学python之运算符和if判断语句

小白学python之运算符和if判断语句

1.数据类型转换

知识点:

转换整数格式: int(x)

转换小数格式: float(x)

转换字符串格式: str(x)

示例:

# 从键盘输入苹果的价格、重量、输出:苹果单价9.00元/斤,购买了5.00元/斤,需要支付45.00元
# 方法一:
print('苹果单价9.00元/斤,购买了5.00元/斤,需要支付45.00元')
print('-' * 25)
# 方法二:采用占位符输出
price = 9.00
weight = 5.00
money = 45.00
print('苹果单价%.2f元/斤,购买了%.2f元/斤,需要支付%.2f元' % (price, weight, money))
print('-' * 25)
# 方法三,通过input函数录入
price = float(input('请输入你的单价'))
weight = float(input('请输入重量'))
money = price * weight
print('苹果单价%.2f元/斤,购买了%.2f元/斤,需要支付%.2f元' % (price, weight, money))

# 总结: %.2f详细解读:%代表占位,.2表示数据长度到小数点后两位,f代表浮点数

2.运算符

知识点:

+ - * /  : 加 减 乘 除

// : 取商

%  : 取余

** : 次幂

= : 赋值

复合赋值运算符: +=   -=    *=   /=    //=    %=    **=



示例:

# 算术运算符:+ - * / // %  **
a = 10
b = 3
print(a / b)  # 3.3333333333333335

# 复制快捷键: ctrl + D
# 格式化快捷键: ctrl+alt+L
print(10 + 3)  # 13
print(10 - 3)  # 7
print(10 * 3)  # 30
print(10 / 3)  # 3.3333333333333335
print(10 // 3)  # 3
print(10 % 3)  # 1
print(10 ** 3)  # 1000

3.比较和逻辑运算符

知识点:

比较运算符: == > >= < <= !=

逻辑运算符: and or not

注意: 表达式结果都是True或者False

示例:

# 比较运算符:> < >= <= == !=
# 逻辑运算符:and or not

# 需求:已知用户名为‘tyh’,密码为'123456',用键盘录入用户名和密码,判断是否登录成功

name = 'tyh'
password = '123456'

temp_name = input('请输入你的用户名')
temp_password = input('请输入你的密码')

if temp_name == name and temp_password == password:
    print('登录成功')
else:
    print('账号或者密码错误')

4.if语句

示例

# 需求:判断年龄是否有18岁,若是大于等于18则可进入上网,若是小于18则回家写作业

# age = int(input('请输入年龄'))
age = 10
if age >= 18:
    print('老油条,请进入上网')
else:
    print('小屁孩,滚回去写作业')

print('-' * 25)

# 需求:用键盘录入分数,100到90为优秀,89到80为中等,79到60为良好,60以下为不及格,其余数据为无效数据
# 普通版
grade = int(input('请输入你的成绩'))
if grade > 100 or grade < 0:
    print('无效成绩')
elif grade >= 90 and grade <= 100:
    print('优秀')
elif grade >= 80 and grade < 90:
    print('中等')
elif grade >= 60 and grade < 80:
    print('良好')
else:
    print('不及格')

# 优化版
# grade = int(input('请输入你的成绩'))
# if grade > 100 or grade < 0:
#     print('无效成绩')
# elif grade >= 90:
#     print('优秀')
# elif grade >= 80:
#     print('中等')
# elif grade >= 60:
#     print('良好')
# else:
#     print('不及格')
# print('-' * 25)

5.人机猜拳游戏

示例:

#      综合案例,猜拳游戏:

import random

# 导入随机函数
computer = random.randint(1, 3)
#   用变量接收随机数,方便验证是否随机
print(computer)
player = eval(input('请出拳,(1)拳头,(2)剪刀,(3)布:'))
if player >= 1 and player <= 3:
    if computer == player:
        print('棋逢对手,势均力敌')
    elif (computer == 1 and player == 3) or (computer == 2 and player == 1) or (computer == 3 and player == 2):
        print('人类获胜')
    else:
        print('机器获胜')
else:
    print('请睁大眼睛看要求')

6.while循环

示例:

# 采用while循环方式求解
i = 1
sum = 0
while i <= 100:
    if i % 2 == 0:
        sum += i
    i += 1
print(sum)

print('-' * 25)
# 采用for循环方式求解
sum1 = 0
for j in range(101):
    if j % 2 == 0:
        sum1 += j

print(sum1)

;