Python Learning-Basic 1

Source: Internet
Author: User
Tags arithmetic constant definition

One, variable:

1) Variable definition specification:

#1. Variable names can only be any combination of letters, numbers, or underscores
#2. The first character of a variable name cannot be a number
#3. Keywords cannot be declared as variable names [' and ', ' as ', ' assert ', ' Break ', ' class ',
' Continue ', ' Def ', ' del ', ' elif ', ' Else ', ' except ', ' exec ',
' Finally ', ' for ', ' from ', ' global ', ' if ', ' Import ', ' on ', ' is ',
' Lambda ', ' not ', ' or ', ' pass ', ' print ', ' raise ', ' return ', ' try ', ' while ', ' with ', ' yield ']

2) Variable format:

Variable name = value
Example: Name= ' Zhenxi '

3) Definition Method:

#驼峰体
Ageofoldboy = 56
Numberofstudents = 80
#下划线 (recommended)
Age_of_oldboy = 56
Number_of_students = 80

4) Define a bad way to name a variable

#1. The variable is named Chinese, pinyin
#2. Variable name too long
#3. Variable nouns are not expressive

5) The definition variable will be:id,type,value

Copy Code
The #1 equals sign compares the value,
#2 is compares the ID (the value is in the memory location)

#强调:
#1. The same ID means that the type and value must be the same
#2. Value the same type must be the same, but the ID may be different, as follows
>>> x= ' Info zhenxi:18 '
>>> y= ' Info zhenxi:18 '
>>> ID (x)
4376607152
>>> ID (y)
4376607408
>>>
>>> x = = y
True
>>> x is y
False

6) Constants

Constants are constant quantities, such as Pai 3.141592653 ..., or quantities that do not change during a program's operation
For example, if a person's age changes, then this is a variable, but in some cases, his age will not change, that is constant. In Python, there is no specific syntax for constants, and programmers have used the variable names to represent constants in all capitals.
Age_of_oldboy = 56

#ps: There is a special constant definition syntax in C,const int count =, and once defined as a constant, the change will be an error


Second, the file header:
The normal script file will have a file header, and Python is no exception:
The file header like the shell is:#!/bin/bash
The file header for Python is:
#!/usr/bin/env python
#-*-Coding:utf-8-*-


Three, the basic data type:
Digital Type classification:
#int整型
Definition:age=10 #age =int (Ten)
For identification: Age, grade, ID number, QQ number, number

#float浮点型
Definition:salary=3.1 #salary =float (3.1)
Used to identify: salary, height, weight,

Additional numeric types are described:
#int (integral type)
On a 32-bit machine, the number of integers is 32 bits and the value range is -2**31~2**31-1, which is -2147483648~2147483647
On a 64-bit system, the number of integers is 64 bits and the value range is -2**63~2**63-1, which is -9223372036854775808~9223372036854775807
#long (Long integer type)
Unlike the C language, Python's long integers do not refer to the positioning width, that is, Python does not limit the size of long integer values, but in fact, because of limited machine memory, we use a long integer value can not be infinite.
Note that, since Python2.2, Python automatically converts integer data to long integers if an integer overflows, so it does not cause any serious consequences if you do not add the letter L after long integer data.
Note: There is no longer a long type in Python3, all int
>>> a= 2**64
>>> type (a) #type () is a way to view data types
<type ' Long ' >
>>> B = 2**60
>>> type (b)
<type ' int ' >

#complex复数型
>>> x=1-2j
>>> X.imag
-2.0
>>> X.real
1.0


String:

#在python中, the quoted character is the string type, and Python does not have a character type.
Definition:name= ' Egon ' #name =str (' Egon ')
Used to identify: descriptive content, such as name, gender, nationality, ethnicity


What is the difference between #那单引号, double quotes, and multiple quotes? Let me tell you aloud that there is no difference between single and double quotes, only the following situation you need to consider a single pair of mates
msg = "My name is Egon, I ' m years old!"

#多引号什么作用呢? The function is that multiple lines of string must be in multiple quotes
msg = "'
Today I want to write a little poem,
Sing the praises of my deskmate,
You see his black short hair,
It's like a fried chicken.
‘‘‘
Print (msg)

#数字可以进行加减乘除等运算, where are the strings? Let me tell you aloud, too, can I? What? Yes, but only the "add" and "multiply" operations can be performed.
>>> name= ' Egon '
>>> age= ' 18 '
>>> Name+age #相加其实就是简单拼接
' Egon18 '
>>> name*5
' Egonegonegonegonegon '


#注意1: The efficiency of string addition is not high
The string 1+ string 3, and does not add the string 2 on the basis of string 1, but applies a completely new memory space to the string 1 and the string 3, the equivalent string 1 with the space of the string 3 is copied once,

#注意2: String only, cannot string plus other types

List:

#在 [] separated by commas, you can store n any type of value
Definition: students=[' Egon ', ' Alex ', ' Wupeiqi ',] #students =list ([' Egon ', ' Alex ', ' Wupeiqi ',])
Used to identify: a situation in which multiple values are stored, such as a person having multiple hobbies

