Python syntax foundation of day

Basic Python learning

day_02

  • Use method to change the case of a string

Change the initial of a string to uppercase

>>> name = "ada lovelace"
>>> print(name.title())
Ada Lovelace

Make all strings uppercase

>>> print(name.upper())
ADA LOVELACE

Make all strings lowercase

>>> print(name.lower())
ada lovelace
  • Merge strings

Use + to merge first_name,last_name, space

>>> first_name = "ada"
>>> last_name = "lovelace"
>>> full_name = first_name + " " +last_name
>>> print(full_name)
ada lovelace

Use title() to assemble a string

>>> print("Hello,"+ " " + full_name.title() +"!")
Hello, Ada Lovelace!

You can also store the entire information in one variable

>>> message = "Hello,"+ " " + full_name.title() +"!"
>>> print(message)
Hello, Ada Lovelace!
  • Use tabs or line breaks to add white space

Add tabs to characters, using character combinations \ t

>>> print("Python")
Python
>>> print("\tPython")
	Python

Add line breaks to characters, using character combinations \ n

>>> print("I\nlove\nPython")
I
love
Python

Use line breaks with tabs

>>> print("I\n\tlove\n\tPython")
I
	love
	Python
  • Remove blank

Use the method rstrip(), which is only temporary

>>> a_word = 'python '
>>> a_word
'python '  #There is a space character when entering
>>> a_word.rstrip()
'python'   #Eliminate gaps
>>> a_word
'python ' 

To permanently delete spaces, you need to reassign the deleted operation to the original variable

>>> a_word = a_word.rstrip()
>>> a_word
'python'

rstrip() removes the white space on the right

lstrip() removes the left margin

strip() to remove all blanks

>>> a_word = ' python '  #Left and right margins
>>> a_word.rstrip()
' python'
>>> a_word.lstrip()
'python '
>>> a_word.strip()
'python'
  • Using strings to avoid syntax errors

The apostrophe is between two double quotation marks, so the whole string can be recognized

>>> message = "I'm a student."
>>> print(message)
I'm a student.

But when using single quotes

>>> message = 'I'm a student.'
SyntaxError: invalid syntax

Python can't determine the end of a string correctly

  • number

integer

Integers can be + - * / operated in Python

>>> 1+1
2
>>> 3-5
-2
>>> 3-2
1
>>> 3/2
1.5
>>> 8*9
72

Python uses two multipliers (* *) for multiplication

>>> 8*9
72
>>> 3**3
27
>>> 2**3
8
>>> 5**5
3125

Floating point

You don't need to think about other behaviors when using floating-point numbers. Just enter the number you want to use

>>> 1.2+5
6.2
>>> 1.2+36.3
37.5
>>> 1.7+9.6
11.299999999999999
>>> 1.6+1.6
3.2
>>> 0.2+0.1
0.30000000000000004
>>> 2*0.2
0.4
>>> 1*0.3
0.3

Sometimes the result contains an indeterminate decimal point

But don't worry, we will solve these problems in the next study

  • Using str() to avoid typos

Sometimes you want to

>>> age = 22
>>> message = "Happy" + " " + age +"rd Birthday!!"

You will want to output "Happy 22rd Byrthday!!"

However, it's a pity that the above code will cause an error

>>> age = 22
>>> message = "Happy" + " " + age  +"rd Birthday!!"
Traceback (most recent call last):
  File "<pyshell#54>", line 1, in <module>
    message = "Happy" + " " + age  +"rd Birthday!!"
TypeError: can only concatenate str (not "int") to str

This is a type error. Python finds that you use a value of integer (int). It doesn't know how to interpret this value. It thinks that this variable may express 22, or 2 and 2 characters. For this reason, when calling the variable, it is. You need to call the str() function to turn this variable into a string.

>>>age = 22
>>> message = "Happy" + " " + str(age) + "rd Birthday!!"
>>> print(message)
Happy 22rd Birthday!!
  • Zen of python

Run import this in IDLE to get the Zen of Python

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

That's what Python will learn the next day. I hope it can help you. I wish you success in your study!!!

day_03

  • What is the list

In Python, the list is represented by [] and the elements are separated by commas. Here is a simple list example:

>>> bicycles = ['treak','cannondale','redline','specialized']
>>> print(bicycles)

Python prints out the list, including brackets

['treak', 'cannondale', 'redline', 'specialized']
  • Access list elements

Use [] to access elements in the list

>>> print(bicycles[0])
treak

The previous statement used cycles [0] to access the first element in the list

I can use the string method mentioned yesterday to make the output more concise -- use the title() method:

>>> print(bicycles[0].title())
Treak
  • Index starts from 0 instead of 1

You can see

>>> bicycles = ['treak','cannondale','redline','specialized']
>>> print(bicycles[1])
cannondale
>>> print(bicycles[3])
specialized

The element with subscript 1 is canondale, and the element with subscript 3 is specialized

You can get the last list element by visiting [- 1]

>>> bicycles = ['treak','cannondale','redline','specialized']
>>> print(bicycles[-1])
specialized

Similarly, visit [- 2] to get the penultimate element and [- 3] the penultimate element

  • Use each value in the list

Now try to extract a bike and use this value to create a message:

>>> message = "My first bicycles was a "+bicycles[1].title() + "."
>>> print(message)
My first bicycles was a Cannondale.
  • Modify list elements

For example, suppose you have a list of animals, where the first element is' tiger '. How can you change its value?

>>> animal = ['tiger','bird','fox']
>>> print(animal)
['tiger', 'bird', 'fox']

>>> animal[0] = 'monkey'
>>> print(animal)
['monkey', 'bird', 'fox']
  • Add elements to the list

Using the method append() to add elements

>>> animal.append('fish')
>>> print(animal)
['monkey', 'bird', 'fox', 'fish']

This adds a function to the list

You can also create an empty list and add elements one by one

>>> fruits = []

>>> fruits.append('apple')
>>> fruits.append('banana')
>>> fruits.append('cherry')
>>> print(fruits)

The result is

['apple', 'banana', 'cherry']

But functions added in this way are always in the last

So you need a way to insert elements

Use the insert() method to add new elements anywhere in the list. To do this, you need to specify the index and value of the new element:

>>> fruits.insert(0,'lemon')
>>> print(fruits)

Using this method, 'lemon' is inserted at the beginning of the list, which moves all elements in the list one position to the right

['lemon', 'apple', 'banana', 'cherry']
  • Delete element in list

Delete elements with del statement

The premise of del statement is to know the location of the element to be deleted

>>> fruits = ['apple','banana','orange']
>>> print(fruits)
['apple', 'banana', 'orange']
>>> del fruits[0]
>>> print(fruits)
['banana', 'orange']

