Python Basics Exercises

Source: Internet
Author: User

1. Two ways to run Python scripts
Run the. py file to Python in Windows or Linux
Python's own interactive interpreter runs directly
2, briefly describe the relationship between bits and bytes
1 bits is the smallest representation unit in a computer
1 bytes is a small storage unit in a computer.
8 x bits = one byte
3. Brief description of the relationship between ASCII, Unicode, Utf-8, GBK
ASCII can represent a maximum of 255 symbols
GB2312 1980 of 6,763 Kanji
GBK1.0 1995 Windows default encoding Chinese 2 bytes
GB18030 pc must support
Backward compatible
Unicode Universal Code: Chinese 3 bytes English 1 bytes
Utf-8 Variable length Encoding
4. Please write "Li Jie" the number of digits that are encoded by Utf-8 and GBK respectively.
6 4 x
5, Pyhton single-line comments and multiline comments with what?
Single line: #
Multiple lines "" "" ""
6. What are the considerations for declaring variables?
denoted by a letter or underscore
Make sense
8. How do I see the address of a variable in memory?
ID (variable)
9. What is the purpose of the automatically generated. pyc file when executing a Python program?
When the Python program runs for the second time, the program will first look for the PYc file on the hard disk and, if found, load it directly into the

PYC file is actually a persistent way to save Pycodeobject
10
A. Implement user input user name and password, when the user name is seven and the password is 123, the display login is successful, otherwise the login failed!
Name = input (' Please input your name: ')
passwd = input (' Please input your passwd: ')
If name = = ' Seven ' and passwd = = ' 123 ':
Print (' Welcome seven ')
Else
Print (' name or passwd wrong ')

B. Implement user input user name and password, when the user name is seven and the password is 123, the display login is successful, otherwise the login failed, the failure to allow repeated input three times

Count = 0
For count in range (3):
Name = input (' Please input your name: ')
passwd = input (' Please input your passwd: ')
If name = = ' Seven ' and passwd = = ' 123 ':
Print (' Welcome seven ')
Break
Else
Print (' name or passwd wrong ')
Count + = 1
C. Implement user input user name and password, when the user name is seven or Alex and the password is 123, the display login is successful, otherwise the login failed, the failure to allow repeated input three times
Count = 0
For count in range (3):
Name = input (' Please input your name: ')
passwd = input (' Please input your passwd: ')
if passwd = = ' 123 ' and name = = ' Seven ' or name = = ' Alex ':
Print (' Welcome seven ')
Break
Else
Print (' name or passwd wrong ')
Count + = 1
11.
A. Using a while loop to implement output 2-3 + 4-5 + 6 ... + 100 and
j = 0
K = 0
i = 2
While I < 101:
If i%2 = = 0:
j = j + I
else:
K = k + I
i + = 1
Print (J-K)


B. Using a For loop and a range for output 1-2 + 3-4 + 5-6 ... + 99 and
j = 0
K = 0
For I in range (100):
If i%2 = = 0:
j = j + I
Else
K = k + I
Print (K-J)
C. Using a while loop to implement output 1, 2, 3, 4, 5, 7, 8, 9, 11, 12
i = 0
While I < 12:
i + = 1
if i = = 6 or i = = 10:
Continue

Print (i)
D. Using a while loop to implement all odd numbers in output 1-100
i = 0
While I <= 99:
i + = 1
If i%2! = 0:
Print (i)

E. Using a while loop to implement all the even numbers in output 1-100
i = 0
While I <= 99:
i + = 1
If i%2 = = 0:
Print (i)
12. Binary representation of numbers 5, 10, 32, 7 respectively
5:00000101
10:00001010
32:00100000
7:00000111
14, the existing following two variables, please briefly describe what the relationship between N1 and N2?
N1 = 123
N2 = 123
Two points to the same memory address ID (n1) = ID (n2)
15, the existing following two variables, please briefly describe what the relationship between N1 and N2?
N1 = 123456
N2 = 123456
Two points to 2 different address IDs (N1)! = ID (n2) memory only caches variables between 0-255, which will be stored on the hard disk
16, the existing following two variables, please briefly describe what the relationship between N1 and N2?
N1 = 123456
N2 = N1
N1 points to 123456 memory address, N2 points to N1 memory address common one ID address N1 change will re-open an ID address

18, what are the Boolean values respectively? False and Ture