#存放多个学生的信息: Name, age, hobby
>>> students_info=[[' Egon ', 18,[' play ',]],[' Alex ', 18,[' play ', ' sleep ']
>>> Students_info[0][2][0] #取出第一个学生的第一个爱好
' Play '

Dictionary:

#为何还要用字典?
To store a person's information: name, gender, age, is obviously a number of values, since it is a number of values, we can completely based on the list of just learning to store, as follows
>>> info=[' Egon ', ' Male ', 18]
The purpose of defining the list is not only to save, but also to consider the value, if I want to take out this person's age, can use
>>> Info[2]
18
But this is based on the knowledge that we already know the age in the 3rd place, we know that index 2 corresponds to age
That is:#name, sex, age
info=[' Egon ', ' Male ', 18]
And this is purely an assumption, and there is no real sense that the third place is the age, so we need to find a way, that can store multiple arbitrary types of values, but also can be hard to specify the value of the mapping relationship type, such as Key=value, which is used in the dictionary
The #在 {} is separated by commas and can hold multiple key:value values, and value can be any type
Definition:info={' name ': ' Egon ', ' age ': +, ' sex ': $ #info =dict ({' name ': ' Egon ', ' Age ' : ', ' sex ': ')
Used to identify: store multiple values, each value has a unique key, can be more convenient and efficient to take the value
Dictionary-related nesting, taking values

Boolean:

Copy Code
#布尔值, a true one false
#计算机俗称电脑, that is, when we write a program to let the computer run, it should be to let computers infinitely close to the human brain, or what the human brain can do, what the computer should be able to do, the main role of the human brain is data operation and logical operation, where the Boolean type of the simulation of the logic of human operation, that is, when a condition Mark with true, false if not established
>>> a=3
>>> b=5
>>>
>>> a > B #不成立就是False, i.e. fake
False
>>>
>>> a < b #成立就是True, which is true
True

Then you can do different things according to the result of the condition:
If a > B
Print (A is bigger than B)

Else
Print (A is smaller than B)
This is pseudo-code, but it means that the computer can perform different actions as the human brain does differently depending on the outcome of the judgment.
Copy Code

"//* Key *\\":

#1. mutable type: In the case where the ID is constant, value can be changed, which is called a mutable type, such as a list, a dictionary

#2. Immutable type: Once the value changes, the ID also changes, which is called the immutable type (ID variable, which means that a new memory space is created)

Four, formatted output

There are often scenarios in a program that require users to enter information and then print it in a fixed format

For example, ask the user to enter a user name and age, and then print the following format:

My name is Xxx,my age is xxx.

Obviously, the string concatenation with commas, only the user entered the name and age to the end, can not be placed in the specified XXX location, and the number must be a str (number) conversion to and string splicing.

This uses placeholders such as:%s,%d

#%s string placeholder: You can receive a string or receive a number
Print (' My name is%s,my '%s '% (' Egon ', 18)
#%d Digit placeholder: can only receive numbers
Print (' My name is%s,my-age is%d '% (' Egon ', 18)
Print (' My name is%s,my-age is%d '% (' Egon ', ') ') #报错

#接收用户输入, print to the specified format
Name=input (' Your Name: ')
Age=input (' Your Age: ') #用户输入18, will be stored as a string 18 and cannot be passed to%d

Print (' My name is%s,my '%s '% (name,age))

#注意:
#print (' My name is%s,my ' name,age ') #age as a string type and cannot be passed to%d, so an error will be

Exercise: Users enter their name, age, work, hobbies, and then print to the following format
------------Info of Egon-----------
Name:egon
Age:22
Sex:male
Job:teacher
-------------End-----------------

Code:
# name=input (' Your Name: ')
# age=input (' Your Age: ')
# sex=input (' Sex: ')
# job=input (' Your Jos: ')
#
# Print (
# ‘‘‘
#------------Info of%s-----------
# Name:%s
# Age:%s
# Sex:%s
# Job:%s
#-------------End-----------------
# "% (Name,name,age,sex,job)
# )

Basic operators

Computer can be carried out many kinds of operations, can not only subtraction so simple, operations by type can be divided into arithmetic operations, comparison operations, logical operations, assignment operations, member operations, identity operations, bit operations, today we only learn arithmetic operations, comparison operations, logical operations, assignment operations

Arithmetic operations

The following hypothetical variables: a=10,b=20

Comparison operation

The following hypothetical variables: a=10,b=20

Assignment operations

The following hypothetical variables: a=10,b=20

Logical operations

>>> true or Flase and falsetrue>>> (True or flase) and Falsefalse

Five, Process Control:

If...else format:
If condition:
Execute ""
Else
Execute ""

Example:
1 if: Woman's age >30 years old, then: Call Aunt

Age_of_girl=31
If Age_of_girl > 30:
Print (' Auntie Good ')
2 if: Woman's age >30 years old, then: Call aunt, otherwise: called Miss

Age_of_girl=18
If Age_of_girl > 30:
Print (' Auntie Good ')
Else
Print (' Miss Good ')

If...elif format:
If condition:
Execute ""
Elif Conditions:
Execute ""
...
Else
...

Example:
If: Score >=90, then: excellent

If the score >=80 and <90, then: good

If the scores are >=70 and <80, then: normal

Other situation: very poor



Score=input (' >>: ')
Score=int (Score)

If score >= 90:
Print (' excellent ')
Elif Score >= 80:
Print (' good ')
Elif score >= 70:
Print (' normal ')
Else
Print (' very poor ')

While condition loop, the syntax is as follows:

While condition:
# Loop Body

# If the condition is true, then the loop body is executed, after the execution is finished again, the condition is re-judged ...
# If the condition is false, then the loop body does not execute and the loop terminates

Example:
#打印0-10
Count=0
While Count <= 10:
Print (' Loop ', count)
Count+=1
An even number between #打印0-10
Count=0
While Count <= 10:
If count%2 = = 0:
Print (' Loop ', count)
Count+=1

#打印0-odd between 10
Count=0
While Count <= 10:
if count%2 = = 1:
Print (' Loop ', count)
Count+=1







Python Learning-Basic 1

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.