Deleted the first element in the list using the del statement

['apple', 'banana', 'orange']
['banana', 'orange']

Using del, you can delete list elements anywhere, provided you know the index

Use the method pop() to delete elements

The pop() method removes the element at the end of the list and allows you to continue using it

>>> fruits = ['apple','banana','orange']
>>> print(fruits)
['apple', 'banana', 'orange']

>>> popend_fruits = fruits.pop()
>>> print(fruits)
['apple', 'banana']
>>> print(popend_fruits)
orange

If the fruit is bought by time, I would like to know what kind of fruit is the last one to buy?

>>> fruits = ['apple','banana','orange']
>>> print(fruits)
['apple', 'banana', 'orange']

>>> last_buy = fruits.pop()
>>>Print ("the last fruit I bought was" + last buy. Title())
The last fruit I bought was Orange

Elements anywhere in the pop-up list

In fact, pop() can be used to pop up any element in the list, simply specifying the index of the element to be removed in parentheses

>>> fruits = ['apple','banana','orange']
>>> print(fruits)
['apple', 'banana', 'orange']

>>> second_fruits = fruits.pop(1)
>>> print(second_fruits)
apple

Sometimes you don't know where the element is in the list. If you only know the value of the element to delete, you can use the method remove()

Suppose we want to remove the value 'apple' from the list

>>> fruits = ['apple','banana','orange']
>>> print(fruits)
['apple', 'banana', 'orange']

>>> fruits.remove('apple')
>>> print(fruits)
['orange', 'banana']

Use remove() to let Python know where 'apple' appears and remove the element

Give it a try

Guest list: if you could invite anyone to dinner, who would you invite? Create a list of at least 3 people you want to invite; then. Use this list to print messages and invite these people to dinner with you.

