[Python learning notes] Chapter 2 variables and simple data types in Python Programming: from introduction to practice

"Python Programming: from introduction to practice" is a book that I think is very suitable for Xiaobai's introduction. The first part explains the basic knowledge, and the last part is three projects using python.

This article is a note of my personal study. Most of the content comes from textbooks, and some are knowledge supplements after searching for relevant parts in the learning process. It is very suitable for Xiaobai reading like me.
This series will be continuously updated with my learning progress in the future. I hope this note can also help you~

The first chapter is about the configuration of python and the text editor Geany used in this course in different systems. If you have no knowledge, just read the original book.

  • 2.2 variables

    • 2.2.1 naming and use of variables
      • Including a-zA-Z1-9_ (alphanumeric and underlined) (but try to avoid capital letters)
      • Cannot start with a number
      • You cannot use python keywords or functions as variable names (such as print)
      • Short and descriptive:
        • student_name > name_of_student > s_n
      • Avoid using lowercase L and uppercase O (easily confused with 0 and 1)
  • 2.2 give it a try

    2-1 simple message: store a message in a variable and print it out

    # simple_message.py
    message = "hello world"
    print(message)
    
    '''
    Output:
    hello world
    '''
    

    2-2 multiple simple messages: store a message in a variable and print it out; Then change the value of the variable to a new message and print it out.

    # simple_messages.py
    message = "hello world"
    print(message)
    message = "hello python world"
    print(message)
    
    '''
    Output:
    hello world
    hello python world"
    '''
    
  • 2.3 String

    • Both double and single quotation marks can be used

    • At the same time, you can print quotation marks, such as:

      >>> print("hello 'my' world")
      hello 'my' world
      
      >>> print('"hello world"')
      "hello world"
      
    • 2.3.1 use the method to modify the case of the string

      • Capitalize the first letter: title() (only the first letter is capitalized, and if capitalized later, it will become lowercase, such as: Abcd → Abcd
      • All uppercase: upper()
      • All lowercase: lower()
      >>> name = "ada lovelace" 
      >>> print(name.title())
      Ada Lovelace
      >>> print(name.upper())
      ADA LOVELACE
      >>> print(name.lower())
      ada lovelace
      
    • 2.3.2 merge (splice) strings

      • Use + to splice strings (all must be strings. If it is in other formats, such as int, str(1) is required before splicing)
      first_name = "ada" 
      last_name = "lovelace" 
      full_name = first_name + " " + last_name # Splicing
      
      >>> print(full_name)
      ada lovelace
      
      >>> print("Hello, " + full_name.title() + "!")
      Hello, Ada Lovelace!
      
      >>> message = "Hello, " + full_name.title() + "!" 
      >>> print(message)
      Hello, Ada Lovelace!
      
    • 2.3.3 use tabs or line breaks to add white space

      • tab: \t
      • Wrap: \ n
      • (can also be used at the same time)
      >>> print("\tPython") 
      	Python
      
      >>> print("Languages:\nPython")
      Languages: 
      Python 
      
      >>> print("Languages:\n\tPython")
      Languages: 
      	Python 
      
    • 2.3.4 delete blank

      • lstrip() removes the left space
      • rstrip() removes the space on the right
      • strip() removes the spaces on both sides (removes all the left and right spaces, but cannot remove the space between words)
        • But this does not modify the variable itself, which means:
        • String is a string, string Rstrip () is also a string. If you don't make new_string = string.rstrip(), after calling string After rstrip(), print(string) still has spaces
        • Therefore, the modified string must be stored (it can also be saved back to the original variable name)
      >>> favorite_language = ' python '
      
      >>> favorite_language.rstrip()
      ' python' 
      
      >>> favorite_language.lstrip()
      'python ' 
      
      >>> favorite_language.strip() 
      'python'
      
    • 2.3.5 avoid syntax errors when using strings

      • If you want to use apostrophe ', avoid using single quotes when defining this string

      • 💡 You can also use the escape character \. For example, \ 'means' the character itself, not as a quotation mark

      • For example:

      string = "This is Tom's book"
      # or
      string = 'This is Tom\'s book'
      # instead of
      string = 'This is Tom's book'
      
    • 2.3.6 print statement in Python 2

      >>> python2.7 
      >>> print "Hello Python 2.7 world!" 
      Hello Python 2.7 world!
      
  • 2.3 give it a try

    2-3 personalized message: save the user's name into a variable and display a message to the user. The message displayed should be very simple, such as "Hello Eric, would you like to learn some Python today?".

    name = "Eric"
    message = "Hello " + name + ", would you like to learn some Python today?"
    print(message)
    
    '''
    Output:
    Hello Eric, would you like to learn some Python today?
    '''
    

    2-4 adjust the case of Name: store a person's name in a variable, and then display the person's name in lowercase, uppercase and initial uppercase

    • 💡 It is found that title() ensures that only the initial letter is capitalized, rather than turning the initial letter into uppercase
    name = "eRic"
    print("Title: " + name.title()) 
    print("Lower: " + name.lower())
    print("Upper: " + name.upper())
    
    '''
    Output:
    Title: Eric
    Lower: eric
    Upper: ERIC
    '''
    

    2-5 quotes: find a quote from a celebrity you admire and print out the name of the celebrity and his quotes. The output should look like this (including quotation marks):
    Albert Einstein once said, "A person who never made a mistake never tried anything new."

    print('Albert Einstein once said, "A person who never made a mistake never tried anything new."')
    
    '''
    Output:
    Albert Einstein once said, "A person who never made a mistake never tried anything new."
    '''
    

    2-6 quote 2: repeat exercise 2-5, but store the name of the celebrity in the variable famous_ In person, create the message to be displayed, store it in the variable message, and then print the message.

    famous_person = "Albert Einstein"
    message = famous_person + ' once said, "A person who never made a mistake never tried anything new."'
    print(message)
    
    '''
    Output:
    Albert Einstein once said, "A person who never made a mistake never tried anything new."
    '''
    

    2-7 eliminate whitespace in person's name: store a person's name and include some whitespace characters at the beginning and end. Be sure to use the character combinations "\ t" and "\ n" at least once.
    Print this person's name to show the blanks at the beginning and end. Then, the person names are processed by using the culling functions lstrip(), rstrip() and strip() respectively, and the results are printed out.

    name = "  \n Eric \t   "
    print("lstrip: " + "'" + name.lstrip() + "'")
    print("rstrip: " + "'" + name.rstrip() + "'")
    print("strip: " + "'" + name.strip() + "'")
    
    '''
    Output:
    lstrip: 'Eric      '
    rstrip: '
     Eric'
    strip: 'Eric'
    '''
    
  • 2.4 figures

    • 2.4.1 integer

      • Add:+

      • Minus:-

      • Multiply:*

      • Except:/

        • In python, 3 / 2 = 1.5
        • Compared with C language, 3 / 2 = 1
      • Modulus:% (remainder)

      • Power:**

      • Parentheses indicate the order of operations

      • 💡 Spaces do not affect the calculation, so whether to add spaces or not depends on your own habits

    • 2.1.2 floating point number

      • float() can convert integers or string s to floating-point numbers
      • int() converts a floating-point number or string to an integer (rounded to the nearest digit, without rounding)
      >>> float(1)
      1.0
      
      >>> float("1.5")
      1.5
      
      >>> float("1") # The same applies to integer string s
      1.0
      
      >>> int(1.8)
      1
      
      >>> int("1") # Integer string can be converted
      1
      
      >>> int("1.8") # If the decimal is string, the conversion will be wrong
      ValueError: invalid literal for int() with base 10: '1.8'
      
      >>> int(float("1.8")) # For the above situation, you can use float to cover it
      1
      
    • 2.4.3 using the function str() to avoid type errors

      • You need to use str() to change the number into a string before splicing
      age = 23 
      message = "Happy " + str(age) + "rd Birthday!" 
      print(message)
      
  • 2.4 give it a try

    **2-8 number 8: * * write four expressions that use addition, subtraction, multiplication and division respectively, but the result is the number 8. In order to use the print statement to display the results, be sure to enclose these expressions in parentheses, that is, you should write four lines of code similar to the following:

    print(5 + 3)

    The output should be 4 lines, each of which contains only the number 8.

    print(2 + 6)
    print(10 - 2)
    print(2 * 4)
    print(16 / 2)
    
    '''
    Output:
    8
    8
    8
    8.0
    '''
    

    **2-9 favorite number: * * store your favorite number in a variable, then use this variable to create a message, point out your favorite number, and then print this message.

    favourite_number = 3
    print("My favourite number is: " + str(3))
    
    '''
    Output:
    My favourite number is: 3
    '''
    
  • 2.5 notes

    • Single line note:#
    • Multiline comment: '' 'or' '(mark the beginning and end, but be sure to be consistent)
  • 2.6 Python Zen (guidelines for writing good Python code)

    >>> import this
    The Zen of Python, by Tim Peters
    
    Beautiful is better than ugly. # pretty
    Explicit is better than implicit.
    Simple is better than complex. # simple
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts. # Make code easy to read with comments
    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!
    

Keywords: Python

Added by Altec on Thu, 03 Feb 2022 20:43:27 +0200