20, write code, there are the following variables, please follow the requirements to achieve each function
Name = "AleX"
A. Remove the space on both sides of the value corresponding to the name variable and enter the content to be removed
name = ' AleX '
Print (Name.strip ())
# B. Determine if the value corresponding to the name variable starts with "Al" and outputs the result
Name.startswith (' al ')
# c. Determines whether the value corresponding to the name variable ends with "X" and outputs the result
Name.endswith (' X ')
# d. Replace "L" in the value corresponding to the name variable with "P", and output the result
Print (Name.replace (' l ', ' P '))
# E. The value corresponding to the name variable is split according to "L" and the result is output.
Print (Name.split (' l '))
# f. Excuse me, what type is the value of the previous question E split?
# list
# G. Capitalize the value corresponding to the name variable and output the result
Print (Name.upper ())
# H. lowercase the value corresponding to the name variable and output the result
Print (Name.lower ())
I. Please output the 2nd character of the value corresponding to the name variable?
Print (name[1])
# J. Please output the first 3 characters of the value corresponding to the name variable?
Print (Name[0:3])
# k. Please output the first 2 characters of the value corresponding to the name variable?
Print (name[-2:])
L. Please output the value of the name variable corresponding to the index where "E" is located?
Print (Name.index (' e '))

22, write code, such as the following table, as required to achieve each function
# li = [' Alex ', ' Eric ', ' Rain ']
# A. Calculates the list length and outputs
Li = [' Alex ', ' Eric ', ' Rain ']
Print (Len (LI))
# B. Append the element "seven" to the list and output the added list
Li.append (' seven ')
Print (LI)
# c. Please insert the element "Tony" in the 1th position of the list and output the added list
Li.insert (0, ' Tony ')
Print (LI)
# d. Please modify the element in the 2nd position of the list to "Kelly" and output the modified list
Li[li.index (' alex ')] = ' Kelly '
Print (LI)
# E. Please remove the element "Eric" from the list and output the modified list
Li.remove (' Eric ')
Print (LI)
# f. Delete the 2nd element in the list and output the value of the deleted element and the list after the element is deleted
Print (Li.pop (1))
Print (LI)
# G. Delete the 3rd element in the list and output the list after the element is deleted
Del Li[2]
Print (LI)
# H. Delete the 2nd to 4th element in the list and output the list after the element is deleted
Del Li[1:3]
Print (LI)
I. Invert all the elements in the list and output the inverted list
Print (Li.reverse ())
J. Use the index of the for, Len, range output list
For I in range (Len (LI)):
Print (i)
# k. Use Enumrate to output list elements and ordinal numbers (starting from 100)
For I, number in enumerate (li,100):
Print (I,number)
L. Use the For loop to output all the elements of the list
For I in Li:
Print (i)

