这是我从零开始学python的第一周。在之前通过C++接触过编程,当时学得算是十分痛苦。今日从头开始学习python,下定决心要学好、熟练。之后便将每一周的所学整理、记录下来。

第一周的内容比较基础,主要是有关python的变量、字符编码、用户交互、if判断、while、for循环等等。

首先是变量(var)。变量可以由数字、字母、下划线组成,数字不可以放在开头。python3也是支持中文变量的。要表示字符串的话加上引号(双引号、单引号一样),变量是不可加引号的。要表示多行或大片的字符串组合用‘’‘ 字符串 ’‘’。

之后是字符编码,包括二进制的一部分内容以及ASCII码,utf-8等等。在程序初始可以用(# -*- coding:utf-8 -*-)这样的格式来进行指定。

之后是用户交互。主要是input、print等等。input输入的初始格式是字符串,想要输入整形的话需要int(input()),整形是int,字符串是str。print就是输出、打印,其中格式化输出是一个点。将用户输入的信息按照自己设定好的格式进行输出,有三种方法,我主要记下其中两种。一种是%s、%d、%f,‘’‘    内容   ’‘’%(对应的输入),另外一种是{另外的变量名},‘’‘   内容   ’‘’.format()。程序如下:

name = input("name:")
age = input("age:")
stuID = input("stuID:")
teacher = input("teacher:")

information = '''
------------   information of {_name}   ------------   
             Name   : {_name}
             Age    : {_age}
             StuID  : {_stuID}
             Teacher: {_teacher}

------------   Thanks for using      ------------


'''.format(_name=name,_age=age,_stuID=stuID,_teacher=teacher)

print(information)
之后是if判断。主要格式有if、else、elif等,记得加冒号,还有就是对齐一定要看好,直接影响后面的程序。程序如下:
username = input("username:")
password =input("password:")

_username = "zzb"
_password = "7456"

table = '''
      -*-  Welcome to BIT {0}  -*-

'''.format(username)

if _username == username and _password == password :
    print(table)
else :
    print("404 not found")
之后是while循环。主要格式有while true、while + 判断 、else,举了一个猜班级的例子,结合了if等等,程序如下:
table = '''
--------------- guess game ---------------
               Attention!
There are twenty class in this school,
from 1 to 20,guess which is the class
of xiaoming,you have three chances.
'''
print(table)

class_number = 13
count = 0
while count <3:
    guess_class_number = int(input("guess :"))
    if guess_class_number == class_number:
        print("Congratulations!")
        break
    elif guess_class_number > class_number:
        print("Think smaller!")
    else:
        print("Think bigger!")
    count= count + 1
else:
    print("you have tried too many times!")
最后是for循环,for循环的格式是for i in range(m,n,k),i会从m一直走到n,步长为k。for循环可以嵌套。break是直接跳出循环,continue是跳出当前循环开始下一个循环。for的练习代码如下:
for i in range(0,10):
    if i < 5 :
      print("why",i)
    else :
      continue
    print("whose")


for i in range(10):
    print("---------",i)
    for j in range(10):
        if j < 4 :
          print(j)
结合上一个猜班级的for循环的代码:
table = '''
--------------- guess game ---------------
               Attention!
There are twenty class in this school,
from 1 to 20,guess which is the class
of xiaoming,you have three chances.
'''
print(table)
class_number = 13
for i in range(3):
    guess_class_number = int(input("guess :"))
    if guess_class_number == class_number:
        print("Congratulations!")
        break
    elif guess_class_number > class_number:
        print("Think smaller!")
    else:
        print("Think bigger!")
else:
    print("you have tried too many times!")
这一周的内容大概就是这些。一切都是从零开始,慢慢地去学习、掌握,慢慢积累,坚持下去。