- 学习前仪式
print("hello word!")
ps: 熟练各种语言的hello world书写, 嘻嘻 - 注释
单行注视:# 被注释内容
多行注释:""" 被注释内容 """
或者'''被注释内容'''
- 变量
变量定义的规则:
变量名只能是 字母、数字或下划线的任意组合
变量名的第一个字符不能是数字
以下关键字不能声明为变量名
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
代码
# Author:Scott She
name = "Scott She"
name2 = name
print("My name is ", name, ", again, my name is ", name2)
name = "马云"
print(name, name2)
# 单引号和双引号基本一样, 三个单(或双)引号还能打印多行, 也可以注释多行
lines = """
name = "马云"
print(name, name2)
"""
print(lines)
打印
- 用户输入及字符串格式化
代码
# Author:Scott She
name = input("name ")
age = int(input("age "))
job = input("job ")
salary = float(input("salary "))
print(type(name), type(age), type(job), type(salary))
info1 = """
---------------- info of %s ------------------
Name: %s
Age: %d
Job: %s
Salary: %.1f
""" % (name, name, age, job, salary)
print(info1)
info2 = '''
---------------- info of {_name} ------------------
Name: {_name}
Age: {_age}
Job: {_job}
Salary: {_salary}
'''.format(_name=name,
_age=age,
_job=job,
_salary=salary)
print(info2)
info3 = '''
---------------- info of {0} ------------------
Name: {0}
Age: {1}
Job: {2}
Salary: {3}
'''.format(name,
age,
job,
salary)
print(info3)
# 以上三种字符串格式化, 一般都会用第二种
打印
- if 语句及密文
代码
# Author:Scott She
import getpass # 模块
_username = "scott"
_password = "666666"
username = input("username ")
password = getpass.getpass("password ") # 注意, 该方法在PyCharm中不能运行,可以用终端测试
if _username == username and _password == password:
print("Wellcom {name} login...".format(name=username))
else:
print("Invalid username or password!")
终端测试
- 循环语句
# Author:Scott She
age_of_scott = 25
# while循环
'''
count = 0
while count < 3:
guess_age = int(input("age "))
if guess_age == age_of_scott:
print("yes, you got it")
break
elif guess_age > age_of_scott:
print("think smaller...")
else:
print("think bigger...")
count += 1
else:
print("you have tried too many... fuck off")
'''
# for循环
'''
for i in range(3):
guess_age = int(input("age "))
if guess_age == age_of_scott:
print("yes, you got it")
break
elif guess_age > age_of_scott:
print("think smaller...")
else:
print("think bigger...")
else:
print("you have tried too many... fuck off")
'''
# for循环详解
'''
类似于其他语言中的
for (int i = 0; i < 10; i+=2) {
print(i)
}
'''
for i in range(0, 10, 2):
print(i)
count = 0
while count < 3:
guess_age = int(input("age "))
if guess_age == age_of_scott:
print("yes, you got it")
break
elif guess_age > age_of_scott:
print("think smaller...")
else:
print("think bigger...")
count += 1
if count == 3:
print("Do you want to keep guessing... n or N for no, others for yes: ")
continue_confirm = input()
if continue_confirm != "n" and continue_confirm != "N":
count = 0
打印
- 三元运算
result = 值1 if 条件 else 值2
如果条件为真:result = 值1
如果条件为假:result = 值2
由于简书格式原因, 代码均没有空行, 可以去这里下载我的练习代码