python Programming: from introduction to practice Chapter 5 knowledge summary + Exercises 6-1 ~ 6-12

Posted by shopphp on Tue, 19 Oct 2021 01:25:54 +0200

 

6-1 persons: Use a dictionary to store information about an acquaintance, including first name, last name, age and city of residence. The dictionary should contain keys first_name , last_name , age and city . Store in this dictionary
Every piece of information is printed.
people = {
    'first_name': 'Smith',
    'last_name': 'Tom', 
    'age': '18', 
    'city': 'Shanghai'
}
print(people)
{'first_name': 'Smith', 'last_name': 'Tom', 'age': '18', 'city': 'Shanghai'}

Process finished with exit code 0
6-2 favorite numbers: Use a dictionary to store some people's favorite numbers. Please think of 5 Personal names and use these names as keys in the dictionary; Think of a number that everyone likes and store them as values
Store in a dictionary. Print everyone's name and favorite number. To make this program more interesting, make sure the data is true by asking friends.
numbers = {'Tom': 5, 'Hu': 87, 'Sui': 15, 'Jin': 16, 'Bao': 666}
print(numbers['Tom'])
print(numbers['Jin'])
print(numbers['Bao'])
print(numbers['Hu'])
print(numbers['Sui'])
5
16
666
87
15

Process finished with exit code 0
6-3 Glossary: Python Dictionaries can be used to simulate dictionaries in real life, but to avoid confusion, we call the latter glossary.
         Think of what you learned before A programming vocabulary, use them as keys in the vocabulary, and store their meanings in the vocabulary as values.
         Print each word and its meaning in a neat manner. To this end, you can print the word first, add a colon after it, and then print the meaning of the word; You can also print words on one line and use newline (\ n )Insert
Enter a blank line, and then print the meaning of the word in indent on the next line.
vocabulary = {'php': 'Technical language 1', 'python': 'Technical language 2',
              'java': 'Technical language 3', 'sql': 'Technical language 4'}

print("php: \n" + vocabulary['php'])
print("python: \n" + vocabulary['python'])
print("java: \n" + vocabulary['java'])
print("sql: \n" + vocabulary['sql'])
php: 
Technical language 1
python: 
Technical language 2
java: 
Technical language 3
sql: 
Technical language 4

Process finished with exit code 0
6-4 glossary 2: Now that you know how to traverse the dictionary, please organize your exercises for completion 6-3 And the code will be a series of print Statement is replaced by a loop that traverses the keys and values in the dictionary. Determine the
After the loop is correct, add it to the glossary 5 individual Python Terminology. When you run the program again, these new terms and their meanings will be automatically included in the output.
vocabulary = {'php': 'Technical language 1', 'python': 'Technical language 2',
              'java': 'Technical language 3', 'sql': 'Technical language 4'}

for key, value in vocabulary.items():
    print("\nkey: " + key)
    print("value: " + value)
vocabulary['bash']: 'Technical language 5'
vocabulary['C++']: 'Technical language 6'
vocabulary['CSS']: 'Technical language 7'
vocabulary['HTML']: 'Technical language 8'
vocabulary['go']: 'Technical language 9'
for key, value in vocabulary.items():
    print("\nkey1: " + key)
    print("value1: " + value)
key: php
value: Technical language 1

key: python
value: Technical language 2

key: java
value: Technical language 3

key: sql
value: Technical language 4

key1: php
value1: Technical language 1

key1: python
value1: Technical language 2

key1: java
value1: Technical language 3

key1: sql
value1: Technical language 4

Process finished with exit code 0
6-5 rivers: Create a dictionary that stores the three major rivers and the countries they flow through. One of the keys — Value pairs may be 'nile': 'egypt' .
         Use a loop to print a message for each river, such as "the nileruns throughetype." .
         Use the loop to print out the name of each river in the dictionary.
         Use the loop to print out the name of each country contained in the dictionary.
rivers = {'nile': 'egypt',
         'huanghe': 'china',
         'rhine': 'Switzerland',
}

for key, value in rivers.items():
    print("The " + key + " through " + value + ".")