#Guest list
guest = ['Harry','Ben','Babo','Jack']
for i in range(0,4):
     print("I would like to invite" + guest[i].title() + "to dinner with me. ""
        
I'd like to invite Harry to dinner with me.
I'd like to invite Ben to dinner with me.
I'd like to invite Babo to dinner with me.
I'd like to invite Jack to dinner with me.
guest = ['Harry','Ben','Babo','Jack']
print("I would like to invite" + guest[0].title()+"," +guest[1].title() +","+guest[2].title() +","+guest[3].title() + "to have dinner with me. ""

I'd like to invite Harry, Ben, Babo and Jack to dinner with me.

Revise the guest list: you just learned that one guest could not attend the appointment, so you need to invite another guest

#List of guests
guest = ['Harry','Ben','Babo','Jack']
guest.remove('Babo')
guest.insert(2,'Mical')
print("I would like to invite"+guest[0].title()+"," +guest[1].title() +","+guest[2].title() +","+guest[3].title()+"Come and have dinner with me.")

//I'd like to invite Harry,Ben,Mical,Jack to dinner with me.

Add guest: you have found a larger table that can accommodate more guests. Please invite three more guests

  • Use insert() to add a guest at the beginning and middle of the invitation list
  • Use append() to add the last new guest to the end of the list
  • Print a message to invite each guest on the list
guest = ['Harry','Ben','Babo','Jack']
guest.remove('Babo')
guest.insert(2,'Mical')
guest.insert(0,'Batman')
guest.insert(2,'Ironman')
guest.append('Superman')
for i in range(0,8):
    print("I would like to invite" + guest[i].title() + "to dinner with me. ""
    
    
I'd like to invite Batman to dinner with me.
I'd like to invite Harry to dinner with me.
I'd like to invite Ironman to dinner with me.
I'd like to invite Ben to dinner with me.
I'd like to invite Mical to dinner with me.
I'd like to invite Jack to dinner with me.
I'd like to invite Superman to dinner with me.

Shortlist: you just learned that the newly purchased table can't arrive on time, so you can only invite two guests

  • At the end of the program, print the information that you can only invite two guests
  • Use pop() to delete the guests in the list until there are only two guests left. If a guest pops up from the list every time, a message will be printed to let the guest know the situation. We can't have dinner with you
  • For the remaining two guests, print a message to inform them that they are still among the invited guests
guest = ['Harry','Ben','Babo','Jack']
guest.remove('Babo')
guest.insert(2,'Mical')
guest.insert(0,'Batman')
guest.insert(2,'Ironman')
guest.append('Superman')

print("I'm very sorry, because of the table, I can only invite three people to my dinner"+"\n\n")

one_guest = guest.pop()
print("so sorry"+ one_guest+"I can't invite you to my dinner")
two_guest = guest.pop()
print("so sorry"+ two_guest+"I can't invite you to my dinner")
three_guest = guest.pop()
print("so sorry"+ three_guest+"I can't invite you to my dinner")
four_guest = guest.pop()
print("so sorry"+ four_guest+"I can't invite you to my dinner"  + "\n\n")
for i in range(0,4):
    print("Hello"+guest[i].title()+"You are still among my guests.")

I'm very sorry, because of the table, I can only invite three people to my dinner


I'm sorry Superman can't invite you to my dinner
 I'm sorry Jack can't invite you to my dinner
 I'm very sorry that Mical can't invite you to my dinner
 I'm sorry Ben can't invite you to my dinner


Hello, Batman, you are still among my guests.
Hello Harry, you are still among my guests.
Hello, Ironman. You are still among my guests.
  • Organization list

In the list you created. The arrangement of elements is often unpredictable, because you don't always have control over user supplied data.

Use the method sort() to permanently sort the list

The sort() method in Python makes it easier to sort lists. Suppose you have a list of cars in alphabetical order.

cars = ['bmw','audi','fengtian','dazhong']
cars.sort()
print(cars)


['audi', 'bmw', 'dazhong', 'fengtian']

You can also sort in reverse alphabetical order by passing the parameter reverse=True to the sort() method

cars = ['bmw','audi','fengtian','dazhong']
cars.sort(reverse=True)
print(cars)


['fengtian', 'dazhong', 'bmw', 'audi']

Use the function sorted() to sort the list temporarily

If you want to keep the original list, you can use the function sorted() to sort the list temporarily

cars = ['bmw','audi','fengtian','dazhong']
print("Using functions sorted()Arranged list")
print(sorted(cars))

print("Original list")
print(cars)

A list arranged with the function sorted()
['audi', 'bmw', 'dazhong', 'fengtian']
Original list
['bmw', 'audi', 'fengtian', 'dazhong']

Print list backwards

You can use the method reverse(). Assuming that the cars are arranged according to the purchase time, you can easily arrange the cars in the opposite order

cars = ['bmw','audi','fengtian','dazhong']
print("Original list")
print(cars)

print("In reverse order of purchase time")
cars.reverse()
print(cars)

Original list
['bmw', 'audi', 'fengtian', 'dazhong']
In reverse order of purchase time
['dazhong', 'fengtian', 'audi', 'bmw']

Determine the length of the list -- using the len() function

print("the length of the list")
print(len(cars))

Length of the list
4

day_04

  • Traverse the entire list

When we create a list, we need to output the whole list, but usually the list will be long and contain many elements. When the length of the list changes, we must modify the code. With the for loop, we can easily output the entire list.

#Traverse the entire list to create a fruit list
fruits = ['apple','orange','banana','cherry']
for i in fruits:
    print(i)
apple
orange
banana
cherry
  • Do more in the for loop

Print a message for each fruit to show that I like this fruit so much

fruits = ['apple','orange','banana','cherry']
for i in fruits:
    print("I really like it,"+i.title()+"This fruit.")
    print("I eat it every day"+i.title()+".\n")
I really like it, Apple.
I eat Apple every day

I really like it, Orange.
I eat Orange every day

I really like it, Banana.
I eat Banana every day

I really like it, Cherry.
I eat Cherry every day

day_05

if statement

A simple example

cars =['audo','bwm','benchi','toyota']
for i in cars:
    if i=='bwm':
        print(i.upper())
    else:
        print(i.title())

If there is any 'bmw' in the list, it will be printed in full capitals. Otherwise, it will be printed in initial capitals.

Audo
BWM
Benchi
Toyota
  • Condition test

At the core of each if statement is an expression with values of True and false, which is called a conditional test. Python determines whether to execute the code in the if statement based on whether the value of the conditional test is True or false.

Check that a specific value is included in the list

To determine whether a particular value is already in the list, use the keyword in.

>>> aminal = ['lion','tiger','birl','monkey']
>>> 'lion' in aminal
True
>>> 'fish' in aminal
False

Check that specific values are not included in the list

aminal = ['lion','tiger','birl','monkey']
aaa = 'fish'
if aaa not in aminal:
     print(aaa.title()+"Not in animal list")
Fish is not in the animal list
  • Omit else statement block

Else is an all inclusive statement. As long as the conditional tests in if or elif are not met, the code in it will execute, which may introduce invalid or even malicious data. If you know the final conditions to test, consider using an elif code instead of an else code block. This way, you can be sure that your code will run only if the conditions are met.

  • Test multiple conditions

If elif else: the structure is powerful, but it is only suitable for one condition: Python skips the rest of the tests after passing the tests. This kind of behavior is very good and efficient. Allows you to test a specific condition.

However, there are times when you have to check all the conditions you care about. In this case, you should use a simple if statement that does not contain code blocks for elif and else. This method is suitable for multiple conditions that are true and need to perform related operations under each true condition.

essage = ['mushroom','tea','buger','dumpling']

if 'dumpling' in essage:
    print("Have a guest order dumpling")
if 'tea' in essage:
    print("Have a guest order tea")
if 'apple' in essage:
    print("Have a guest order apple")

print("\n Order over")
There are guests ordering dinner
 Have a guest order tea

Order over

If you use the if elif else statement, the code will not run correctly, because after one test passes, the remaining tests will be skipped:

essage = ['mushroom','tea','buger','dumpling']

if 'dumpling' in essage:
    print("Have a guest order dumpling")
elif 'tea' in essage:
    print("Have a guest order tea")
elif 'apple' in essage:
    print("Have a guest order apple")
    
print("\n Order over")
There are guests ordering dinner

Order over
  • Use if statement to process list

Check special elements

Continue to use the previous example, when the restaurant is making, the guest prints a message every time he orders a dish. By creating a list and using a loop to print out what the guest ordered:

essage = ['mushroom','tea','buger','dumpling']
for i in essage:
    print("Have a guest order"+i.title())
print("\n Order over")
Have guests order Mushroom
 We have guests to order, Tea
 Have a guest order, Buger
 There are guests ordering dinner

Order over

The output is very simple. The above code is just a simple foe statement

However, if the restaurant runs out of tea, how to deal with it?

essage = ['mushroom','tea','buger','dumpling']
for i in essage:
    if i == 'tea':
        print("Sorry, there's no one in the store tea")
    else:
        print("Have a guest order"+i.title())
print("\n Order over")
Have guests order Mushroom
 Sorry, there's no tea in the store
 Have a guest order, Buger
 There are guests ordering dinner

Order over

Day 06 (Dictionary)

  • A simple dictionary

Create an alien dictionary

alien_0 = {'color':'green','points':5,'X_position':4,'Y_position':5,'speed':'unknow'}
print(alien_0['color'])
print(alien_0['points'])

new_color = alien_0['color']
new_points = alien_0['points']
print("Congratulations, you beat one"+ new_color +"Alien, got"+str(new_points) +"Points.")
  • Add key value pair
alien_0['X_position'] = 4
alien_0['Y_position'] = 5
print(alien_0)
  • Modify values in dictionary
print("The current color of aliens is:"+alien_0['color'])

alien_0 = {'color':'red'}
print("The current color of aliens is:"+alien_0['color'])
  • Change the alien's position
alien_0 = {'color':'green','points':5,'X_position':4,'Y_position':5,'speed':'unknow'}

#The original coordinates of Aliens
print("Location of Aliens("+ str(alien_0['X_position']) +","+ str(alien_0['Y_position']) +")" )
add_number = 0
for i in range(10):
    if alien_0['speed'] == 0:
        add_number+=1
    elif alien_0['speed']  == 'unknow':
        add_number+=2
    else:
        add_number+=3
    
#New position equals old position plus increment
    alien_0['X_position'] = alien_0['X_position'] + add_number
    alien_0['Y_position'] = alien_0['Y_position'] + add_number
    print("Now the alien coordinates are("+ str(alien_0['X_position']) +","+ str(alien_0['Y_position']) +")")
Location of Aliens (4,5)
Now the alien coordinates are (6,7)
Now the alien coordinates are (10,11)
Now the alien coordinates are (16,17)
Now the alien coordinates are (24,25)
Now the alien coordinates are (34,35)
Now the alien coordinates are (46,47)
Now the alien coordinates are (60,61)
Now the alien coordinates are (76,77)
Now the alien coordinates are (94,95)
Now the alien coordinates are (114115)
  • Delete key value pair

For values no longer needed in the dictionary, you can use the del statement to completely delete the corresponding key value pair. When using the del statement, you must specify the dictionary name and the key to delete.

In the following code, alien_ Delete key 'points' and its value in 0:

alien_0 = {'color':'green','points':5,'X_position':4,'Y_position':5,'speed':'unknow'}
print(alien_0)

del alien_0['points']
print(alien_0)

{'color': 'green', 'points': 5, 'X_position': 4, 'Y_position': 5, 'speed': 'unknow'}
{'color': 'green', 'X_position': 4, 'Y_position': 5, 'speed': 'unknow'}

Deleted key value pair, forever disappear

  • A dictionary of similar objects

When using a dictionary to store multiple key value pairs, you can use the following format:

favorite_language = {
    'herry':'java',
    'mical':'python',
    'jun':'ruby',
    'lily':'C'
    }
print("herry My favorite language is:"+ favorite_language['herry'].title())
herry's favorite language is Java

This example demonstrates how to split a long print statement into multiple lines.

  • Ergodic dictionary

Traverse all key value pairs

The user name, first name, and last name of a user are stored in the following Dictionary:

user_0= {
    'user_name':'GHP',
    'first':'G',
    'last':'P'
    }
for key,value in user_0.items():  #Using two variables to store keys and values respectively
    print('\n key: '+key)
    print('value: '+value)

You can use for to traverse the dictionary

Key: user_name
 Value: GHP

Key: first
 Value: G

Key: last
 Value: P
  • Traverse all keys in the dictionary
user_0= {
    'user_name':'GHP',
    'first':'G',
    'last':'P'
    }
for name in user_0.keys():
    print(name.title())

User_Name
First
Last

Create a list and use the values in the list to traverse the dictionary

favorite_language = {
    'herry':'java',
    'mical':'python',
    'jun':'ruby',
    'lily':'C'
    }
friends = ['herry','mical']
for name in favorite_language.keys():
    print(name.title())

    if name in friends:
        print("Hello," + name.title() + "I know your favorite language is" + favorite_language[name].title())
Herry
 Hello, Herry. I know your favorite language is Java
Mical
 Hello, Mical. I know your favorite language is Python
Jun
Lily

Iterate through all keys in the dictionary in order

Dictionaries always record the relationship between keys explicitly, but the order of getting dictionary elements is unpredictable.

You can use sorted() to get a copy of a list of keys in a specific order:

favorite_language = {
    'herry':'java',
    'mical':'python',
    'jun':'ruby',
    'lily':'C'
    }

for name in sorted(favorite_language.keys()):
    print(name.title()+"thank you\n")
=================RESTART: H:\python practice \ Python \ Python 38-32 \ dictionary.py================
Herry, thank you

Jun, thank you

Lily, thank you

Thank you, Mical

>>> 
=================RESTART: H:\python practice \ Python \ Python 38-32 \ dictionary.py================
Herry, thank you

Jun, thank you

Lily, thank you

Thank you, Mical

Output twice, in the order of keys in the dictionary

Traverse all values in dictionary

If you just want to output all the values in the dictionary, not the key, you can use the method values(), which returns a list of values without any values.

favorite_language = {
    'herry':'java',
    'mical':'python',
    'jun':'ruby',
    'lily':'C'
    }

for language in sorted(favorite_language.values()):
    print("Their favorite languages are:"+language.title())
Their favorite language is: C
 Their favorite language is Java
 Their favorite language is Python
 Their favorite language is Ruby
  • nesting

Sometimes you need to store a series of dictionaries in a list, or a list as a value in a dictionary, which is called nesting. You can nest dictionaries in lists, lists in dictionaries, and even dictionaries in dictionaries.

Dictionary list

How to manage swarms of aliens? One way is to create a list of aliens, each of which is a dictionary with information about aliens.

alien_0 = {'color':'green','points':3}
alien_1 = {'color':'red','points':4}
alien_2 = {'color':'orange','points':6}

aliens = [alien_0,alien_1,alien_2]

for alien in aliens:
    print(alien)
{'color': 'green', 'points': 3}
{'color': 'red', 'points': 4}
{'color': 'orange', 'points': 6}

Now we use range() to generate 30 Aliens:

#Create an empty list of Aliens
aliens = []

#Create 30 aliens
for alien in range(30):
    new_aliens = {'color':'green','points':3}
    aliens.append(new_aliens)

#Show five aliens
for alien in aliens[:5]:
    print(alien)

print("...\n")
print("A total of"+ str(len(aliens))+"Robots.")
{'color': 'green', 'points': 3}
{'color': 'green', 'points': 3}
{'color': 'green', 'points': 3}
{'color': 'green', 'points': 3}
{'color': 'green', 'points': 3}
...

A total of 30 robots were created.

Modify the relevant value of each robot

#Create an empty list of Aliens
aliens = []

#Create 30 aliens
for alien in range(30):
    new_aliens = {'color':'green','points':3}
    aliens.append(new_aliens)
    
#Show five aliens
for alien in aliens[0:3]:
    if alien['color'] == 'green':
        alien['color'] = 'red'
        alien['points'] = 6

for alien in aliens[0:7]:
    print(alien)

print("...\n")
print("A total of"+ str(len(aliens))+"Robots.")
{'color': 'red', 'points': 6}
{'color': 'red', 'points': 6}
{'color': 'red', 'points': 6}
{'color': 'green', 'points': 3}
{'color': 'green', 'points': 3}
{'color': 'green', 'points': 3}
{'color': 'green', 'points': 3}
...

A total of 30 robots were created.

You can also add some conditions

#Show five aliens
for alien in aliens[0:3]:
    if alien['color'] == 'green':
        alien['color'] = 'red'
        alien['points'] = 6
    elif alien['color'] == 'red':
        alien['color'] = 'green'
        alien['points'] = 3

Store list in dictionary

Store pizza information

pizza = {
        "Facial skin":"Durian skin",
        "Seasoning":["Durian","shrimp","beef","Cheese"]
    }

#Error. The list cannot be output directly. It needs to be traversed with a loop. No more errors
'''print("You ordered pizza number one, yes"+pizza["Facial skin"]+","+"It has"+pizza["Seasoning"]+"Of pizza.")'''
print("You ordered number one"+pizza["Facial skin"]+"Pizza")

for i in pizza["Seasoning"]:
    print("The ingredients in pizza 1 are\t"+i)

You ordered No.1 durian pizza
 Durian is one of the ingredients in pizza 1
 The sauce in pizza 1 is shrimp
 The sauce in pizza 1 is beef
 Cheese is the sauce in pizza 1

Output everyone's favorite language:

favorite_language = {
    'harry':['python','php'],
    'merry':['java'],
    'micle':['c'],
    'ben':['Embedded','c++']
    }

for k,v in favorite_language.items():
    print("\n"+k+"What I like")
    for language in v:
        print("\t"+language.title())
What harry likes
	Python
	Php

What merry likes
	Java

What Michael likes
	C

What ben likes
	Embedded
	C++

Store dictionary in dictionary

Create a city dictionary

cities = {
    'Beijing':{
        'population':3000000,
        'country':'China',
        'foods':['Beijing Roast Duck','Bean juice']
        },
     'GuangZhou':{
        'population':20000000,
        'country':'China',
        'foods':['Yuntun','Steamed Pork Dumplings']
        },
     'NewYork':{
        'population':4000000,
        'country':'U.S.A',
        'foods':['hamburger','steak']
        }
    }

for k,v in cities.items():  #v is a little dictionary
    print("\n The name of the city"+k)
    new_population = v['population']
    countries = v['country']
    print("Its population has"+str(new_population))
    print("This city belongs to"+countries)
    for food in v['foods']:
        print("Their favorite food is:"+food)
The name of the city
 It has a population of 3000000
 This city belongs to China
 Their favorite food is Beijing roast duck
 Their favorite food: bean juice

City Name: GuangZhou
 It has a population of 20000000
 This city belongs to China
 Their favorite food is: wonton
 Their favorite food is: roast wheat

The name of the city, New York
 It has a population of 4000000
 This city belongs to the United States
 Their favorite food is hamburger
 Their favorite food is steak

day_07 (user input and while loop)

  • Use while loop

The difference between the while loop and the for loop is that the for loop is used for a code block for each element in the collection, while the while loop runs continuously until the specified conditions are not met:

Use the while loop to count:

#while Loop 
i = 0
while (i<5):
    i+=1
    print(i)
    
1
2
3
4
5

Let users choose when to exit

message_0 = "You have two choices, either enter a message or enter'quit'Exit program"

message_1 = " "

while message_1 != 'quit':
    message_1 = input(message_0)
    print(message_1)

You have two choices, either enter a message or enter 'quit' to exit the program. Hello
 How do you do
 You have two choices, either enter a message or enter 'quit' to exit the program hello
hello
 You have two choices, either enter a message or enter 'quit' to exit the program
quit

Do not output the last quit, you need to add a judgment statement;

message_0 = "You have two choices, either enter a message or enter'quit'Exit program"
message_1 = " "

while message_1 != 'quit':
    message_1 = input(message_0)
    if message_1 !='quit':
        print(message_1)
You have two choices, either enter a message or enter 'quit' to exit the program, regardless of what others have
 Don't care what others have
 You have two choices, either enter a message or enter 'quit' to exit the program
  • Use logo

In a program that requires many conditions to be met before it can continue to run, a variable can be defined to determine whether the entire program is active. This variable, known as a sign, acts as a traffic light for the program. You can keep the program running when the flag is True, and stop the program when any event causes the value of the flag to be false. In this way, you only need to check out one condition in the while statement - whether the current value of the flag is True or not, and put all the tests in other places to make the program more concise.

message_0 = "You have two choices, either enter a message or enter'quit'Exit program"
message_1 = " "
active = True
while active:
    message_1 = input(message_0)
    if message_1  =='quit':
        active = False
    else:
        print(message_1)
You have two options, either enter a message or enter 'quit' to exit nihao
nihao
 You have two choices, either enter a message or enter 'quit' to exit the program
  • Use the while loop to work with lists and dictionaries
#Move elements between lists
#First create two lists
first_list = ['apple','orange','cherry','banana']
second_list = []

#Verify each element until there are no elements
#Move each verified element to an empty list
while first_list:
    fruits = first_list.pop()

    print("Verified elements:"+fruits.title())
    second_list.append(fruits)

#Show all validated elements
print("\n Verified elements")
for i in second_list:
    print(i)
Verified element: Banana
 Verified element: Cherry
 Validated element: Orange
 Verified element: Apple

Verified elements
banana
cherry
orange
apple

Delete all list elements that contain a specific value

There are multiple identical elements in the list. How can we just delete the same elements

#Create a pet list
pets = ['dog','cat','dog','cat','fish','rabbit','cat']
print(pets)

while 'cat' in pets:
    pets.remove('cat')

print(pets)
['dog', 'cat', 'dog', 'cat', 'fish', 'rabbit', 'cat']
['dog', 'dog', 'fish', 'rabbit']

Use user input to fill in the dictionary

#Fill dictionary with user input
responses = {}  #Create an empty dictionary

#Set a label to indicate whether the investigation continues
active = True

while active:
    #Prompt for the name and answer of the respondent
    name = input("Please enter your name:")
    response = input("What would you like to eat?")

    responses[name] = response

    #See if anyone else is involved in the investigation
    message = input("Is there anyone else involved in the investigation[yes/no]")
    if message == "no":
        active = False

print("\n Findings")
for name,response in responses.items():
    print(name.title()+"Like to eat"+response.title()+". \n")
Please enter your name: ghp
 What do you like to eat? Watermelon
 Is there anyone else involved in the investigation [yes/no]yes
 Please input your name: lily
 What do you like? Hami melon
 Is there anyone else involved in the investigation [yes/no]no

Findings
 Ghp likes watermelon.

Lily likes to eat cantaloupe.

day_ 08 (function)

  • Defining functions
#Define a function
def greet_user():
    print("Hello!!!")

greet_user()
Hello!!!

Passing information to a function

In greet_user() adds a parameter in parentheses

#Define a function
def greet_user(username):
    print("Hello\t"+username.title()+"\t!!!")

greet_user('GHP')
Hello	Ghp	 !!!

Formal and actual parameters

In the function greet_ In the definition of user(), the variable username is a parameter - a piece of information required by the function to complete its work. In code greet_ In user ('ghp '), the value' GHP 'is an argument. An argument is the information passed to a function when it is called. When we call a function, we put the information we want the function to use in parentheses. At greet_ In user ('ghp '), the argument' GHP 'is passed to the function greet_user(), which is stored in the parameter username.

  • Pass arguments

Position argument

A function to display pet information:

def pets(animal_type,animal_name):
    '''Display pet information'''
    print("I have one"+animal_type)
    print("\n Its name is"+animal_name)

pets('Short tailed cat','harry')
I have a short tailed cat

Its name is harry

Call function multiple times

def pets(animal_type,animal_name):
    '''Display pet information'''
    print("I have one"+animal_type)
    print("Its name is"+animal_name+"\n")

pets('Short tailed cat','harry')
pets('Harpy dog','ben')
I have a short tailed cat
 Its name is harry

I have a harpy
 Its name is ben

The order of positional arguments is important

Keyword arguments

Using keyword arguments does not need to consider the sequential calls in the function,

def pets(animal_type,animal_name):
    '''Display pet information'''
    print("I have one"+animal_type)
    print("Its name is"+animal_name+"\n")

pets('Short tailed cat','harry')
pets(animal_name='micle',animal_type='Sandskin cat')
I have a short tailed cat
 Its name is harry

I have a Shapi cat
 Its name is Michael

Default

def pets(animal_name,animal_type ='Dog'):
    '''Show pet information'''
    print("I have one"+animal_type)
    print("Its name is"+animal_name+"\n")

pets('happy')
I have a dog
 Its name is happy

Equivalent function call

  • Return value

The value returned by the function is called the return value

Return simple value

def get_name(first_name,second_name):
    full_name = first_name+ '  ' + second_name
    return full_name

name_01 = get_name('week','Jay')
print(name_01)
Jay Chou

Make arguments optional

def get_name(first_name,last_name,middle_name = ''):
    if middle_name:
        full_name = first_name +' ' + middle_name +' ' + last_name +"\n"
    else:
        full_name = first_name +' ' + last_name +"\n"
    return full_name

name_01 = get_name('week','Jie','Lun')
print(name_01)

name_02 = get_name('week','Jie')
print(name_02)

Python interprets non empty strings as True, so if middle is provided in a function call_ Name will be True

Zhou lunjie

Zhou Jie

Return to dictionary

def build_person(first_name,last_name):
    person = {'first':first_name,'last':last_name}
    return person

message = build_person("Jay Chou","Zhang Xueyou")
print(message)

{'first': 'Jay Chou', 'last': 'Zhang Xueyou'}

Storage age

def build_person(first_name,last_name,age = ''):
    person = {'first':first_name,'last':last_name}
    if age:
        person['age'] = age
    return person

message = build_person("Jay Chou","Zhang Xueyou",28)
print(message)


{'first': 'Jay Chou', 'last': 'Zhang Xueyou', 'age': 28}

Using functions with while loops

def get_name(first_name,second_name):
    full_name = first_name+ " " +second_name
    return full_name

while True:
    print("Please enter your name")
    print("input'q' Exit program after")

    f_name = input("Please enter your last name")
    if f_name == 'q':
        break
    l_name = input("Please enter your name")
    if l_name == 'q':
        break
    your_name = get_name(f_name,l_name)
    print("Hello,"+your_name+"\n")

Please enter your name
 Enter 'q' to exit the program
 Please enter your last name week
 Please enter your name, Jay
 Hello, Jay Chou

Please enter your name
 Enter 'q' to exit the program
 Please enter your last name q
>>> 
  • Delivery list

Suppose there is a list of users, and I want to greet each of them. The following example passes a list of names to a list called greet_ Functions for users()

#Pass list to function
def greet_user(names):
    for name in names:
        message = "Hello,"+ name+". \n"
        print(message)

user_name = ['harry','ben','jack']
greet_user(user_name)

Hello, harry.

Hello, ben.

Hello, jack.

Modify list in function

A company that produces 3D printing models for user submitted designs. Designs that need to be printed are stored in one list and moved to another after printing. Here is the code to simulate this process without using the function:

#First, create a list that contains some software to print
first_list = ['iphone case','robot pendant','dodecahedron']
completed_models = []

#Simulate printing each design until there is no printed design
#After printing each design, move it to the list completed_ In models
while first_list:
    current_design = first_list.pop()

    #Simulate the process of making 3D printing model according to design
    print("Print model:"+ current_design)
    completed_models.append(current_design)

#Display all printed models
print("\n All printed models")
for completed_model in completed_models:
    print(completed_model )

Print model: dodecahedron
 Print model: robot pendant
 Print model: iphone case

All printed models
dodecahedron
robot pendant
iphone case
  • Pass any number of arguments

Sometimes you don't know how many parameters to accept

For example, a function that makes pizza needs to accept many ingredients, but you can't predict how many ingredients customers need. The following functions have only one parameter, but no matter how many arguments are provided, they are all included in the bag:

def make_pizza(*toppings):  #Asterisk * allows Python to create a new metagroup called toppings
    '''   Print customer order ingredients'''
    print(toppings)

make_pizza('Durian')
make_pizza('Ham','pork','beef','Cheese','shrimp')
('Durian',)
('Ham', 'pork', 'beef', 'Cheese', 'shrimp')

Traverse customer requirements

def make_pizza(*toppings):
    '''   Print customer order ingredients'''
    print("\n The ingredients in the pizza ordered by the customer are")
    for i in toppings:
        print(i,end=" ")

make_pizza('Durian')
make_pizza('Ham','pork','beef','Cheese','shrimp')
The ingredients in the pizza ordered by the customer are
 Durian 
The ingredients in the pizza ordered by the customer are
 Ham, pork, beef, cheese and shrimp 

Combining positional arguments with arbitrary number arguments

If the previous function also needs an argument representing the pizza size, it must be placed in front of the parameter * toppings:

def make_pizza(size,*toppings):
    '''   Print customer order ingredients'''
    print("\n The size of the pizza ordered by the customer is"+str(size)+",Among them, the ingredients are")
    for i in toppings:
        print(i,end=" ")

make_pizza(14,'Durian')
make_pizza(12,'Ham','pork','beef','Cheese','shrimp')

The size of the pizza ordered by the customer is 14, among which the ingredients are
 Durian 
The size of the pizza ordered by the customer is 12, among which the ingredients are
 Ham, pork, beef, cheese and shrimp 

Use any number of keyword arguments

Create a dictionary in the function to hold the key value pairs entered

def user_name(xing,ming,**other):
    name = {}
    print("Your last name is:")
    name['surname'] = xing
    print(name['surname'])
    
    print("Your name is:")
    name['name'] = ming
    print(name['name'] )
    for k,v in other.items():
        name[k] = v
    return name

message = user_name('week','Jay',hobby='Play basketball',goodfor='sing')
print(message)

Your last name is:
week
 Your name is:
Jay
 {'last name': 'week', 'first name': 'Jay', 'hobby': 'playing basketball', 'good for': 'singing'}
  • Store functions in modules

Import specific functions

from module name import function name
 from module name import function name 1, function name 2, function name 3

Using as to assign aliases to functions

from module name import function name as other name

Using as to assign an alias to a module

import module name as other name

Import all functions of the module

Use * to import all functions in a module

from module name import*

day_ 09 (class)

Creating objects according to requirements is called instantiation. When creating objects based on classes, each object automatically has this general behavior, and then each object can be given a unique personality as required. With object-oriented programming, I can simulate real-world situations to a degree that surprises me.

  • Create and use classes

Create a Dog class so that each instance stores the name and age. We will give the Dog the ability to squat and roll.

#encoding:utf-8
class Dog():
    '''A simple attempt to simulate a dog'''
    def __init__(self,name,age):
        '''Initialize properties name and age'''
        self.name = name
        self.age = age
        
    def sit(self):
        '''Simulation dog is ordered to squat'''
        print(self.name.title()+"Now it's down")
        
    def roll_over(self):
        '''Simulate a dog rolling when ordered'''
        print(self.name.title()+"Now it's rolling")
        
  1. Methods__ init__ ()

    The init() method is a special method that Python runs automatically when you create an instance based on a Dog class. In the name of this method, there are two underscores at the beginning and the end, which is a convention to avoid name conflicts between Python default methods and ordinary methods.

    We will__ init__ () is defined as three parameters: self, name, age. In this method. Parameter self is necessary, and must be in front of other parameters. Why must self be included? Because when Python calls this method to create a Dog instance, it will automatically pass in the argument self. Each method associated with a class automatically passes the parameter self, which is a reference to the instance itself, allowing the instance to access the properties and methods in the class.

    Variables prefixed with self can be used by all methods in the class, and we can also access these variables through any instance of the class. Variables that can be accessed through an instance are called properties.

Create instance from class

Next, create an instance representing a specific Dog (based on the Dog class created above):

my_dog = Dog('harry',12)

print("My dog's name is"+my_dog.name.title()+". ")
print("\n My dog is now"+str(my_dog.age)+"Years old.")
My dog's name is Harry.

My dog is now 12 years old.

Call method

my_dog = Dog('harry',12)

my_dog.sit()
my_dog.roll_over()
Harry's down now
 Harry is rolling now

Create multiple instances

#Access properties
my_dog = Dog('harry',12)

print("My dog's name is"+my_dog.name.title()+". ")
print("My dog is now"+str(my_dog.age)+"Years old.")
#Call method
my_dog.sit()
my_dog.roll_over()

#Create multiple instances
your_dog = Dog('jack',11)

print("\n Your dog's name is"+your_dog.name.title()+". ")
print("Your dog is now"+str(your_dog.age)+"Years old.")

your_dog.sit()
your_dog.roll_over()
My dog's name is Harry.
My dog is now 12 years old.
Harry's down now
 Harry is rolling now

Your dog's name is Jack.
Your dog is 11 years old now.
Jack's down now
 Jack is rolling now

  • Try it yourself

Restaurant: create a class called resturant with methods__ init__ () set two properties: restaurant_name and cuisine_type . Create a description_ The method of restaurant () and a method named open_ The restaurant () method, where the former prints both of the above information and the latter prints a message indicating that the restaurant is open.

According to this class, create an instance named restaurant, print its two properties respectively, and then call the two methods mentioned above.

#encoding:utf-8
class Restaurant():
    def __init__(self,restaurant_name,cuisine_type):
        '''Two attributes of creating a restaurant'''
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type

    def describe_restaurant(self):
        print("The name of this restaurant is"+self.restaurant_name.title())
        print("The type of cooking in this restaurant is"+self.cuisine_type)


    def open_restaurant(self):
        print("The restaurant is open")
        
#Create an instance named message
message_01 = Restaurant('mqilin','western restaurant')
message_02 = Restaurant('guangzhou restaurant ','Cantonese food')

message_01.open_restaurant()
message_01.describe_restaurant()
print("\n")
message_02.open_restaurant()
message_02.describe_restaurant()
The restaurant is open
 The name of this restaurant is Mqilin
 This restaurant is a Western Restaurant


The restaurant is open
 The name of this restaurant is Guangzhou Restaurant
 The cuisine of this restaurant is Cantonese

  • Using classes and instances

car

Next, write a class representing a car, which stores information about the car, and a method to summarize the information:

#encoding:utf-8
class Car():
    '''A simple attempt to simulate a car'''

    def __init__(self,make,model,year):
        '''Initialize car properties'''
        self.make = make
        self.model = model
        self.year = year

    def get_descriptive_name(self):
        '''Return concise information description'''
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name

my_new_car = Car('BMW','a1',2020)
print(my_new_car.get_descriptive_name())

2020 BMW a1

Next, add a time-varying attribute to it, which stores the total mileage of the car.

Assign default values to properties

Add a new one called odometer_reading, with an initial value of 0. We also added a read_odometer method, used to read the odometer of the car:

#encoding:utf-8
class Car():
    '''A simple attempt to simulate a car'''

    def __init__(self,make,model,year):
        '''Initialize car properties'''
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self):
        '''Return concise information description'''
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name

    def read_odometer(self):
        '''Print a message indicating the vehicle mileage'''
        print("Your car has gone"+str(self.odometer_reading)+"km!")

my_new_car = Car('BMW','a1',2020)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
2020 BMW a1
 Your car has driven 0 km!

Modify the value of the property

#encoding:utf-8
class Car():
    '''A simple attempt to simulate a car'''

    def __init__(self,make,model,year):
        '''Initialize car properties'''
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self):
        '''Return concise information description'''
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name

    def read_odometer(self):
        '''Print a message indicating the vehicle mileage'''
        print("Your car has gone"+str(self.odometer_reading)+"km!")

my_new_car = Car('BMW','a1',2020)
print(my_new_car.get_descriptive_name())
# my_new_car.read_odometer()

my_new_car.odometer_reading = 23
my_new_car.read_odometer()

Modify the value of the property directly

​~~~
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
2020 BMW a1
 Your car has driven 23km!

Method to modify the value of a property

​~~~
my_new_car.update_odmoeter(25)
my_new_car.read_odometer()
2020 BMW a1
 Your car has driven 25km!

You can update_odometer () is extended to do extra work when modifying odometer readings. Add some logic below to prevent anyone from calling back the odometer reading:

​~~~
 def update_odmoeter(self,message):
        '''
        Set the odometer reading to the specified value
        The odometer reading shall not be recalled
        '''
        if message >= self.odometer_reading:
            self.odometer_reading = message
        else:
            print("you can't call back values")
​~~~

Method to increment the value of an attribute

#encoding:utf-8
class Car():
    '''A simple attempt to simulate a car'''

    def __init__(self,make,model,year):
        '''Initialize car properties'''
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self):
        '''Return concise information description'''
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name

    def read_odometer(self):
        '''Print a message indicating the vehicle mileage'''
        print("Your car has gone"+str(self.odometer_reading)+"km!")

    def update_odmoeter(self,message):
        '''
        //Set the odometer reading to the specified value
        //The odometer reading shall not be recalled
        '''
        if message >= self.odometer_reading:
            self.odometer_reading = message
        else:
            print("You can't call back values")

    def increment_odometer(self,mil_message):
        '''Increase odometer reading'''
        self.odometer_reading += mil_message

