1.python基本语法

基本语法

 

一. 用户交互

 

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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 一、Python的两种编程方式: 1、交互式:对每个输出语句即时运行结果,适合语法练习。2、文件式:批量执行一组语...
    lassiey阅读 3,322评论 0 0
  • 一、字符串的使用 使用[]获取字符串中的一个或多个字符 -索引:返回字符串中单个字符 <字符串>[M] eg:"...
    追逐_e6cf阅读 1,539评论 0 1
  • 学习前仪式print("hello word!")ps: 熟练各种语言的hello world书写, 嘻嘻 注释单...
    佘红响阅读 1,022评论 0 0
  • [!] sckit did not pass validation, due to 3 warnings (but...
    swagon阅读 1,554评论 0 2
  • 周末,下雨的下午我和娃难得的亲密时光,腻在床上说悄悄话 娃说他在学校里面的趣事 他说他同桌会模仿他,他生气了,就做...
    hcissy阅读 282评论 0 0

友情链接更多精彩内容