The nile through egypt.
The huanghe through china.
The rhine through Switzerland.

Process finished with exit code 0
6-6 investigation: stay 6.3.1 Program written in section favorite_languages.py Do the following in.
         Create a list of people who should be surveyed, some of whom are included in the dictionary and others are not included in the dictionary.
         Traverse the list of people and print a message to thank those who have participated in the survey. For those who have not yet participated in the survey, print a message inviting them to participate in the survey.
user_0 = { 'username': 'efermi', 'first': 'enrico', 'last': 'fermi', }

user_1 = {
    'name1': 'efermi',
    'name2': 'Tom',
    'name3': 'tonny'
}
for v in user_1.values():
    if v in user_0.values():
        print(v.title() + ", thanks for join!")
    else:
        print(v.title() + ", hope you join in our investigation.")
Efermi, thanks for join!
Tom, hope you join in our investigation.
Tonny, hope you join in our investigation.

Process finished with exit code 0
6-7 persons: Completing exercises for 6-1 In the program written, two more dictionaries representing people are created, and then these three dictionaries are stored in a people In the list of. Go through the list and put all the names of each person in it
The information is printed out.
people = {
    'people1': {
        'first_name': 'Smith',
        'last_name': 'Tom',
        'age': '18',
        'city': 'Shanghai',
    },
    'people2': {
        'first_name': 'Blane',
        'last_name': 'Sam',
        'age': '22',
        'city': 'Anshan',
    },
    'people3': {
        'first_name': 'Ho',
        'last_name': 'Jin',
        'age': '25',
        'city': 'Chongqing',
    },
}
for person, peopleA in people.items():
    print("\nUsername: " + person)
    full_name = peopleA['first_name'] + " "+ peopleA['last_name']
    age = peopleA['age']
    city = peopleA['city']
    print("\t Full_name: "  + full_name.title())
    print("\t Age: " + age)
    print("\t City:" + city)
Username: people1
	 Full_name: Smith Tom
	 Age: 18
	 City:Shanghai

Username: people2
	 Full_name: Blane Sam
	 Age: 22
	 City:Anshan

Username: people3
	 Full_name: Ho Jin
	 Age: 25
	 City:Chongqing

Process finished with exit code 0
6-8 pets: Create multiple dictionaries. For each dictionary, use the name of a pet to name it; In each dictionary, include the type of pet and the name of its owner. Store these dictionaries in a file named pets
Then traverse the list and print out all the information of the pet.
[method 1]
Doggy_Sam = {
    'kind': 'dog',
    'owner': 'Tommy'
}
Cat_Jenny = {
    'kind': 'cat',
    'owner': 'tina'
}
Lion_Dazhuang = {
    'kind': 'lion',
    'owner': 'Jin'
}

Pets = [Doggy_Sam, Cat_Jenny, Lion_Dazhuang]
for pet in Pets:
    print(pet)
{'kind': 'dog', 'owner': 'Tommy'}
{'kind': 'cat', 'owner': 'tina'}
{'kind': 'lion', 'owner': 'Jin'}

Process finished with exit code 0
[method 2]
Doggy_Sam = {
    'kind': 'dog',
    'owner': 'Tommy'
}
Cat_Jenny = {
    'kind': 'cat',
    'owner': 'tina'
}
Lion_Dazhuang = {
    'kind': 'lion',
    'owner': 'Jin'
}

Pets = [Doggy_Sam, Cat_Jenny, Lion_Dazhuang]
for pet in Pets:
    if pet == Doggy_Sam:
        print(
            '\nDoggy_Sam:' + '\n\tkind:'
            + pet['kind'] + '\n\towner:'
            + pet['owner']
        )
    elif pet == Cat_Jenny:
        print(
            '\nCat_Jenny:' + '\n\tkind:'
            + pet['kind'] + '\n\towner:'
            + pet['owner']
        )
    elif pet == Lion_Dazhuang:
        print(
            '\nLion_Dazhuang:' + '\n\tkind:'
            + pet['kind'] + '\n\towner:'
            + pet['owner']
        )
Doggy_Sam:
	kind:dog
	owner:Tommy