my_use_car = Car('Honda','Accord',2015)
print(my_use_car.get_descriptive_name())

my_use_car.update_odmoeter(23500)
my_use_car.read_odometer()

my_use_car.increment_odometer(100)
my_use_car.read_odometer()

2015 Honda Accord
 Your car has driven 23500km!
Your car has driven 23600km!
  • inherit

    When you write a class, you don't always start with whitespace. If you are writing a special version of another off the shelf class, you can use inheritance. When a class inherits another class, it will automatically obtain all the properties and methods of the other class; the original class is called the parent class, and the new class is called the child class. The child class inherits all the properties and methods of the parent class, and can also define its own properties and methods.

Subclass method__ init__ ()

Let's simulate an electric Car. Electric Car is a special kind of Car, so we can create a class of electric Car based on the Car class we created earlier, so we just need to write code for the special attributes and behaviors of electric Car

#To create an EV class
class ElectricCar(Car):
    '''Unique attributes of electric vehicles'''
    def __init__(self,make,model,year):
        '''Initialize properties of parent class'''
        super().__init__(make,model,year)

my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
2016 tesla model s

When creating a subclass, the parent class must be included in the current file and preceded by the subclass

Define properties and methods for classes

Next, add a special attribute (battery) of electric vehicle and a method to describe the attribute. We will store the battery capacity and write a method to print the battery Description:

