Python basic question type 1: python basic question type

Source: Internet
Author: User

Python basic question type 1: python basic question type

I. Two ways to execute Python scripts

Ii. Brief the relationship between bit and byte

1 Byte = 8bit

Iii. Relationship between ascii, unicode, UTF-8, and gbk

Ascii is the first English encoding method in the United States.

Gbk is an extension of ascii Chinese characters. As long as the first character is greater than 127, it indicates the start of the Chinese character, no matter whether it is followed by the content in the extended character set, the extended encoding scheme is called the gbk standard.

Unicode is ISO to unify the encoding of all cultures, letters, and symbols on the earth. A Chinese Character occupies 2 bytes.

Utf-8 is the most widely used Unicode implementation method on the Internet, the encoding designed for transmission, and make the encoding without borders, so that it can show all the characters in the world, UTF-8 is a Chinese character that occupies 3 bytes.

4. Write "Li Jie", the digits occupied by UTF-8 and gbk encoding respectively.

UTF-8: 2 Chinese characters = 6 bytes = 48bit

Gbk: 2 Chinese characters = 4 bytes = 32bit

5. What are Python single-line and multi-line annotations used?

Single line comment :#

Multi-line comment: ""

6. What are precautions for declaring variables?

7. How can I view the address of a variable in the memory?

Name = 'Alex'

Id (name)

8. What is the role of the. pyc file automatically generated when a Python program is executed?

Pyc file is a persistent storage method of PyCodeObject. It is a variant bytecode file generated before execution in Python.

