Python exercises (Basic knowledge Exercises (ii))

Source: Internet
Author: User
Tags chr python script

1. Two ways to execute a python script
(1). Interactive mode: Start the Python interpreter and execute the command (2). Scripting: Python xxx.py or chmod +x &&./xxx.py
2. Briefly describe the relationship between bits and bytes
A bits is the smallest representation unit in a computer. One byte is the smallest storage unit in the computer. Bits =8bits=1byte=1 bytes
3. Brief description of the relationship between ASCII, Unicode, uft-8, GBK
The United States has developed a set of character encoding, the relationship between English characters and bits, which is known as ASCII code, consisting of 1 bytes, up to a maximum of 2**8=256 characters Unicode is an international organization to accommodate all the world's words and symbols of the character encoding scheme, Consists of 2 bytes, up to support 2**16=65536 characters UTF-8 The biggest feature is that it is a variable length encoding, consisting of 1-6 bytes, the commonly used English letters are encoded into 1 bytes, Chinese characters are usually 3 bytes, only very uncommon characters will be encoded into 4-6 bytes. GBK is the Chinese National standard extension code, because GBK also covers Unicode all CJK Kanji, so it can also be done with Unicode one by one correspondence. Windows default encoding GBK, Chinese accounts for 2 bytes.
4. Please write out the number of digits of "Li Jie" that are encoded with utf-8 and GBK respectively.
In UTF-8, an English account is 1 bytes, and one Chinese is 3 bytes, where "Li Jie" occupies 6 bytes. GBK a Chinese account of 2 bytes, where "Li Jie" is 4 characters.
What are 5.Python single-line comments and multiline comments used separately?
Single-line comment: #要注释内容多行注释: "" To comment the content "" "or" "to comment on the content"
6. What are the considerations for declaring variables?
Variables made up of numbers, letters, underscores cannot start with a number variable cannot be case-sensitive using keyword variables
7. If there is a variable n1 = 5, use the method provided by int to get the minimum number of bits that the variable can be represented?
#!/usr/bin/env python#-*-Encoding:utf-8-*-n1 = 5v = Int.bit_length (n1) print (v)
8. What are the Boolean values?
True false "" and "= False #空字符串" Content "= True0  = False Other numbers = True
9. Read the code and write out the results
" Alex "  = a.capitalize ()print(a)print(b)
View Code

Execution Result:

Alexalex
10. Write the code, with the following variables, please implement each function as required

Name= "AleX"

A. Remove the space on both sides of the value corresponding to the name variable and enter the content after removal

Print (Name.strip ())

B. Determine if the value corresponding to the name variable starts with "Al" and outputs the result

Print (Name.startswith (' al '), name)

C. Determine if the value corresponding to the name variable ends with "X" and outputs the result

Print (Name.endswith (' X '), name)

D. Replace "L" in the value corresponding to the name variable with "P", and output the result

Print (Name.replace (' l ', ' P '))

E. Split the "L" in the value corresponding to the name variable and output the result.

Print (Name.split (' l '))

F. What type (optional) can I get after I split the previous question?

#列表

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[:3])

K. Please output the first 2 characters of the value corresponding to the name variable?

Print (name[-2:]) #-1 for the last character, 2 for the penultimate character

L. Please output the index where "E" is located in the value corresponding to the name variable.

Print (Name.index (' e '))

M. Gets a subsequence that does not contain the last character. such as: Oldboy get oldbo;root then get Roo

Print (Name.rstrip (name[-1:]))
11. Can strings be iterated? Can I use a for loop for each element?
#可迭代对象 = = can be used for loop get name = "AleX" For I in Name:print (i)
12. Please use the code to implement:

A. Using underscores to stitch each element of a list into a string, Li = "Alexericrain"

Li = "alexericrain" Print (' _ '. Join (LI))

B. Use an underscore to stitch each element of the list into a string, Li = [' Alex ', ' Eric ', ' Rain ']