#To create an EV class
class ElectricCar(Car):
    '''Unique attributes of electric vehicles'''
    def __init__(self,make,model,year):
        '''
        //Initialize properties of parent class
        //Initializing EV specific properties
        '''
        super().__init__(make,model,year)
        self.battery_size = 70
    def describe_battery(self):
        '''Print a message to describe the battery'''
        print("This battery car has"+ str(self.battery_size) + "Capacity battery")

my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
2016 tesla model s
 This battery car has a battery capacity of 70

Override method of parent class

As for the method of the parent class, it can be rewritten as long as it does not conform to the behavior of the child class simulating the real object. To do this, you can define a method in a subclass that has the same name as the parent method you want to override. In this way, Python will not consider the method of the parent class, but only the corresponding method defined in the child class:

Suppose there is a method named fill_gas_tank() in the Car class, which means nothing to the battery Car, so you want to override it. An overriding method is shown below.

class Car():
def fill_gas_tank(self):
    '''Increase exhaust emission value for automobile'''
    print("The vehicle's exhaust emissions are"+ str(self.gas_tank) +"Per kilometer")

~~~Python

class ElectricCar(Car):
def fill_gas_tank(self):
'' electric cars don't have fuel tanks' '
print("electric vehicles will not exhaust gas")

my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
my_tesla.fill_gas_tank()
print("\n")
my_car = Car('Honda ',' civic ', 2018)
my_car.fill_gas_tank()