Cat_Jenny:
	kind:cat
	owner:tina

Lion_Dazhuang:
	kind:lion
	owner:Jin

Process finished with exit code 0
6-9 favorite places: Create a file named favorite_places My dictionary. In this dictionary, the names of three people are used as keys; For each of them, store what he likes 1~3 A place. To make this practice
Learning is more interesting. Let some friends point out several places they like. Traverse the dictionary and print out everyone's name and what they like.
favorite_places = {
    'Tom': ['Shanghai', 'Chongqing', 'Shengyang'],
    'Tina':['Zhongshan', 'Beijing', 'London'],
    'Tony':['Hangzhou', 'Xiaoshan', 'Guiyang']
}
# Output mode 1:
for name, place in favorite_places.items():
    print(name + " would like to travel these places:", place)
# Output mode 2:

for name, place in favorite_places.items():
    print(f"\n{name.title()} likes to travel to these places:")
    for pla in place:
        print(pla)
Tom would like to travel these places: ['Shanghai', 'Chongqing', 'Shengyang']
Tina would like to travel these places: ['Zhongshan', 'Beijing', 'London']
Tony would like to travel these places: ['Hangzhou', 'Xiaoshan', 'Guiyang']

Tom likes to travel to these places:
Shanghai
Chongqing
Shengyang

Tina likes to travel to these places:
Zhongshan
Beijing
London

Tony likes to travel to these places:
Hangzhou
Xiaoshan
Guiyang

Process finished with exit code 0
6-10 favorite numbers: Modify to complete the exercise 6-2 The program allows everyone to have multiple favorite numbers, and then print everyone's name and favorite numbers.
numbers = {
    'Tom': [5, 6, 68],
    'Hu': [87, 55,45],
    'Sui': [15, 22],
    'Jin': [16,13],
    'Bao': [666, 34, 34, 55]
}

for name, number in numbers.items():
    print(f"\n{name.title()} likes these number:")
    for num in number:
        print(num)
Tom likes these number:
5
6
68

Hu likes these number:
87
55
45

Sui likes these number:
15
22

Jin likes these number:
16
13

Bao likes these number:
666
34
34
55

Process finished with exit code 0
6-11 cities: Create a file named cities A dictionary that uses three city names as keys; For each city, a dictionary is created that contains the country to which the city belongs, the approximate population, and an information about the city
The facts of the city. In the dictionary representing each city, it should include country , population and fact Wait for the key. Print out the name of each city and the information about them.
cities = {
    'Chongqing': {
        'country':'China',
        'popilation':'100,000',
        'description':'Chongqing is a beautiful mountain city'
    },
    'Shanghai': {
        'country':'China',
        'popilation': '900,000',
        'description':'Shanghai is a beautiful modern city'
    },
    'Berlin': {
        'country':'Deutschland',
        'popilation':'985,154,454',
        'description':'Berlin is the capital of Germany'
    },
}
# Mode 1:
for city, info in cities.items():
    print(f"\n{city}:{info} ")
# Mode 2:
for city, value in cities.items():
    print(f"\n{city}: ")
    for cityA, valueA in value.items():
        print(f"{cityA}:{valueA}")
Chongqing:{'country': 'China', 'popilation': '100,000', 'description': 'Chongqing is a beautiful mountain city'} 

Shanghai:{'country': 'China', 'popilation': '900,000', 'description': 'Shanghai is a beautiful modern city'} 

Berlin:{'country': 'Deutschland', 'popilation': '985,154,454', 'description': 'Berlin is the capital of Germany'} 

Chongqing: 
country:China
popilation:100,000
description:Chongqing is a beautiful mountain city

Shanghai: 
country:China
popilation:900,000
description:Shanghai is a beautiful modern city

Berlin: 
country:Deutschland
popilation:985,154,454
description:Berlin is the capital of Germany

Process finished with exit code 0

6-12 expansion: The examples in this chapter are complex enough to be extended in many ways. Please extend one of the examples in this chapter: add keys and values, adjust the problems to be solved by the program, or improve the format of the output.
No, there are updates later

Topics: Python Java Database