Li = [' Alex ', ' Eric ', ' Rain ']print (' _ '. Join (LI))
What is the difference between range in 13.python2 and range in Python3?
The range in Python2 returns a list that is directly created in content Python3 returns an iteration value that is only created when the For loop
14. Implement an integer addition calculator:

Such as:
Content = input (' Please enter content: ') #如: 5+9

#方法一: Content = input (' Please input: ') print (eval (content)) #方法二: content = input (' Please enter content: ')  #5 +9n1,n2 = content.split (' + ') n1 = Int (n1) n2 = Int (n2) print (N1+N2)
15. How many decimal numbers are included in the calculation of user input? A few letters?

Such as:
Content=input (' Please enter content: ') #如: asduiaf878123jkjsfd-213928

Content = input (' Please enter content: ') n = 0;s = 0for i in range (len (content)): # print (Content[i]) if Content[i].isdecimal (): n + = 1if con Tent[i].isalpha (): S + = 1print (' Number of decimal numbers: ', N, ' number of letters: ', s)
16. Briefly describe the relationship between int and 9 and strings such as STR and "Xxoo"?
Int,str is Class 0 and "Xxoo" are objects created from the corresponding class
17. Make Fun Template program

Requirements: Wait for the user to enter a name, place, hobby, more user's name and hobbies to display any:
such as: Dear and amiable xxx, favorite in XXX place dry xxx

#方法一: Name = input (' Please enter name: ') where = input (' Please enter location: ') Love = input (' Please enter hobby: ') print ("Dear and amiable%s, most like the%s local dry%s"% (name,where,love ) #方法二: name = input (' Enter name: ') where = input (' Please enter location: ') Love = input (' Please enter hobby: ') template = "Dear amiable {0}, most like {1} place {2}" print ( Template.format (Name,where,love))
18. Make random verification code, case-insensitive.

Process:
-User executor
-Show user the verification code that needs to be entered
-user entered value
display the correct information at the same time as the value entered by the user; otherwise continue to generate random verification code continue waiting for user input
Generate random code case:

 def   Check_code ():  import   Randomcheckcode  =  for  i in  range (4 = Random.randrange (0,4 if  current!= i:temp  = Chr (Random.randint ( 65,90 else  :temp  = Random.randint (0,9) Checkcode  +=< Span style= "COLOR: #000000" > str (temp)  return   Checkcodecode  = Check_code ()  print  (code) 
View Code
#!/usr/bin/env python#-*-Encoding:utf8-*-def check_code ():    import random    Checkcode = ' for    i in range (4): Current        = Random.randrange (0, 4) if current! =        I:            temp = Chr (random.randint (+))        else:            temp = RA Ndom.randint (0, 9)        Checkcode + = str (temp)    return checkcodewhile True:  code = check_code ()  print ( Code)  app = input ("Enter Verification Code:")  if code.upper () = = App.upper ():    print ("input correct")    break  Else:    Print ("Input error")    s = input ("Do you want to re-enter?") ")    if s = =" No ": Break    Else:        continue
19. Develop the sensitive Word filter program, prompting the user to enter content, if the user input contains special characters: such as "Teacher Cang" "Tokyo Hot", then replace the content with * * *
v = input (">>>") v = v.replace ("Cang teacher", "* * *") v = v.replace ("Tokyo Hot", "* *") print (v)
20. Making Forms

Loop Prompt user input: User name, password, mailbox (requires the user to enter a length of not more than 20 characters, if more than the first 20 characters are valid)

If the user enters Q or Q for no further input, the content entered by the user is displayed in a tabular format.

#!/usr/bin/env python#-*-Encoding:utf8-*-s = "" While True:    name = input ("User name:")    if name = = "Q" or name = = "Q":        break    If Len (name) >=:        name = name[:20]    passwd = input ("Password:")    If Len (passwd) >=:        passwd = passwd[:20]    email = input ("email:")    if Len (email) >=:        email = email[:20]    template = "{0}\t{ 1}\t{2}\n "    v = Template.format (name, passwd, email)    s + = Vprint (S.expandtabs (20))

Python exercises (Basic knowledge Exercises (ii))

Related Article

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.