23, write code, such as the following table, please follow the functional requirements to achieve each function
Li = ["Hello", ' Seven ', ["Mon", ["H", "Kelly"], ' all '], 123, 446]
A. Please output "Kelly"
Li = [' Hello ', ' seven ', [' Mom ', [' H ', ' Kelly '], ' all '],123, 446]
Print (li[2][1][1])
# B. Please use the index to find the ' all ' element and modify it to "all"
Li[li[2].index (' all ') [] = ' all '
Print (LI)
24, write code, have the following tuple, according to the requirements of each function
Tu = (' Alex ', ' Eric ', ' Rain ')
A. Calculating the tuple length and outputting
Tu = (' Alex ', ' Eric ', ' Rain ')
Print (Len (TU))
# B. Gets the 2nd element of a tuple and outputs
Print (tu[1])
# c. Gets the 第1-2个 element of the tuple and outputs
Print (Tu[0:2])
# d. Please use the for output tuple element
For I in Tu:
Print (i)
# E. Use the index of the for, Len, and range output tuples
For I in range (len):
Print (i)
# f. Use the Enumrate output primitive element and ordinal (ordinal starting from 10)
For I,number in Enumerate (tu,10):
Print (I,number)
25, there are the following variables, please implement the required functions
Tu = ("Alex", [One, one, a, {"K1": ' V1 ', "K2": ["Age", "name"], "K3": (11,22,33)}, 44])
A. Describing the characteristics of Ganso
Cannot be modified
B. Can you tell me if the first element in the TU variable, "Alex", could be modified?
Not
C. What is the value of "K2" in the TU variable? Is it possible to be modified? If you can, add an element, "Seven", to the
#列表 can

tu[1][2][' K2 '].append (' seven ')
Print (TU)
D. What is the value of "K3" in the TU variable? Is it possible to be modified? If you can, add an element, "Seven", to the
Tuples cannot be
26. Dictionaries
DiC = {' K1 ': "v1", "K2": "V2", "K3": [11,22,33]}
A. Please loop out all the keys
DiC = {' K1 ': ' v1 ', ' K2 ': ' v2 ', ' K3 ': [11,22,33]}
For key in DIC:
Print (key)
# B. Please loop out all the VALUEC. Please loop out all the keys and value
For key in DIC:
Print (Key,dic[key])
# d. Please add a key-value pair in the dictionary, "K4": "V4", and output the added dictionary
dic[' K4 '] = ' v4 '
Print (DIC)
# E. In the modified dictionary, the value of "K1" corresponds to "Alex", Output the modified dictionary
dic[' K1 ' = ' Alex '
Print (DIC)
# f. Please append an element 44 to the value of the K3 to output the modified dictionary
dic[' K3 '].append (44)
Print (DIC)
# G. Please insert element 18 in the 1th position of the K3 corresponding value, output the modified dictionary
Dic2 = {' K3 ': [18,11,22,33,44]}
Dic.update (DIC2)
Print (DIC)
27. Conversion
A. Converting a string s = "Alex" to a list
s = ' Alex '
List (s)
# B. Convert string s = "Alex" to Cheng Yuanju
s = ' Alex '
Tuple (s)
# B. Convert list li = ["Alex", "seven"] to Narimoto Group
Li = [' Alex ', ' seven ']
List (LI)
# c. Convert meta-progenitor tu = (' Alex ', ' seven ') to a list
Tu = (' Alex ', ' seven ')
List (TU)
D. Convert the list li = ["Alex", "seven"] to a dictionary and the dictionary key is incremented by 10


27, transcoding n = "Old boy"
A. Convert the string to UTF-8 encoded byte and output, then convert the byte to Utf-8 encoded string, and then output
n = ' old boy '
Print (N.encode (' Utf-8 '))
m = N.encode (' Utf-8 ')
Print (M.decode (' Utf-8 '))
A. Convert the string to GBK encoded byte and output, then convert the byte to GBK encoded string, and then output
n = ' old boy '
Print (N.encode (' GBK '))
m = N.encode (' GBK ')
Print (M.decode (' GBK '))
28. For all numbers within 1-100
j = 0
For I in range (100):
j = j + I
Print (j)

29. Element classification
Has the following value set {11,22,33,44,55,66,77,88,99,90}, saving all values greater than 66 to the first key in the dictionary,
Saves a value less than 66 to the value of the second key.
Dict = {' K1 ': [], ' K2 ': []}
Set = {11,22,33,44,55,66,77,88,99,90}
For I in set:
If I > 66:
dict[' K1 '].append (i)
Else
dict[' K2 '].append (i)
Print (DICT)

That is: {' K1 ': All values greater than 66, ' K2 ': All values less than 66}
30. Shopping Cart
Functional Requirements:
Require users to enter total assets, for example: 2000
Display the list of items, let the user select the item according to the serial number, add the shopping cart
Purchase, if the total amount of goods is greater than the total assets, indicating that the account balance is insufficient, otherwise, the purchase succeeds.
goods = [
{"Name": "Computer", "Price": 1999},
{"Name": "Mouse", "Price": 10},
{"Name": "Yacht", "Price": 20},
{"Name": "Beauty", "Price": 998},
]
Shopping_cart = []
index = 0
salary = Int (input (' Please input your salary: '))

While True:
For I in Goods:
Print (index, i)
Index + = 1
Choice = input (' Please input the number of goods: ')
If Choice.isdigit ():
Choice = Int (choice)
If choice < Len (goods) and Choice > 0:
Product = Goods[choice]
If product[' price '] < salary:
Shopping_cart.append (product[' name ')
Salary-= product[' price ']
Print (product[' name ']+ ' into your shopping cart ')
Else
Print (' You don't have enough money! ')
elif Choice = = ' Q ' or choice = = ' Q ':
Break
Else
Print (' What kind of ghost are you typing? Re-lose 1 ')
Print (' Shopping_cart list as follow: ')
For I in Shopping_cart:
Print (i)
Print (' Your current salary is: ', str (salary))


19. Read the code and write out the results
# a = "Alex"
# b = a.capitalize ()
# Print (a)
# print (b)
Please write out the results
' Alex '
' Alex '
22, please use the code to achieve: the use of an underscore each element of the list is stitched into a string, Li = [' Alex ', ' Eric ', ' rain ']
Print (' _ '. Join ([' Alex ', ' Eric ', ' Rain '])

17, if there is a variable n1 = 5, use the provided method of int, how many bits can be used to get the variable at least?
N1 = 5
Print (Int.bit_length (N1)) # 3 x


Python Basics Exercises

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.