基本语法
一. 用户交互
1. input交互:
#!/usr/bin/env python
#_*_coding:utf-8_*_
name = input("What is your name?")
print( "Hello:" + name )
[root@linux-node1 ~]# python3 test.py
What is your name?wy.zhang
Hello:wy.zhang
2. 格式化输出字符串拼接:
name = input("name:")
age = input("age:")
info = '''
Name:''' + name +'''
Age:''' + age +'''
'''
print(info)
[root@linux-node1 ~]# python3 test.py
name:wy.zhang
age:23
Name:wy.zhang
Age:23
3. 格式化输出%:
name = input("name:")
# 交互输入是str型,强制转换int型
age = int(input("age:"))
# %d必须是整型
info = '''
Name:%s
Age:%d
'''%(name,age)
print(info)
4. 格式化输出format:
name = input("name:")
age = int(input("age:"))
info = '''
Name:{_name}
Age:{_age}
'''.format(_name=name,_age=age)
print(info)
name = input("name:")
age = int(input("age:"))
info = '''
Name:{0}
Age:{1}
'''.format(name,age)
print(info)
二. if流程判断
1. 密文输入:
#!/usr/bin/env python
#_*_coding:utf-8_*_
import getpass
name = input("name:")
password = getpass.getpass("password")
print(name,password)
2. 用户密码:
import getpass
_name = 'wy.zhang'
_password = 'abc123'
name = input("name:")
password = getpass.getpass("password")
if _name == name and _password == password:
print("Welcome {0} login".format(name))
else:
print("{user} is Invalid".format(user=name))
3. 猜测年龄:
age = 23
guess_age = int(input("guess age:"))
if guess_age == age:
print("yes")
elif guess_age > age:
print("smaller")
else:
print("bigger")
三. while循环
1. 循环加一:
#!/usr/bin/env python
#_*_coding:utf-8_*_
count = 0
while True:
print("count:",count)
count = count +1
if count == 1000:
break
2. 猜测年龄三次退出提示:
age = 23
count = 0
while count <3:
guess_age = int(input("guess age:"))
if guess_age == age:
print("yes")
break
elif guess_age > age:
print("smaller")
else:
print("bigger")
count += 1
else:
print("tried too many")
三. for循环
1. 猜测年龄三次退出提示:
#!/usr/bin/env python
#_*_coding:utf-8_*_
age = 23
for i in range(3):
guess_age = int(input("guess age:"))
if guess_age == age:
print("yes")
break
elif guess_age > age:
print("smaller")
else:
print("bigger")
else:
print("tried too many")
2. range
for i in range(0,10,2):
print("loop",i)