Python Foundation hardening 2-variables and data types

Source: Internet
Author: User

Knowledge points
    • Python keyword
    • Definition and assignment of variables
    • Input () function
    • Formatting of strings

Keywords and identifiers

Each programming language has its own grammatical rules, like the foreign language we speak.

The following identifiers are keywords of Python3 and cannot be used for the usual identifiers. Keywords must be spelled exactly as follows:

FalseDefifraisenone del ImportreturnTrueElif inTry andElseIs while asexcept Lambda withassertfinally nonlocal yield Break                for notclassFrom orContinue            GlobalPass
The content can be obtained in the PYTHON3 interpreter:

In Python, we don't need to specify a data type for a variable. So you can write it directly so that abc = 1 the variable abc is an integer type. If you write abc = 1.0 , then the variable abc is a floating-point type.

In the example above you should understand how to define variables in Python, that is, you just need to enter the variable name and value. Python can also manipulate strings, which are enclosed in single or double quotes, as in the following.

Reading input from the keyboard

Typically, Python's code does not need to read input from the keyboard. But we can still use functions in Python input() to do this, input() there is an optional string parameter for printing on the screen, and a string that returns the user input.

Let's write a program that reads a number from the keyboard and checks if the number is less than 100. This program name is /home/shiyanlou/testhundred.py .

# !/usr/bin/env Python3  number = Int (input ("Enter an Integer:"))if number <=:    print(" Your number is smaller than equal to]else:    print("Your number is greater than 100")

If number less than 100, the output "Your number is smaller than 100", if greater than 100, the output "Your number is greater than 100".

The program runs like this:

$./testhundred.  integer: smaller than/testhundred.  integer: 123 number is greater than 100

Next program to calculate the investment:

 #  !/usr/bin/env python3  amount = float  (Input ("Enter amount:") #   Enter the amount  inrate = float  (Input (" Enter Interest rate: ")) #   Enter interest rate  period = Int (input ("Enter period:")) #   Enter term  value = 0year  = 1while  year <= period: value  = Amount + (inrate * amount)  print  ("year {} Rs. {:. 2f} ". Format (Year, value) amount  = value year 
    = year + 1 
/home/chmod +x investment.  ./investment. pyenter amount: 10000Enter Interestrate: 0.14Enter period: 51 Rs. 11400.00  2 Rs. 12996.003 rs. 14815.444 rs. 16889.605 rs. 19254.15

while year <= period:This means that when year the value is less than period or equal, the following statement will continue to loop until it year is greater than the period stop loop.

Year {} Rs. {:.2f}".format(year, value)Called string formatting, curly braces and the characters in them are replaced with the parameters passed in as well str.format() year value . {:.2f}The meaning is to replace the floating-point number with 2-bit precision.

code example

This section includes several examples:

    1. Find the average of N numbers
    2. Fahrenheit to Celsius temperature conversion procedure

The following program is used to calculate the average of N numbers. Please write the program code to the file /home/shiyanlou/averagen.py , the program will need to enter 10 numbers, and finally calculate the average of 10 numbers.

Code content, understand the meaning of each line of code:

#!/usr/bin/env Python3N = 10sum= 0Count= 0Print("Please input number:") while Count< N: Number=float(input ()) Sum= Sum + Number    Count=Count+ 1Average= SUM/NPrint("n = {}, Sum = {}". Format (n,sum))Print("Average = {:. 2f}".format (average)) to run the program procedure, you need to enter10Number: $ cd/home/shiyanlou$chmod+x Averagen.py$./averagen.py1.23.43.533.22462.445.5N= ten, Sum = 65.2Average= 6.52

In the following procedure, we use the formula C = (F-32)/1.8 to convert Fahrenheit to Celsius temperature.

#!/usr/bin/env Python3Fahrenheit = 0Print("Fahrenheit Celsius") whileFahrenheit <= 250:Celsius= (fahrenheit-32)/1.8#Convert to Celsius    Print("{: 5d} {: 7.2f}". Format (Fahrenheit,Celsius)) Fahrenheit= Fahrenheit + 25{: 5d} means replace with 5integer with a character width that is not wide enough to fill with spaces. Run Program: $ CD/home/shiyanlou$chmod+x temperature.py$./temperature.Pyfahrenheit Celsius0-17.78 25-3.89 50 10.00 75 23.89 100 37.78 125 51.67 150 65.56 175 79.44 200 93.33 225 10 7.22 250 121.11
You can even assign multiple values to multiple variables in a single line and enter into the Python3 interactive interface:>>> A, B = 54>>>, 45>>>  b
    54 This technique is handy for exchanging two-digit values. >>> A, B = B, a>>> a54>>> b45

To understand how this works, you need to learn the tuple (tuple) data type. We create tuples with commas. On the right side of the assignment statement we create a tuple, which we call the tuple encapsulation (tuple packing), and the left side of the assignment statement is the tuple unpacking (tuple unpacking).

Here is another example of a tuple unpacking:

>>> data = ("Shiyanlou", "China", "Python")>>> name, country, language = data> >> name' Shiyanlou ' >>> country' China ' >>> language' Python '

Python Foundation hardening 2-variables and data types

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.