9. write code

  • The user can enter the user name and password. If the user name is seven and the password is 123, the logon is successful. Otherwise, the logon fails, and three times can be entered if the logon fails.
  • The user enters the user name and password. If the user name is seven or alex and the password is 123, the logon is successful. Otherwise, if the user name fails, the user can enter the password three times.
  •           

    Error_num = 0

    While True:

    Username = input ("Enter the User name :")

    Password = input ("enter the password :")

    If username = 'hangzhou' or username = 'wang ':
    If password = 'Password ':
    Print ('login successful! ')
    Break
    Else:
    Print ("incorrect user name or password! ")
    Error_num + = 1
    If error_num = 3:
    Exit ()
    Else:
    Continue
    10. write code
    1. Use the while loop to implement the sum of 2-3 + 4-5 + 6... + 100
    Sum = 0
    For I in range (2,101 ):
    If I % 2 = 0:
    Sum + = I
    Else:
    Sum-= I
    Print (I, sum)
    Print ("sum:", sum)
    2. Use the for loop and range to output the sum of 1-2 + 3-4 + 5-6... + 99.
          sum = 0
          for i in range(1,100):
          if(i%2==0):
         sum -= i
          else:
         sum += i
          print(i,sum)
          print("sum:",sum)
    3. Use a while loop to output 1, 2, 3, 4, 5, 7, 8, 9, 11, 12
          n=0
          while(n < 12):
          n+=1
          if(n == 6 or n == 10):
        print(end=" ,")
          continue
           else:
          print(n,end=",")
    4. Use the while loop to output all odd numbers in 1-
           n = 0
           s = 0
           while(s < 99):
           s = 2*n+1
           n+=1
           print(s,end=" ")
           for i in range(1,100,2):
          print(i,end=" ")
           print("\n")
    5. Use the while loop to output all the even numbers within 1-
          m = 1
          h = 0
          while(h < 100):
          h = 2*m
          m+=1
          print(h,end=" ")
    11. Write the binary representation of numbers 5, 10, 32, and 7 respectively.
    A = [5, 10, 32, 7]
    For I in:
    Print (I, "(decimal):", bin (I ))
    Print (I, "(octal):", oct (I ))
    Print (I, "(hexadecimal):", hex (I ))
    12. Briefly describe the relationship between objects and classes (metaphorical approaches are available)
    Instantiation of object is an example
    13. The following two variables are available. Briefly describe the relationship between n1 and n2. n1 = 123, n2 = 123?
    The memory address is the same and the same memory address is referenced.
    14. The following two variables are available. Briefly describe the relationship between n1 and n2. n1 = 123, n2 = 123?
    The memory address is the same and the same memory address is referenced.

    15. If the following Variable n1 = 5 is available, use the method provided by int to obtain how many binary bits can be used for the variable at least? N1 = 5
    V = int (n1.bit _ length ())
    Print (v)
    Print (bin (n ))

    What are the 16 and boolean values?
    True or false
    True and False
    0, 1
    17. Read the code and write the execution result.
    A = "alex"
    B = a. capitalize ()
    Print ()
    Print (B)
    Please write the output result: alex
    Alex
    18. write code with the following variables. implement each function as required.
    Name = "alex"
    1. Remove the spaces on both sides of the value corresponding to the name variable, and enter the removed content.
    2. Determine whether the value corresponding to the name variable starts with "al" and output the result.
    3. Determine whether the value corresponding to the name variable ends with "X" and output the result.
    4. Replace "l" with "p" in the value corresponding to the variable and output the result.
    5. Split the value corresponding to the name variable according to "l" and output the result.
    6. What type of value is obtained after dividing e in the previous question?
    7. Change the value of the name variable to uppercase and output the result.
    8. Write down the value corresponding to the name variable and output the result.
    9. Output 2nd characters of the value corresponding to the name variable
    10. output the name variable with the first three characters
    11. output the last two characters of the value corresponding to the name variable.
    12. output the index location of "e" in the value corresponding to the name variable.
    Answer:
    Name = "aleX"
    Print ("name =", name)
    Print ("name =", name. strip () # Remove Spaces
    Print ("name =", name. startswith ("al") # whether to start with al
    Print ("name =", name. endswith ("X") # Whether to end with X
    Print ("name =", name. replace ("l", "p") # replace l with p
    Print (name. split ('l') # split by l
    Print (type (name. split ('l') # value types after l Segmentation
    Print ("name =", name. upper () # convert uppercase letters
    Print ("name =", name. lower () # convert lowercase letters
    Print (name [1]) # The second character corresponding to the output variable value
    Print (name [: 2]) # output the first three characters
    Print (name [-2:]) # output the last two characters
    Print (name. index ("e "))
    19. Can strings be iterated? If possible, use for to loop every element.
    For I in name: # string iteration, use for to loop every element
    Print (I, end = "")
    20. Use the code: concatenate each element of the list into a string using an underscore, li = ['Alex ', 'Eric', 'rain']
    Li = ['Alex ', 'Eric', 'rain'] # concatenate each element of the list into a string using an underscore.
    Print ("_". join (li ))
    21. Write the Code as follows:
    Li = ['Alex ', 'Eric', 'rain']
    1. Calculate the list length output
    2. append the element "seven" to the list and output the added list.
    3. Insert the "Tony" element in the second position of the list and output the added list.
    4. Modify the element of the 2nd position in the list to "Kelly" and output the Modified list.
    5. Delete the "eric" element in the list and output the Modified list.
    6. Delete the 2nd elements in the list and output the values of the deleted elements and the list of deleted elements.
    7. Delete the 2nd elements in the list and output the list after the elements are deleted.
    8. Delete the 2nd to 4th elements in the list and output the list of deleted elements.
    9. Please reverse all the elements in the list and output the reversed list
    10. Use the indexes of the for, len, and range output lists.
    11. Use enumrate to output the list elements and serial numbers (starting from 100)
    12. Use all elements in the for loop output list
    Answer:
    Li = ['Alex ', 'Eric', 'rain']
    Print ("1:", len (li) # Calculate the length of the li Array
    Li. append ("seven") # append Element
    Print ("2:", li)
    Li. insert (0, "Tony") # Add the Tony element at the first position of the array
    Print ("3:", li)
    Li [1] = "Kelly" # change the element in the second position of the array to Kelly
    Print ("4:", li)
    Li. remove ("eric") # Delete the element eric
    Print ("5:", li)
    Print ("6:", li [1]) # Delete the second element in the list
    Del li [1]
    Print ("7:", li)
    Del li [2] # Delete the third element
    Print ("8:", li)
    Li. append ("seven ")
    Li. append ("alex ")
    Li. append ("Kelly ")
    Li. append ("hello ")
    Print (li)
    Del li [] # Delete elements 2nd to the fourth
    Print ("9:", li)
    Li. reverse () # reverse all elements in the list
    Print ("11:", li)
    Print ("\ n ")
    For I in range (len (li): # Use for, len, range to output the index of the List
    Print (I, end = "")
    Print ("\ n ")
    For k, v in enumerate (li, 100): # Use enumerate to output the list element and serial number
    Print (k, ".", v)
    For I in li: # for loop output element list
    Print (I, end = "")
    22. implement each function as required
    Li = ["hello", 'seven', ["mon", ["h", "kelly"], 'all'], 123,446]
    1. Output "Kelly"
    2. Use the index to locate the 'all' element and change it to "all"
    Answer:
    Li = ["hello", 'seven', ["mon", ["h", "kelly"], 'all'], 123,446]
    Print (li)
    S = li [2] [1] [1] # output "Kelly"
    Print (s. capitalize ())
    Index = li [2]. index ("all") # Use the index to locate all and change all to ALL
    Li [2] [index] = "ALL"
    Print (li)

    23. write code with the following tuples to implement each function as required
    Tu = {'Alex ', 'Eric', 'rain '}
    1. Calculate and output the length of the tuples.
    2. Obtain the 2nd elements of the tuples and Output
    3. Obtain the 1-2 elements of the tuples and Output
    4. Use for to output the elements of the tuples.
    5. Use for, len, and range to output the index of the tuples.
    6. Use enumrate to output the element and serial number of the tuples (the serial number starts from 10)
    Answer:
    Tu = ['Alex ', 'Eric', 'rain']
    Print (len (tu) # Calculate and output the array Length
    Print (tu [1]) # obtain the second element of the tuples
    Print (tu [0: 2]) # obtain the 1-2 elements of a tuples
    For I in tu: # for elements of the output tuples
    Print (I, end = "")
    Print ("\ n ")
    For I in range (len (tu )):
    Print (I, end = "")
    Print ("\ n ")
    For k, v in enumerate (tu, 10 ):
    Print (k, ":", v)
    24. Implement required functions
    Tu = ("alex", [11,22, {"k1": 'v1 ', "k2": ["age", "name"], "k3" :( 11,22, 33)}, 44])
    1. Describe the features of tuples
    2. Can the first element "alex" in the tu variable be modified?
    3. What type is the value of k2 in the tu variable? Can it be modified? If yes, add an element "Seven" to it"
    4. What type is the value corresponding to "k3" in the tu variable? Can it be modified? If yes, add an element "seven" to it"
    Answer:
    1. All features of the list. The difference is that elements cannot be modified.
    2. list, no
    3. tu = ('Alex ', [11, 22, {'k2': ['age', 'name'], 'k1': 'v1 ', 'k3 ': (11, 22, 33)}, 44])
    Tu [1] [2] ["k2"]. append ("Seven ")
    Print (tu)
       
    4. tuple, which cannot be modified
    25. Dictionary
    Dic = {'k1 ': "v1", "k2": "v2", "k3": [11, 22, 33]}
    1. Please output all keys cyclically
    2. Please output all values cyclically
    3. Please output all keys and values cyclically
    4. Add a key-value pair to the dictionary, "k4": "v4", and output the added dictionary.
    5. In the dictionary modification, set "k1" to "alex" and output the modified dictionary.
    6. append an element 44 to the value corresponding to k3 and output the modified dictionary.
    7. insert element 18 at the first position of the value corresponding to k3 and output the modified dictionary.
    Answer:
       Dic = {'k1 ': "v1", "k2": "v2", "k3": [11, 22, 33]}
        for i in dic.keys():
         print(i,end=" ")
        print("\n")
        for j in dic.values():
        print(j,end=" ")
        print("\n")
        for k in dic.items():
        print(k,end=" ")
        print("\n")
        dic["k4"] = "v4"
        print(dic)
        dic["k1"] = "alex"
        print(dic)
        dic["k3"].append(44)
        print(dic)
        dic["k3"].insert(0,18)
        print(dic)
    26. Conversion
    1. Convert string s = "alex" to list
    2. Convert string s = "alex" into a metagroup
    3. Convert the list li = ["alex", "seven"] into a metagroup
    4. Convert the tuple tu = ('Alex ', "seven") to a list.
    5. Convert the list li = ["alex", "seven"] into a dictionary and the dictionary key increments backward from 10.
    Answer:
        S = "alex"
    Print (list (s ))
    Print (tuple (s ))
    Li = ["alex", "seven"]
    Print (tuple (li ))
    Tu = ("alex", "seven ")
    Print (list (li ))
    Print ("\ n ")
    Li_dic = {}
    For k, v in enumerate (li, 10 ):
    Li_dic [k] = v
    Print (li_dic)
    S = "Old Boy"
    Print (s. encode ("UTF-8 "))
    Print (s. encode (). decode ("UTF-8 "))
    Print (s. encode ("gbk "))
    Print (s. encode ("gbk"). decode ("gbk "))
    Calculate the sum of all numbers in 1-
    Sum = 0
    For I in range (1,101 ):
    Sum + = I
    Print (I, sum)
    Print ("sum =", sum)
    29. Element Classification
    There is a set of [, 44,], which saves all values greater than 66 to the first key of the dictionary, save the value smaller than 66 to the value of the second key.
    That is, {'k1 ': All values greater than 66, 'k2': All requirements smaller than 66}
        A = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
         b = []
        c = []
        for i in a:
        if i <= 66:
        b.append(i)
        else:
       c.append(i)
        d = {"k1":b, "k2":c }
        print(d)
    Thirty functional requirements:
    Require the user to enter total assets, such as 2000
    Displays the product list. You can select a product by serial number and add it to the shopping cart.
    If the total amount of the purchased item is greater than the total assets, the system prompts that the account balance is insufficient. Otherwise, the purchase is successful.
    Goods = [
    {"Name": "computer", "price": "1999 "},
    {"Name": "Mouse", "price": "10 "},
    {"Name": "yacht", "price": "20 "},
    {"Name": "beauty", "price": "998 "}
    ]
    Answer:
        
    Zong_zi_chan = 0
    Zong_zi_chan1 = input ("Please input total assets :")
    If zong_zi_chan1.isdigit ():
    Pass
    Else:
    Exit ("your input is not a digital asset ")
    Zong_zi_chan = int (zong_zi_chan1)
    Print ("your total assets are:", zong_zi_chan, "RMB ")
    Print ("\ n ")
    Print ("purchased items include :")
    Shang_pin = [
    {"Name": "computer", "price": "1999 "},
    {"Name": "Mouse", "price": "10 "},
    {"Name": "yacht", "price": "20 "},
    {"Name": "beauty", "price": "998 "},
    ]
    Shang_pin2 = []
    For I in shang_pin:
    Print (I ["name"], I ["price"], "Yuan ")
    Print ("\ n ")
    Ming = ""
    While True:
    Ming_cheng = input ("Enter y settlement/enter the name of the product to be purchased to select the product :")
    If ming_cheng = "y ":
    Break
    Else:
    For I in shang_pin:
    If I ["name"] = ming_cheng:
    Ming = I ["name"]
    Else:
    Pass
    If ming = ming_cheng:
    Pass
    Else:
    Exit ("the product name you entered does not exist ")
    For I in shang_pin:
    If I ["name"] = ming_cheng:
    Shang_pin2.append (I)
    Print ("You can select:", shang_pin2)
    Zongjia = 0
    For I in shang_pin2:
    Danjia = I ["price"]
    Zongjia + = danjia
    Print ("total settlement now:", zongjia, "Yuan ")
    If zong_zi_chan> = zongjia:
    Print ("Congratulations, you have purchased ")
    Else:
    Print ("your balance is insufficient, please recharge ")
     
     

     
     
     
     
     
     

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.