chapter2
# -*- coding:utf-8 -*-
# @FileName :chapter2.py
# @Time :2020/8/13 14:21
# @Author :Wu Hongyi
# @Copyright :Wu Hongyi
# Function description:
'''
本文件为Python编程快速上手-让繁琐工作自动化一书的第二章示例练习代码
'''
# @version :Version1.0
# Modification description:
'''
'''
# for循环和range函数
name = ''
while not name:
print("Enter your name:")
name = input()
print("How many guests will you have?")
numOfGuests = int(input())
if numOfGuests: # 如果numOfGuests不是0,打印提示信息
print("Be sure to have enough room for all your guests.")
print('done')
# FiveTimes.py的两种等价形式
# 1
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')
# 2
print('My name is')
i = 0
while i < 5:
print('Jimmy Five Times (' + str(i) + ')')
i += 1
# 高斯计算1+2+...+100的数学问题用python编程快速实现
total = 0;
for num in range(101):
total = total + num
print(total)
# range函数用法
for i in range(0, 10, 2):
print(i)
for j in range(5, -1, -1):
print(j)
# 导入模块
# printRandom.py
import random
for i in range(5):
print(random.randint(1, 10))
# 导入多个模块可用如下形式:
import random, sys, os, math
# import 的另一种形式包括from关键字,之后是模块名称,import关键字和一个*号
# 例如:
from random import *
# 使用这种形式的import语句,调用random模块中的函数时不需要random.前缀
# 但是使用完整的名称会让代码更可读,所以最好是使用普通形式的import语句
# 用sys.exit()提前结束程序
# 通过调用sys.exit()函数,可以让程序终止或退出。因为该函数在sys模块中,故需先导入sys库才可使用
# exitExample.py
import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
sys.exit()
print('You typed ' + response + '.')