Python first day

Source: Internet
Author: User
Tags python script

One, Python data type

string, number, tuple (tup), List (list), Dict (dictionary)

1. Digital Operation:

1.1 Arithmetic: +-*/% (for redundancy)

Print 2+24print 1+2*49print 1.0/2.00.5print 2%42



2. String manipulation:

2.1. String: Enclosed in single or double quotation marks

print ' Hello ' hello


2.2. String concatenation: Add multiple strings together with A + sign

print ' Hello ' + ' world ' Hello World


2.3. String escaping: In Python, strings are enclosed in single or double quotes, and if there are characters inside the string that need to be escaped (for example: "and ' itself), simply add the escape character before the character: \ Can

Common escape characters:

>>> print ' My name\ ' s lilei ' my name ' s Lilei

4. Variables: Variable values can be string, number, list, dict, tup

x = ' Hello World ' print xhello worldage = 20print age20

5. Get user input: Raw_input () #python内置函数

#代码x = raw_input (' Please input a string: ') print ' Hello ' +x# enter world output Hello World

6. String formatting:

Common types:

%s: string

%d: Integral type

%f: Floating-point type

%x: Hex

Percent: indicates% itself

name = ' Liuyang ' age = 26# number and string cannot be added directly #26 to a number, cannot be connected to a string, so we want to convert the type to string print ' Hello ' +name+ ', and I Am ' +str (age) + ' years old ' Hello liuyang,and I am years old# string formatting%s Introduction variable trailing% end meaning left string end now to be substituting variable) print ' Hello%s,and I am%s years old '% (name,ag e) Hello Liuyang,and I am years old# with%s replaced by%d placeholder, representing a number >>>print ' Hello%s,and I am%d years old '% (name,age) Hell o liuyang,and I am years old

7. Data type

int: integral type

STR: string

float: Float type

BOOL: Boolean type

x = raw_input (' Print input a number: ') y = raw_input (' Print input a number2: ') print int (x) +int (y) #输入x 3 input y 4# output 7

8.Python built-in function strip ():

. Strip () #消除字符串两边空格

#默认是空格, it can be another character

. strip (' \ n ')

#消除换行符

. Rstrip () #消除字符串右边空格

. Lstrip () #消除字符串左边空格

. Upper () uppercase Turn lowercase

. Upper (). Lower () lowercase to uppercase

name = ' Liuyang ' Print Name.strip () liuyangprint name.lstrip () Liuyang print Name.rstrip () liuyangprint Name.strip (). Up Per () Liuyangprint Name.strip (). Upper (). Lower () Liuyang

9.Python built-in function strip ():

Type ()

Judging data types

name = ' Liuyang ' Print type (name) str

10. Process Control

10.1. Boolean value: True,false

True: Indicates True

False: Indicates false

4>3truenot 0true5>6false

10.2. Logical operation: And OR not

#A and B are true when both A and B are true, and all other cases are false

#A or B is a and b as long as one is true and true, the condition is set to True

#not A If A is false returns True if A is true returns false

Note: The priority of ' and ' is higher than ' or '

10.3.if Else judgment:

If condition judgment (True/false): The condition is true if the following statement is executed

else: #条件为假执行else语句

Conditions for the false case:

#空字符串

#空列表

#数字0

#空字典都是

#none

If ': print ' 123 ' else:print ' 1231343 ' 1231343#if not 0:print ' add ' else:print ' dd ' add#list = []>>>if l Ist:print ' list is not empty for true ' else:print ' aaa ' aaa#if dict:print ' 123132 ' else:print ' AF ' AF

10.4.while Loop:

#while conditions are established:

# If the condition is true, the code continues to execute; not immediately false

#while循环直到情况是false才会退出

#while true always loops, break manual termination

Break and continue are both for the For loop and the while loop

Break: Jump out of the loop

#continue: Skip this cycle

i = 0

While i<20:

Print I

i = i + 1

#

>>>name = ' '

# definition name is NULL, while the name is not NULL is true, code is executed,

# name Empty is false, condition evaluates false exit print name

While not name:

Name=raw_input (' Input your name ')

print ' Hello ' +name

10.5.for Cycle sequence: specifically for List,dict, later with more process Control

For name in [' 2 ', ' 3 ', ' 4 ']: Print name2 3 4

Exercise 1: Enter a number that does not print all numbers for 0 o'clock and if the data input is 0 exit directly

#/usr/bin/python#coding=utf-8sum = 0while true:num = Int (raw_input (' Input a number ')) if num = = 0:breakelse:sum = sum + int (num) Print sum execution script: input 23 22 22 Input 0 Exit script, print input number sum 67

Exercise 2: The principal is 10000, the annual interest rate is 3.25%, ask how much money, the deposit can be turned over

#/usr/bin/python#coding=utf-8money=10000lixi=0.0325y=0# If the money is less than 20,000 and true then the loop executes, flase jumps out of the loop That is, money greater than 20000 is the principal rollover while the <= 20000:money=money* (1+lixi) y = y + 1print money,y# Execute script 20210.6986788 deposit rollover 22

Exercise 3: Print a maximum of two values

#/usr/bin/python#coding=utf-8unsort_num = [1,2,3,444,555,3234,35,65535,65535,21] #print unsort_nummax_num1 = 0max_ num2 = 0for i in unsort_num:if i > max_num1:max_num2 = MAX_NUM1MAX_NUM1 = Ielif i > max_num2:max_num2 = iprint "Max Num Is:%s,second Max num is:%s "% (max_num1,max_num2) #打印结果max num is:65536, second Max num is 65535

Exercise 4: User login, verify user and password, password input error three times log out

Name = raw_input (' Input your Name: '). Strip () if name = = ' Liuyang ': Count = 0while count<3:passwd = raw_input (' Input your passwd: ') if passwd = = ' 123456 ':p rint ' User%s login sucessfully! '% ( Name) breakelse:print ' wrong passwd,please input again! ' Count +=1print ' passwd wrong three times,the count%s is locked! '% ( Name) Else:print "User%s not exists,please confirm!"% ( Name

Exercise 5: Enter a number, compare with 50, greater than 50 prompt input number is too large, less than 50, prompt input number is too small, three opportunities, more than three times, return input error

Before optimization:

#/usr/bin/python#coding=utf-8compare_num = 50count = 0while count<=3:input_num = Int (raw_input (' Input a number: ')) if Input_num = = Compare_num:print ' input number correct ' breakelif input_num > Compare_num:print ' entered the number%s is greater than%s, and there is%d chance '% (Input_num, Compare_num,3-count) Else:print ' entered number%s is less than%s and%d chance '% (input_num,compare_num,3-count) Count +=1# optimized ##/usr/bin/  Python#coding=utf-8import Syscompare_num = 50count = 0while Count<=3:input_num = raw_input (' Input a number: ') Try:num = int (num) except exception,e:print ' input illegal ' sys.exit () time = 3-countif input_num > Compare_num:print ' The number entered is too large, and%s chance '% ( Time) Elif Input_num < Compare_num:print ' entered the number is too small, and%s chance '% '% of else:print ' input number correct ' Breakcount +=1


#引申:

Exit (): Is the Python system function Import sys #导入系统函数

Break with Exit () exit is a direct exit from the Python script, and break exits the current loop


Exception Check Handling

Try

1/0 #执行语句, and return execution results

Except Exception,e:

Print "Syntax error"


Python first day

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.