Concise python3 tutorial 14. Input and Output

Source: Internet
Author: User
Tags reverse text

Introduction

In some cases, you have to allow the program to interact with the user. For example, you need to obtain the input from the user and then output the calculation result. We can useInput ()AndPrint ()Function.

For the output, we can also useStr(String. For exampleMust USTMethod to obtain a right-aligned string with the specified width. For details, seeHelp (STR).

Another common input/output type is file processing. For many programs that have the ability to create and read and write files, we will explore these contents in this section.

 

Get user input

#! /Usr/bin/Python

# User_input.py

Def reverse (text ):

Return text [:-1]

Def is_palindrome (text ):

Return text = reverse (text)

Something = input ('enter text :')

If (is_palindrome (something )):

Print ("Yes, it is a palindrome ")

Else:

Print ("no, it is not a palindrome ")

Output:

$ Python user_input.py

Enter Text: sir

No, it is not a palindrome

$ Python user_input.py

Enter Text: Madam

Yes, it is a palindrome

$ Python user_input.py

Enter Text: racecar

Yes, it is a palindrome

Example:

In this example, we use the slice operation to reverse the text. We have learned how to passSEQ [A: B](Starting from A to B) slice the sequence.

For slice operations, we can also specify the third parameter step. The step size defaults1Returns a continuous part of the text. Given a negative step-1, the reverse text is returned.

Input ()The function receives a real string parameter and prints it to the user. Then, the function waits for the user to input something. Once the user presses the Enter key, the input ends. The input function returns the input text.

After that we reverse the text, if the reverse text is the same as the original text, it represents a back-to-text (http://en.wiktionary.org/wiki/palindrome ).

 

Exercise questions:

Check whether a text is a text return. punctuation, space, and case are ignored.

For example"Rise to vote, sit ."It is also a back-to-text object, but we cannot identify it in the current example. Can you improve this example so that it can all do this?

 

File

By creatingFileClass Object, use itsRead,ReadlineOrWriteYou can read and write files.

The specific reading or writing method depends on the mode specified when you open the file.

Finally, when you complete file operations, callCloseClose the file.

Example:

#! /Usr/bin/Python

# Filename: using_file.py

 

Poem = '''/

Programming is fun

When the work is done

If you wanna make your work also fun:

Use python!

'''

 

F = open('poem.txt ', 'w') # Enable write mode

F. Write (POEM) # Write a file

F. Close () # close the file

 

F = open('poem.txt ') # If the open mode is not provided, the Read mode is assumed by default.

While true:

Line = f. Readline ()

If Len (line) = 0: # The length of 0 indicates EOF (Note: End of file is the end of the file)

Break

Print (line, end = '')

F. Close () # close the file

Output:

$ Python using_file.py

Programming is fun

When the work is done

If you wanna make your work also fun:

Use python!

Example:

First, we open a file through the built-in function open. In the function, we specify the file name to be opened and the desired open mode.

The open mode can be read mode ('R'), write mode ('W'), or append mode ('A '). In addition, we can also process file files ('T') and binary files ('B ').

There are actually many available modes. For details, seeHelp (open). DefaultOpenTreat the file as a text file 'T' and open it in Read mode 'R.

In this example, we first open the file in write text mode and useWriteMethod To write the file and callCloseDisable it.

Then we open the same file again for reading. Here we do not need to specify the open mode because 'read text file' is the default open mode.

In the loop, we useReadlineMethod to read each row of a file. This method returns an entire line of text including the line break at the end.

When an empty string is returned, it means that we have come to the end of the file, so we useBreakJump out of the loop.

By default, the print () function automatically prints a line feed. Because a line break is included at the end of the text line read from the file, we specify the ParameterEnd =''Suppress line breaks.

Finally, close the file.

Now, checkPoem.txtFile Content to ensure that the program has actually written and read the file.

 

Pickle

Python providesPickleThe standard module is used to store or read any Python object from a file. This is called a permanent storage object (persistently ).

Example:

#! /Usr/bin/Python

# Filename: pickling. py

 

Import pickle

 

# The name of the file where we will store the object

Shoplistfile = 'shoplist. data'

# The list of things to buy

Shoplist = ['apple', 'mango', 'carrot']

 

# Write to the file

F = open (shoplistfile, 'wb ')

Pickle. Dump (shoplist, f) # dump an object to a file

F. Close ()

 

Del shoplist # destroy the shoplist variable

 

# Retrieving objects from a file

F = open (shoplistfile, 'rb ')

Storedlist = pickle. Load (f) # Load objects from a file

Print (storedlist)

Output:

$ Python pickling. py

['Apple ', 'mango', 'carrot']

Example:

To store objects to files, we must first'Wb'Open the file and callPickleModuleDumpFunction. This process is called a collection object.

Next we will use the pickleLoadFunction to retrieve objects. This process is called unpickling objects.

 

Summary

We have discussed various forms of input/output, and used the pickle module for file processing.

Next, we will learn how to handle exceptions.

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.