~~~
2016 tesla model s
 This battery car has a battery capacity of 70
 Electric cars don't exhaust


The car's exhaust emissions are 13 per kilometer

Use instance as property

When using code to simulate a real object, you may find yourself adding more and more details to the class: the list of properties and methods, and the files are getting longer and longer. In this case, you may need to extract part of the class as a separate class. You can split large classes into small classes that work together.

For example, as we continue to add details to the ElectricCar class, we may find that it contains many attributes and methods that are specific to car batteries. In this case, we can extract these attributes and methods, put them into another class named Battery, and use a Battery instance as an attribute of the ElectricCar class:

class Car():
```Python
#To create a battery class
class Battery():
    '''A simple attempt to simulate electric vehicle battery'''
    def __init__(self,battery_size=70):
        '''Initialize battery properties'''
        self.battery_size = battery_size

    def describe_battery(self):
        '''Print a message describing the battery'''
        print("The battery capacity of this electric car is"+ str(self.battery_size))
        
#To create an EV class
class ElectricCar(Car):
    '''Unique attributes of electric vehicles'''
    def __init__(self,make,model,year):
        '''
        //Initialize properties of parent class
        //Initializing EV specific properties
        '''
        super().__init__(make,model,year)
        self.battery = Battery()    

my_test = ElectricCar('tesla','model s',2016)

print(my_test.get_descriptive_name())
my_test.attery.describe_battery()
```

