赞
踩
目录
- message = "Hello Python world!"
- print(message)
- message = "Hello Python Crash Course world!"
- print(message)
- 'I told my friend, "Python is my favorite language!"'
- "The language 'Python' is named after Monty Python, not the snake."
- "One of Python's strengths is its diverse and supportive community."
- name = "ada lovelace"
- print(name.title())
-
- #输出:Ada Lovelace
- name = "Ada Lovelace"
- print(name.upper())
- print(name.lower())
-
- #输出:ADA LOVELACE
- # ada lovelace
- first_name = "ada"
- last_name = "lovelace"
- full_name = first_name + " " + last_name
- print(full_name)
-
-
- #输出:ada lovelace
- first_name = "ada"
- last_name = "lovelace"
- full_name = first_name + " " + last_name
- print("Hello, " + full_name.title() + "!")
-
- #输出:Hello, Ada Lovelace!
- ① >>> favorite_language = 'python '
- ② >>> favorite_language
- 'python '
- ③ >>> favorite_language.rstrip()
- 'python'
- ④ >>> favorite_language
- 'python '
存储在变量favorite_language 中的字符串末尾包含多余的空白(见①)。你在终端会话中向Python询问这个变量的值时,可看到末尾的空格(见②)。对变- favorite_language = 'python '
- favorite_language = favorite_language.rstrip()
①整数
在Python中,可对整数执行加(+ )减(- )乘(* )除(/ )求模(%)运算:
- >>> 2 + 3
- 5 >>> 3
- -
- 2
- 1 >>> 2
- *
- 3
- 6 >>> 3
- /
- 2
- 1.5
- >>> 3 ** 2
- 9
- >>> 3 ** 3
- 27
- >>> 10 ** 6
- 1000000
- >>> 2 + 3*4
- 14
- >>> (2 + 3) * 4
- 20
②浮点数
- >>> 0.2 + 0.1
- 0.30000000000000004
- >>> 3 * 0.1
- 0.30000000000000004
- age = 23
- message = "Happy " + age + "rd Birthday!"
- print(message)
为此,可调用函数str() ,它让Python将非字符串值表示为字符串: - age = 23
- message = "Happy " + str(age) + "rd Birthday!"
- print(message)
- bicycles = ['trek', 'cannondale', 'redline', 'specialized']
- print(bicycles)
-
- #输出:
- #['trek', 'cannondale', 'redline', 'specialized']
- bicycles = ['trek', 'cannondale', 'redline', 'specialized']
- print(bicycles[0])
-
- #输出:trek
- bicycles = ['trek', 'cannondale', 'redline', 'specialized']
- print(bicycles[-1])
-
- #输出:specialized
- motorcycles = ['honda', 'yamaha', 'suzuki']
- print(motorcycles)
- motorcycles[0] = 'ducati'
- print(motorcycles)
- motorcycles = ['honda', 'yamaha', 'suzuki']
- print(motorcycles)
- motorcycles.append('ducati')
- print(motorcycles)
-
- #输出:
- #['honda', 'yamaha', 'suzuki']
- #['honda', 'yamaha', 'suzuki', 'ducati']
- motorcycles = []
- motorcycles.append('honda')
- motorcycles.append('yamaha')
- motorcycles.append('suzuki')
- print(motorcycles)
- motorcycles = ['honda', 'yamaha', 'suzuki']
- motorcycles.insert(0, 'ducati')
- print(motorcycles)
- motorcycles = ['honda', 'yamaha', 'suzuki']
- print(motorcycles)
- del motorcycles[1]
- print(motorcycles)
- motorcycles = ['honda', 'yamaha', 'suzuki']
- print(motorcycles)
- popped_motorcycle = motorcycles.pop()
- print(motorcycles)
- print(popped_motorcycle)
-
-
- #输出:
- #['honda', 'yamaha', 'suzuki']
- #['honda', 'yamaha']
- #suzuki
- motorcycles = ['honda', 'yamaha', 'suzuki']
- first_owned = motorcycles.pop(0)
- print('The first motorcycle I owned was a ' + first_owned.title() + '.')
- motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
- print(motorcycles)
-
- too_expensive = 'ducati'
- motorcycles.remove(too_expensive)
-
- print(motorcycles)
- print("\nA " + too_expensive.title() + " is too expensive for me.")
- cars = ['bmw', 'audi', 'toyota', 'subaru']
- cars.sort()
- print(cars)
-
-
- #输出:
- #['audi', 'bmw', 'subaru', 'toyota']
- cars = ['bmw', 'audi', 'toyota', 'subaru']
- cars.sort(reverse=True)
- print(cars)
- cars = ['bmw', 'audi', 'toyota', 'subaru']
- print("Here is the original list:")
- print(cars)
-
- print("\nHere is the sorted list:")
- print(sorted(cars))
-
- print("\nHere is the original list again:")
- print(cars)
- cars = ['bmw', 'audi', 'toyota', 'subaru']
- print(cars)
- cars.reverse()
- print(cars)
- cars = ['bmw', 'audi', 'toyota', 'subaru']
- print(len(cars))
- magicians = ['alice', 'david', 'carolina']
- for magician in magicians:
- print(magician)
- magicians = ['alice', 'david', 'carolina']
- for magician in magicians:
- print(magician.title() + ", that was a great trick!")
- print("I can't wait to see your next trick, " + magician.title() + ".\n")
- for value in range(1,5):
- print(value)
-
-
- #输出:
- #1
- #2
- #3
- #4
- numbers = list(range(1,6))
- print(numbers)
- even_numbers = list(range(2,11,2))
- print(even_numbers)
- squares = []
- for value in range(1,11):
- square = value**2
- squares.append(square)
- print(squares)
- digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
- print(min(digits))
- print(max(digits))
- print(sum(digits))
- squares = [value**2 for value in range(1,11)]
- print(squares)
- players = ['charles', 'martina', 'michael', 'florence', 'eli']
- print(players[0:3])
-
- #输出:['charles', 'martina', 'michael']
- #自动从头开始
- players = ['charles', 'martina', 'michael', 'florence', 'eli']
- print(players[:4])
-
- #自动到尾部结束
- players = ['charles', 'martina', 'michael', 'florence', 'eli']
- print(players[2:])
- players = ['charles', 'martina', 'michael', 'florence', 'eli']
- print(players[-3:])
- players = ['charles', 'martina', 'michael', 'florence', 'eli']
- print("Here are the first three players on my team:")
- for player in players[:3]:
- print(player.title())
- my_foods = ['pizza', 'falafel', 'carrot cake']
-
- #会有两个不同的列表存在
- friend_foods = my_foods[:]
- my_foods.append('cannoli')
- friend_foods.append('ice cream')
- my_foods = ['pizza', 'falafel', 'carrot cake']
-
- #这行不通
- friend_foods = my_foods
- my_foods.append('cannoli')
- friend_foods.append('ice cream')
- dimensions = (200, 50)
- print(dimensions[0])
- print(dimensions[1])
- dimensions = (200, 50)
- print("Original dimensions:")
- for dimension in dimensions:
- print(dimension)
-
- dimensions = (400, 100)
- print("\nModified dimensions:")
- for dimension in dimensions:
- print(dimension)
- cars = ['audi', 'bmw', 'subaru', 'toyota']
- for car in cars:
- if car == 'bmw':
- print(car.upper())
- else:
- print(car.title())
- car = 'Audi'
- car == 'audi' #False
- car = 'Audi'
- car.lower() == 'audi' #True
- age_0 = 22
- age_1 = 18
- age_0 >= 21 and age_1 >= 21 #False
- age_0 = 22
- age_1 = 18
- age_0 >= 21 or age_1 >= 21 #True
- banned_users = ['andrew', 'carolina', 'david']
- user = 'marie'
- if user not in banned_users:
- print(user.title() + ", you can post a response if you wish.")
- game_active = True
- can_edit = False
- if conditional_test:
- do something
- age = 17
-
- if age >= 18:
- print("You are old enough to vote!")
- print("Have you registered to vote yet?")
- else:
- print("Sorry, you are too young to vote.")
- print("Please register to vote as soon as you turn 18!")
- age = 12
-
- if age < 4:
- print("Your admission cost is $0.")
- elif age < 18:
- print("Your admission cost is $5.")
- else:
- print("Your admission cost is $10.")
- requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
-
- for requested_topping in requested_toppings:
- if requested_topping == 'green peppers':
- print("Sorry, we are out of green peppers right now.")
- else:
- print("Adding " + requested_topping + ".")
-
- print("\nFinished making your pizza!")
- requested_toppings = []
- if requested_toppings:
- for requested_topping in requested_toppings:
- print("Adding " + requested_topping + ".")
- print("\nFinished making your pizza!")
- else:
- print("Are you sure you want a plain pizza?")
- available_toppings = ['mushrooms', 'olives', 'green peppers',
- 'pepperoni', 'pineapple', 'extra cheese']
- requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
-
- for requested_topping in requested_toppings:
- if requested_topping in available_toppings:
- print("Adding " + requested_topping + ".")
- else:
- print("Sorry, we don't have " + requested_topping + ".")
- print("\nFinished making your pizza!")
- alien_0 = {'color': 'green', 'points': 5}
- print(alien_0['color'])
- print(alien_0['points'])
-
- #输出:
- #green
- #5
- alien_0 = {'color': 'green', 'points': 5}
-
- print(alien_0)
- alien_0['x_position'] = 0
- alien_0['y_position'] = 25
- print(alien_0)
-
-
- #输出:
- #{'color': 'green', 'points': 5}
- #{'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}
- alien_0 = {'color': 'green'}
-
- alien_0['color'] = 'yellow'
- alien_0 = {'color': 'green', 'points': 5}
-
- del alien_0['points']
- favorite_languages = {
- 'jen': 'python',
- 'sarah': 'c',
- 'edward': 'ruby',
- 'phil': 'python',
- }
- user_0 = {
- 'username': 'efermi',
- 'first': 'enrico',
- 'last': 'fermi',
- }
-
- for key, value in user_0.items():
- print("\nKey: " + key)
- print("Value: " + value)
- favorite_languages = {
- 'jen': 'python',
- 'sarah': 'c',
- 'edward': 'ruby',
- 'phil': 'python',
- }
- for name in favorite_languages.keys():
- print(name.title())
- favorite_languages = {
- 'jen': 'python',
- 'sarah': 'c',
- 'edward': 'ruby',
- 'phil': 'python',
- }
- for name in sorted(favorite_languages.keys()):
- print(name.title() + ", thank you for taking the poll.")
- favorite_languages = {
- 'jen': 'python',
- 'sarah': 'c',
- 'edward': 'ruby',
- 'phil': 'python',
- }
-
- print("The following languages have been mentioned:")
- for language in set(favorite_languages.values()):
- print(language.title())
- alien_0 = {'color': 'green', 'points': 5}
- alien_1 = {'color': 'yellow', 'points': 10}
- alien_2 = {'color': 'red', 'points': 15}
-
- aliens = [alien_0, alien_1, alien_2]
-
- for alien in aliens:
- print(alien)
- # 创建一个用于存储外星人的空列表
- aliens = []
-
- # 创建30个绿色的外星人
- for alien_number in range(30):
- new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
- aliens.append(new_alien)
-
- # 显示前五个外星人
- for alien in aliens[:5]:
- print(alien)
- print("...")
-
- # 显示创建了多少个外星人
- print("Total number of aliens: " + str(len(aliens)))
- favorite_languages = {
- 'jen': ['python', 'ruby'],
- 'sarah': ['c'],
- 'edward': ['ruby', 'go'],
- 'phil': ['python', 'haskell'],
- }
-
- for name, languages in favorite_languages.items():
- print("\n" + name.title() + "'s favorite languages are:")
-
- for language in languages:
- print("\t" + language.title())
- users = {
- 'aeinstein': {
- 'first': 'albert',
- 'last': 'einstein',
- 'location': 'princeton',
- },
- 'mcurie': {
- 'first': 'marie',
- 'last': 'curie',
- 'location': 'paris',
- },
- }
-
- for username, user_info in users.items():
- print("\nUsername: " + username)
- full_name = user_info['first'] + " " + user_info['last']
- location = user_info['location']
- print("\tFull name: " + full_name.title())
- print("\tLocation: " + location.title())
- message = input("Tell me something, and I will repeat it back to you: ")
- print(message)
- age = input("How old are you? ") #21
- age
-
- #输出:'21'
- height = input("How tall are you, in inches? ")
- height = int(height)
-
- if height >= 36:
- print("\nYou're tall enough to ride!")
- else:
- print("\nYou'll be able to ride when you're a little older.")
- current_number = 1
- while current_number <= 5:
- print(current_number)
- current_number += 1
- prompt = "\nTell me something, and I will repeat it back to you:"
- prompt += "\nEnter 'quit' to end the program. "
- message = ""
-
- while message != 'quit':
- message = input(prompt)
- print(message)
- prompt = "\nPlease enter the name of a city you have visited:"
- prompt += "\n(Enter 'quit' when you are finished.) "
-
- while True:
- city = input(prompt)
- if city == 'quit':
- break
- else:
- print("I'd love to go to " + city.title() + "!")
- current_number = 0
-
- while current_number < 10:
- current_number += 1
- if current_number % 2 == 0:
- continue
- print(current_number)
- # 首先,创建一个待验证用户列表
- # 和一个用于存储已验证用户的空列表
- unconfirmed_users = ['alice', 'brian', 'candace']
- confirmed_users = []
-
- # 验证每个用户,直到没有未验证用户为止
- # 将每个经过验证的列表都移到已验证用户列表中
- while unconfirmed_users:
- current_user = unconfirmed_users.pop()
- print("Verifying user: " + current_user.title())
- confirmed_users.append(current_user)
-
- # 显示所有已验证的用户
- print("\nThe following users have been confirmed:")
- for confirmed_user in confirmed_users:
- print(confirmed_user.title())
- responses = {}
-
- # 设置一个标志,指出调查是否继续
- polling_active = True
- while polling_active:
- # 提示输入被调查者的名字和回答
- name = input("\nWhat is your name? ")
- response = input("Which mountain would you like to climb someday? ")
- # 将答卷存储在字典中
- responses[name] = response
- # 看看是否还有人要参与调查
- repeat = input("Would you like to let another person respond? (yes/ no) ")
- if repeat == 'no':
- polling_active = False
-
- # 调查结束,显示结果
- print("\n--- Poll Results ---")
- for name, response in responses.items():
- print(name + " would like to climb " + response + ".")
- def greet_user():
- """显示简单的问候语"""
- print("Hello!")
-
- greet_user()
- def greet_user(username):
- """显示简单的问候语"""
- print("Hello, " + username.title() + "!")
-
- greet_user('jesse')
- def describe_pet(animal_type, pet_name):
- """显示宠物的信息"""
- print("\nI have a " + animal_type + ".")
- print("My " + animal_type + "'s name is " + pet_name.title() + ".")
-
- describe_pet(animal_type='hamster', pet_name='harry')
- def describe_pet(pet_name, animal_type='dog'):
- """显示宠物的信息"""
- print("\nI have a " + animal_type + ".")
- print("My " + animal_type + "'s name is " + pet_name.title() + ".")
-
- describe_pet(pet_name='willie')
-
- #输出:
- #I have a dog.
- #My dog's name is Willie.
- def get_formatted_name(first_name, last_name):
- """返回整洁的姓名"""
- full_name = first_name + ' ' + last_name
- return full_name.title()
-
- musician = get_formatted_name('jimi', 'hendrix')
- print(musician)
- def build_person(first_name, last_name):
- """返回一个字典,其中包含有关一个人的信息"""
- person = {'first': first_name, 'last': last_name}
- return person
-
- musician = build_person('jimi', 'hendrix')
- print(musician)
- def print_models(unprinted_designs, completed_models):
- """
- 模拟打印每个设计,直到没有未打印的设计为止
- 打印每个设计后,都将其移到列表completed_models中
- """
- while unprinted_designs:
- current_design = unprinted_designs.pop()
- # 模拟根据设计制作3D打印模型的过程
- print("Printing model: " + current_design)
- completed_models.append(current_design)
-
- def show_completed_models(completed_models):
- """显示打印好的所有模型"""
- print("\nThe following models have been printed:")
- for completed_model in completed_models:
- print(completed_model)
-
- #函数调用
- unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
- completed_models = []
- print_models(unprinted_designs, completed_models)
- show_completed_models(completed_models)
- def make_pizza(*toppings):
- """概述要制作的比萨"""
- print("\nMaking a pizza with the following toppings:")
- for topping in toppings:
- print("- " + topping)
-
- make_pizza('pepperoni')
- make_pizza('mushrooms', 'green peppers', 'extra cheese')
-
- #输出:
- #Making a pizza with the following toppings:
- #- pepperoni
-
- #Making a pizza with the following toppings:
- #- mushrooms
- #- green peppers
- #- extra cheese
- def make_pizza(size, *toppings):
- """概述要制作的比萨"""
- print("\nMaking a " + str(size) +
- "-inch pizza with the following toppings:")
- for topping in toppings:
- print("- " + topping)
-
- make_pizza(16, 'pepperoni')
- make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
- def build_profile(first, last, **user_info):
- """创建一个字典,其中包含我们知道的有关用户的一切"""
- profile = {}
- profile['first_name'] = first
- profile['last_name'] = last
- for key, value in user_info.items():
- profile[key] = value
- return profile
-
- user_profile = build_profile('albert', 'einstein',
- location='princeton',
- field='physics')
- print(user_profile)
- class Dog():
- """一次模拟小狗的简单尝试"""
- def __init__(self, name, age):
- """初始化属性name和age"""
- self.name = name
- self.age = age
-
- def sit(self):
- """模拟小狗被命令时蹲下"""
- print(self.name.title() + " is now sitting.")
-
- def roll_over(self):
- """模拟小狗被命令时打滚"""
- print(self.name.title() + " rolled over!")
- my_dog = Dog('willie', 6)
- print("My dog's name is " + my_dog.name.title() + ".")
- print("My dog is " + str(my_dog.age) + " years old.")
- class Car():
- def __init__(self, make, model, year):
- """初始化描述汽车的属性"""
- self.make = make
- self.model = model
- self.year = year
- self.odometer_reading = 0
- def get_descriptive_name(self):
- """返回整洁的描述性信息"""
- long_name = str(self.year) + ' ' + self.make + ' ' + self.model
- return long_name.title()
- def read_odometer(self):
- """打印一条指出汽车里程的消息"""
- print("This car has " + str(self.odometer_reading) + " miles on it.")
-
- #使用类
- my_new_car = Car('audi', 'a4', 2016)
- print(my_new_car.get_descriptive_name())
- my_new_car.read_odometer()
- #父类:Car
- class Car():
- """一次模拟汽车的简单尝试"""
- def __init__(self, make, model, year):
- self.make = make
- self.model = model
- self.year = year
- self.odometer_reading = 0
- def get_descriptive_name(self):
- long_name = str(self.year) + ' ' + self.make + ' ' + self.model
- return long_name.title()
- def read_odometer(self):
- print("This car has " + str(self.odometer_reading) + " miles on it.")
- def update_odometer(self, mileage):
- if mileage >= self.odometer_reading:
- self.odometer_reading = mileage
- else:
- print("You can't roll back an odometer!")
- def increment_odometer(self, miles):
- self.odometer_reading += miles
-
- #另一个类:Battery
- class Battery():
- """一次模拟电动汽车电瓶的简单尝试"""
- def __init__(self, battery_size=70):
- """初始化电瓶的属性"""
- self.battery_size = battery_size
- def describe_battery(self):
- """打印一条描述电瓶容量的消息"""
- print("This car has a " + str(self.battery_size) + "-kWh battery.")
- def get_range(self):
- """打印一条消息,指出电瓶的续航里程"""
- if self.battery_size == 70:
- range = 240
- elif self.battery_size == 85:
- range = 270
- message = "This car can go approximately " + str(range)
- message += " miles on a full charge."
- print(message)
-
- #子类:ElectricCar
- class ElectricCar(Car):
- """电动汽车的独特之处"""
- def __init__(self, make, model, year):
- """
- 初始化父类的属性,再初始化电动汽车特有的属性
- """
- super().__init__(make, model, year)
- self.battery = Battery()
-
-
- #使用类
- my_tesla = ElectricCar('tesla', 'model s', 2016)
- print(my_tesla.get_descriptive_name())
- my_tesla.battery.describe_battery()
- my_tesla.battery.get_range()
- from collections import OrderedDict
-
- favorite_languages = OrderedDict()
- favorite_languages['jen'] = 'python'
- favorite_languages['sarah'] = 'c'
- favorite_languages['edward'] = 'ruby'
- favorite_languages['phil'] = 'python'
-
- for name, language in favorite_languages.items():
- print(name.title() + "'s favorite language is " +
- language.title() + ".")
- with open('pi_digits.txt') as file_object:
- contents = file_object.read()
- print(contents)
- file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'
- with open(file_path) as file_object:
- filename = 'pi_digits.txt'
- with open(filename) as file_object:
- for line in file_object:
- print(line)
- filename = 'pi_digits.txt'
- with open(filename) as file_object:
- lines = file_object.readlines()
-
- for line in lines:
- print(line.rstrip())
- filename = 'programming.txt'
- with open(filename, 'w') as file_object:
- file_object.write("I love programming.")
- try:
- print(5/0)
- except ZeroDivisionError:
- print("You can't divide by zero!")
- import json
- numbers = [2, 3, 5, 7, 11, 13]
- filename = 'numbers.json'
-
- with open(filename, 'w') as f_obj:
- json.dump(numbers, f_obj)
- import json
- filename = 'numbers.json'
- with open(filename) as f_obj:
- numbers = json.load(f_obj)
- print(numbers)
- def get_formatted_name(first, last):
- """Generate a neatly formatted full name."""
- full_name = first + ' ' + last
- return full_name.title()
-
- print("Enter 'q' at any time to quit.")
- while True:
- first = input("\nPlease give me a first name: ")
- if first == 'q':
- break
- last = input("Please give me a last name: ")
- if last == 'q':
- break
- formatted_name = get_formatted_name(first, last)
- print("\tNeatly formatted name: " + formatted_name + '.')
- import unittest
-
- def get_formatted_name(first, last):
- """Generate a neatly formatted full name."""
- full_name = first + ' ' + last
- return full_name.title()
-
- class NamesTestCase(unittest.TestCase):
- """测试name_function.py"""
- def test_first_last_name(self):
- """能够正确地处理像Janis Joplin这样的姓名吗?"""
- formatted_name = get_formatted_name('janis', 'joplin')
- self.assertEqual(formatted_name, 'Janis Joplin')
-
- unittest.main()
- import unittest
- from survey import AnonymousSurvey
-
- class TestAnonmyousSurvey(unittest.TestCase):
- """针对AnonymousSurvey类的测试"""
- def test_store_single_response(self):
- """测试单个答案会被妥善地存储"""
- question = "What language did you first learn to speak?"
- my_survey = AnonymousSurvey(question)
- my_survey.store_response('English')
- self.assertIn('English', my_survey.responses)
-
- unittest.main()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。