Python语法命令学习-Day1(零基础)

摘要:

一、打印"()"内的信息

例1:print("a,b")

输出结果:a,b

例2: print("a\nb")

输出结果:a

     b

二、字符编码修改为utf-8

置顶键入:#_*_coding:utf-8_*_

三、定义变量,调用变量

例1: name="lich"

  age=18

  print(name,age)

输出结果:lich,18

说明:只要是带有' '/" "/''' ''' 的当中所有内容都被认为是字符串

四、键入式变量

例1:

name = input("input your name:")    #在python3.x中 input输出的默认都认为是字符串
age = int(input("input your age:")) #convert string into number ,int是将字符串转换成数字
job = input("input your job:")

msg ='''
Information of User %s
-----------------------
Name: %s
Age: %d
Job: %s
----------End----------
''' %(name,name,age,job)

print(msg)

输出结果:可以在开发工具中尝试。
说明:int()表示证
   %s代表引用外面的变量
   从information那行开始用的%s开始,必须在最后 %(通过逗号依次说明变量的填入引用),s=string 、d=digital、f=小数


五、字符编码
编译环境默认用ascii码,若是在python2.x中,必须有解释器和字符集添加,所以需要添加以下参数。
#!/usr/bin/env python
# -*- coding: utf-8 -*-

若在python3.x中,是不需要增加以上参数,在python3.x中默认使用unicode,所以不需要新增参数识别中文了。


六、倒入库
1.getpass库,使屏幕上输入的所有字符变成密文
例1:
import getpass
username = input("username:")
password = getpass.getpass("passwd:")
print(username,password)
#但是在pycharm里面,无法实现python3密文输入。

2.import os (在python下使用shell)
例1:
os.system("df -h")

3.import tab 倒入命令补全库,可以补全命令

七、python下使用shell脚本执行linux命令
例1:
import os #倒入os库,可以使用shell脚本
cmd_res #将linux执行命令的结果保存到变量中
os.system()  #执行linux中shell脚本命令
os.mkdir()  #新建子目录
cmd_res = os.popen("linux执行命令").read()  #将linux执行命令的结果保存到变量中
                           #上一句语句中 os.popen("linux执行命令") 这个意思是先将执行的命令保存到计算机内存中、然后read()意思是将将保存在内存中的结果读出来
import sys  #倒入sys模块
print(sys.path)  #python的全局环境变量存放目录

八、if else elif函数运用
例1:
age = 18  #定义需要猜的年龄数字

guess_age = int(input("please gusse my age:"))  #请用户输出一个数字

if guess_age == age:  #如果所猜年龄=定义的年龄
print("correct!")  #才对后输出correct!
elif guess_age > age:  #如果猜的年龄比定义年龄大了的话
print("the age is too big...")  #输入the age is too big...
else:  #否则语法
print("please think bigger...!")  #输出please think bigger...!


九、for 循环语句
固定语法:for i in range(10):  #定义i可以循环10次,如果输出i得到的返回是0123456789

例1: 猜年龄,定义所需要猜测的年龄=18,用户最多只能猜3次,猜对后输出correct!,猜大了输出the age is too big...,猜小了输出 please think bigger...!
age = 18
for i in range(10):
if i < 3:
guess_age = int(input("please gusse my age:"))

if guess_age == age:
print("correct!")
break
elif guess_age > age:
print("the age is too big...")
else:
print("please think bigger...!")
else:
print("bye!")
break

例2:猜年龄,定义所需要猜测的年龄=18,用户能猜3次,猜对后输出correct!,猜大了输出the age is too big...,猜小了输出 please think bigger...!,在猜了三次之后,会给用户进行选择,是需要继续还是
结束游戏,如果用户选择y,则继续循环三次的猜年龄游戏,否则输出bye终止游戏。
age = 18
count = 0
for i in range(10):
if count < 3:
print("count i=",i)
guess_age = int(input("please gusse my age:"))

if guess_age == age:
print("correct!")
break  #立即跳出这个循环!!
elif guess_age > age:
print("the age is too big...")
else:
print("please think bigger...!")

else:
continue_confirm = input("continue??")
if continue_confirm == "y":
count = 0
continue  #立即跳出当前循环!!
else:
print("bye!")
break
count = count + 1



十、pass占位符
为了保证代码的整体结构一致,可以使用pass做占位符



















猜你喜欢

转载自www.cnblogs.com/lich1x/p/9073819.html