~~~Python
2016 tesla model s
//The battery capacity of this electric car is 70

Next, add a method to Battery to report the vehicle's mileage according to the Battery capacity:

class Battery():
    '''A simple attempt to simulate electric vehicle battery'''
    def __init__(self,battery_size=70):
        '''Initialize battery properties'''
        self.battery_size = battery_size

    def describe_battery(self):
        '''Print a message describing the battery'''
        print("The battery capacity of this electric car is"+ str(self.battery_size))

    def get_range(self):
        '''Print out a message indicating the battery range'''
        if self.battery_size == 70:
            range = 240
        elif self.battery_size == 85:
            range = 270

        message = "Now the battery capacity can go"+str(range)+"KM distance"
        print(message)

#To create an EV class
class ElectricCar(Car):
    '''Unique attributes of electric vehicles'''
    def __init__(self,make,model,year):
        '''
        //Initialize properties of parent class
        //Initializing EV specific properties
        '''
        super().__init__(make,model,year)
        self.battery = Battery()
        
my_test = ElectricCar('tesla','model s',2016)

print(my_test.get_descriptive_name())
my_test.battery.describe_battery()
my_test.battery.get_range()
2016 tesla model s
 The battery capacity of this electric car is 70
 The current battery capacity can go 240KM
  • Import class

As you continue to add functionality to classes, files can become long, even if you use inheritance properly. To follow the general philosophy of python, keep the files as clean as possible. To help with this, python allows you to store classes in modules and then import the required modules in the main program.

Import a single class

#encoding:utf-8
from Car import Car

my_new_car = Car('east wind','Nissan',2022)
print(my_new_car.get_descriptive_name())

my_new_car.odometer_reading = 23
my_new_car.read_odometer()
2022 Dongfeng Nissan
 Your car has driven 23km!

Storing multiple classes in a module

Now you can create a new file called my_electric_car.py, import the electric car class, and create an electric vehicle:

#encoding:utf-8
from Car import ElectricCar

my_tesla = ElectricCar('tesla','model s',2016)

print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
2016 tesla model s
 The battery capacity of this electric car is 70
 The current battery capacity can go 240KM

Tags: Python Java encoding Ruby

Posted on Sat, 16 May 2020 23:07:20 -0700 by Harry57