python之helloworld

python3默认字符集默认是Unicode
python2默认字符集默认是ASCII

print('hello_world!')

name = '小老虎'
age = 27

print("let's go!")
print('你真"帅啊"')
print('''let's go "帅"''')

'''
这是一段多行注释
用三引号就可以了
'''

需要注意python中不能使用关键字做变量名

name1 = input('请输入你的名字:')
print('你的名字是:', name1)

分支语句 if elif else
# username = input('请输入您的用户名:')
# password = input('请输入您的密码:')
# if username == 'wangsilei' and password == 123456:
# print('欢迎光临!')
# else:
# print('账号/密码错误!')

# input接受到的都是str类型的
# score = input('请输入你的分数:')
# if int(score) < 60:
# if int(score) >= 50:
# print('50-60')
# else:
# print('太低了!')
# print('不及格!')
# elif 60 <= int(score) < 80:
# print('及格!')
# elif 80 <= int(score) < 90:
# print('良好!')
# else:
# print('优秀!')

# == != < > <= >=比较运算符

sex = input('请输入你的性别:')
if sex == '男' or sex == '女':
print('性别输入正确!')
else:
print('性别输入有误!')

# 布尔类型 True False

for、while循环
import random


# 循环 迭代 遍历
# for while

# break结束循环
# continue结束本次循环,继续下一次循环
# count = 0
# while count < 10:
# print('哈哈哈哈')
# count += 1
# print('666')
# break
# else: # 循环正常结束运行它
# print('done!')

# count = 0
# while count < 3:
# username = input('请输入名字:')
# password = input('请输入密码:')
# if username == 'wangsilei' and password == '123456':
# print('登录成功!')
# break
# else:
# print('名字/密码错误!')
# count += 1
# else:
# print('错误次数过多!')
# for i in range(10):
# print(i)
random_number = random.randint(1, 1000)
for i in range(3):
number = int(input('请输入你猜的数字:'))
if number > random_number:
print('你猜的太大了!')
elif number < random_number:
print('你猜的太小了!')
else:
print('你猜对了,答案是:', random_number)
break

猜数字游戏
import random


# 以下代码不加continue也可以
random_number = random.randint(1, 1000)
count = 0
while count < 7:
count += 1
number = int(input('请输入你猜的数字:'))
if number > random_number:
print('你猜的太大了!')
continue
elif number < random_number:
print('你猜的太小了!')
continue
else:
print('你猜对了,答案是:', random_number)
break

字符串格式化
username = input('请输入你的名字:')
time = '2017-12-17 17:19:00'
print('欢迎光临' + username) # 通过+号拼接两个字符串
print('欢迎光临%s,时间是%s' % (username, time)) # 这种方式效率高
print('欢迎光临{},时间是{}'.format(username, time)) # 这种比第二种好
print('欢迎光临{name},时间是{date}'.format(name=username, date=time))

# %s后跟字符串 %d后跟整数 %f小数类型

number = 123
print('%.2f' % number) # 保留两位小数

登录小程序
username = 'wangsilei'
password = 123456

for i in range(3):
name = input('请输入账户名称:')
pwd = input('请输入账户密码:')
if name == username and int(pwd) == password:
print('{}欢迎登录'.format(name))
break
elif name == '' or pwd == '':
print('账户名称/账户密码不可为空')
elif name.isspace() or pwd.isspace():
print('账户名称/账户密码不可为空格')
else:
print('账户名称/密码错误!')

生成手机号码并写入txt小程序
import random


phone_lists = ['130', '131', '132', '133', '134', '135', '136', '170', '180']
phone_str = '0123456789'

n = int(input('生成多少个随机的电话号码:'))
with open(r'C:\Users\wangsilei\Desktop\phone.txt', 'w') as f:
for i in range(n):
phone_numbers = random.choice(phone_lists) + ''.join(random.choice(phone_str) for j in range(8)) + '\n'
f.write(phone_numbers)
posted @ 2017-12-19 15:51  王思磊  阅读(773)  评论(0编辑  收藏  举报