table of Contents
Python study notes --Day02
Today is the day to learn Python, and the content will be more than yesterday, in short, is doing would be finished.
Variables and types
In designing the program, we will use variables to store data as a carrier. The value of the variable can be read or modified, the total is stored in a memory, which is the basis of all calculations and control. Data can process a variety of a variety of data types such as numeric, text, images, audio, video, etc., so that different types of data need to distinguish between different types of definition is stored.
Python Data Type:
- digital:
-
- Integer: int type, expressed as a long integer, there python2 Long type, but this type is incorporated as python3 int type, for example:
1,123,714
- Integer: int type, expressed as a long integer, there python2 Long type, but this type is incorporated as python3 int type, for example:
-
- Float: float type, a variety of decimals, because the position of the decimal point in scientific notation can change, so that decimal floating point numbers. For example:
2.1,123.456,2.12e4
- Float: float type, a variety of decimals, because the position of the decimal point in scientific notation can change, so that decimal floating point numbers. For example:
-
- Plural type: complex type, complex type, that is, we used the plural, but by the imaginary part
i
replacedj
, for example:3+4j
- Plural type: complex type, complex type, that is, we used the plural, but by the imaginary part
-
- Boolean: bool type, which only True or False, pay attention to the first letter capitalized
- String: String types, any character by single or double quotes may be used backslash
\
escape special characters, for example"abc",'haha'
- List: List, python is the most frequently used data types. Element type list can not be the same, such as numbers, strings, lists can be used as his element, the element can be repeated use
[]
, the data elements written in square brackets, and separated by commas element, the list contains the index can also be It is intercepted, for example:[1, "haha", [1, 2, 3]]
- Tuple: Similar tuple, and a list of data elements may not be identical, elements can be repeated, except that the modified tuple element can be written in
()
, the elements separated by commas. For example:(1, 1.23, "abc")
- Collection: set, and a list of similar, but the data elements can not be repeated, the basic function is to test membership and remove duplicate elements. You can use braces
{}
orset()
create aggregate functions Note: Creating an empty set must be usedset()
instead{}
, because{}
is used to create an empty dictionary. For example:{1, 2, 3}
- Dictionary: dictionary, stored key-value pair, random key, and the key unique, immutable and must be stored. For example:
{'a': 1, 'b': 2', 'c': 3}
Variable naming
Each variable must have its name, we should do so to the variable named name known to see Italy, and have a certain specification.
- Variable name consists of letters, numbers and underscores, numbers can not begin with
- Case sensitive, uppercase
A
and lowercasea
are two different variables - The system does not use reserved words and keywords as variable names
- Lowercase letters, words may be connected to a plurality underlined
Variables
Next, the definition and use of variable by a few simple examples of small
Example 1: variable assignment, print and print their type
#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
def main():
a = 1 # 整型
b = 2.123 # 浮点型
c = "我是c" # 字符串型
d = False # 布尔型
e = 1 + 3j # 复数型
num_list = [a, b, e, [2, 4, 123]] # 列表
variable_tuple = (a, b, c, d, e, num_list) # 元组
variable_set = {a, b, a, 1, c, d} # 集合
score_dict = {'小明': 12, '张三': 34, '小红': 23} # 字典
print(a)
print("a的类型是:", type(a))
print(b)
print("b的类型是:", type(b))
print(c)
print("c的类型是:", type(c))
print(d)
print("d的类型是:", type(d))
print(e)
print("e的类型是:", type(e))
print(num_list)
print("num_list的类型是:", type(num_list))
print(variable_tuple)
print("variable_tuple的类型是:", type(variable_tuple))
print(variable_set)
print("variable_set的类型是:", type(variable_set))
print(score_dict)
print("score_dict的类型是:", type(score_dict))
if __name__ == '__main__':
main()
Using the above example, this type()
function, is to see what type of parameters passed.
Example 2: a digital arithmetic
#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
def main():
a = 13
b = 21
c = 0
print(a + b)
print(a - b)
print(a / b)
print(a * b)
print(b // a)
c += a
print("c += a", c)
c -= b
print("c -= a", c)
c *= a
print("c *= a", c)
c /= b
print("c /= a", c)
c //= a
print("c //= a", c)
print(c > a)
print(c <= b)
if __name__ == "__main__":
main()
In fact there are other operators in the future we will be 11 to use, that time also had time to talk anymore, just write a few simple examples here
Operators
Operators | description |
---|---|
[] [:] |
Subscript, sliced |
** |
index |
~ + - |
Bitwise, sign |
* / % // |
Multiply, divide, die, divisible |
+ - |
Addition, subtraction |
>> << |
Right, left |
& |
Bitwise AND |
^ \| |
Bitwise XOR Bitwise or |
<= < > >= |
Less than or equal, less than, greater than, greater than or equal |
== != |
Equal, not equal |
is is not |
Identity operator |
in not in |
Member operator |
not or and |
Logical Operators |
= += -= *= /= %= //= **= &= \|= ^= >>= <<= |
(Composite) assignment operator |
Exercise
Exercise 1
Calculate body mass index
#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description: 体重指数的计算
def main():
height = int(input("请输入你的身高(cm):").strip())
weight = int(input("请输入你的体重(kg):").strip())
# 计算标准体重
standard_weight = height- 105
print("你的体重指数为:%.2f%%" % ((weight - standard_weight) / standard_weight * 100))
if __name__ == "__main__":
main()
As used herein, the input () function, Strip () function, int () function, described do eleven, input () function reads the contents is inputted from the console, and returns a value of type String, Strip () function removing spaces to the string, int () is a function of the value of the string is converted to an int type, but must request string value must be a number, letter characters exist if exception occurs, the program terminates, the method of writing not perfect, better implementations behind us say.
English II
Currency Converter
#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description: 人民币兑换美元
def main():
count = int(input("请输入您要兑换的金额:").strip())
print("这里是您兑换的%.3f美元" % (count / 6.851))
if __name__ == "__main__":
main()
This is good simple ah, I'm a little embarrassed to impress, but the next day just beginning to learn python Well, make it too complicated is not good, this same method of writing is not perfect, better implementations behind us say.
if-elif-else statements
In Python, branched structure to be constructed, may be used if
, elif
and else
keywords used :
to write if
the example body of code, the following term used
a, b = 10, 20
if a > b:
print("a大于b")
else:
print("b大于a")
It is if-else
used in combination
a, b = 10, 20
if a > b:
print("a大于b")
This is separate if
case
if a > b:
print("a大于b")
elif a < b:
print("b大于a")
This is the if-elif
case of a combination of
a, b = 10, 20
if a > b:
print("a大于b")
elif a == b:
print("b等于a")
else:
print("a小于b")
This is the if-elif-else
case of a combination of
if exercise
Exercise three
Login authentication
#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:登录验证
def main():
username = input("请输入用户名:").strip()
password = input("请输入密码:").strip()
if username == 'admin' and password == '123456':
print("登录成功")
else:
print("用户名或密码错误")
if __name__ == "__main__":
main()
When the console input admin
and 123456
time will be printed 登录成功
, rather than when these two inputs, the print is 用户名或密码错误
. So you have to remember their own user name and password, avoid typing error. We once again this code to improve after completion of the cycle.
Exercise four
Conversion results, percentile -> hierarchy
90 points or more -> A
80 minutes to 89 minutes -> B
70 min to 79 min -> C
60 min to 69 min -> D
60 points or less -> E
#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:成绩转换,百分制->等级制
"""
90分以上 --> A
80分~89分 --> B
70分~79分 --> C
60分~69分 --> D
60分以下 --> E
"""
def main():
score = int(input("请输入你的成绩:").strip())
if 90 <= score <= 100:
grade = "A"
elif 80 <= score < 90:
grade = "B"
elif 70 <= score < 80:
grade = "C"
elif 60 <= score < 70:
grade = "D"
elif 0 <= score < 60:
grade = "E"
else:
print("请输入合理的成绩")
print("你的成绩等级是%s" % grade)
if __name__ == "__main__":
main()
cycle
There are times when we will need to do a lot of things circulating, such as repeat the statement output 10 times, or set the program per 1 minute intervals once the print operation, we can not own timing one minute to perform a print function, so we use a loop operation . Python is configured in a cyclic structure, there are two approaches, one is for-in
circular, the other is while
circular.
for-in loop
We have a container is equivalent items, take a single item inside a container, we can achieve this:
items = [1, 2, 3, 4, 5, 6]
for item in items:
print(item)
The above example is traversing the list, you can also use this method:
items = [1, 2, 3, 4, 5, 6]
for i in range(len(items)):
print(items[i])
This range is produced by a fixed function digital sequence, and then outputs a list of elements indexed by items[i]
this embodiment is a list of elements based on the index acquired. We can do a lot of things through the range functions, such as find all the numbers from 1 to 100 and
total = 0
for i in range(1, 101):
total += i
print(total)
Parameters, range function can fill out a total of three parameters, the first one is the starting position, the second position is terminated, the third step is, for example range(1, 101, 2)
, which is acquired between the odd-numbered 1-100 starting position in fact, to the end position is a closed left and right open interval [1, 101), including but not including 101 1.
while loop
If we do not know exactly to cycle several times, this time the recommended while
cycle, it is a condition of the loop control expression or bool bool value, True
the cycle continues, False
the loop terminates. Let's look at a few small examples.
Small game viewing, if guessed exit the loop, print Congratulations, you are right, wrong speculation continues
#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:while循环
import random
def main():
target_num = random.randint(0, 100)
while True:
num = input("请输入数字:").strip()
if num.isdigit():
num = int(num)
if num > target_num:
print("猜大了")
elif num < target_num:
print("猜小了")
elif num == target_num:
print("恭喜你答对了")
break
else:
print("猜错了,请重来")
if __name__ == "__main__":
main()
There while True
is an infinite loop, no loop termination condition, when answered correctly by break
otherwise been circulated in a loop out of the loop.
Exercise
A practice optimization
In a practice referred to in that part of the program may be error, if the input of letters or characters, the program will terminate, since we learned if
judge can avoid this situation happening. Plus while
cycle time until the calculation of success, as follows
#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description: 体重指数的计算优化
def main():
while True:
height = input("请输入你的身高(cm):").strip()
weight = input("请输入你的体重(kg):").strip()
if height.isdigit() and weight.isdigit():
height = int(height)
weight = int(weight)
# 计算标准体重
standard_weight = height- 105
print("你的体重指数为:%.2f%%" % ((weight - standard_weight) / standard_weight * 100))
break
else:
print("请输入正确的格式!!!")
if __name__ == "__main__":
main()
Here we add an infinite loop, the user is prompted to re-enter the enter the wrong time, only result is calculated before the end of the program. Isdigit which uses a method, which is a method for determining whether a variable of type string composed of pure numbers, return True
, no return False
, when the two inputs are judged pure when we start to digital, and print the results, out of the loop .
English II Optimization
English II optimization and a practice like learning to be giving top priority, I do not write it, but the code will be transmitted on my github, need can clone down.
Exercise Three Optimizations
In fact, that is, plus one cycle, ha ha ha, but the posted about it, I have not posted doubt yourself lazy.
#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:登录验证优化
def main():
while 1 == 1:
username = input("请输入用户名:").strip()
password = input("请输入密码:").strip()
if username == 'admin' and password == '123456':
print("登录成功")
break
else:
print("用户名或密码错误")
if __name__ == "__main__":
main()
The cycling conditions I am using the 1 == 1
identity, and the effect True
is the same. Until login is successful, otherwise, you have been prompted for a user name and password.
Exercise five
Print 99 multiplication table
#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:99乘法表
def main():
i, j = 1, 1
while i < 10:
while j < i + 1:
print("%d*%d=%d" % (i, j, i * j), end="\t")
j += 1
i += 1
j = 1
print()
# for i in range(1, 10):
# for j in range(1, i + 1):
# print("%d*%d=%d" % (i, j, i * j), end="\t")
# print()
if __name__ == "__main__":
main()
while version and the version for the two to achieve, print function default wrapping, use end='\t'
can make the end of the print function into a horizontal tab. \t
Escape character is representative of a horizontal tab. Other characters are listed in the transfer time to learn the string, so do not worry, the past will come.
Epilogue
Today a lot of content, these must be firmly grasp, is the basis of this foundation, learn every day!
If you find my articles where there is an error or have any good ideas can contact me, we study together progress together, my email address is [email protected]
let’s do more of those!