Python Learning Note--day1

Source: Internet
Author: User

#Python Day1

Tags: python

[toc]# #1. Hellow World Program # # #1) Hellow World creates a file called hellow.py in Linux.

File contents:

#!/usr/bin/env pythonprint("Hellow World!")

The need to specify an interpreter in Linux #!/usr/bin/env python means to find an environment variable named Python in the entire Linux system.

Give the file execute permission to execute the file using the./hellow.py.

Output Result:

Hellow World!

Python Common escape characters:

Escape Character | Description---|---\n| \r| carriage return \v| portrait tab \t| landscape tab \ "| "\\ |
\ (at end of line) | Continuation character \a| Bell \b| backspace (Backspace) \000| empty





# #2. Variable # # #1) What is a variable?

Variables are used to store information that is referenced and manipulated in a computer program. They also provide a way to tag data with descriptive names so that our programs can be more clearly understood by the reader and ourselves. It is helpful to consider variables as containers for storing information. Their sole purpose is to mark and store data in memory. This data can then be used throughout the program.

# # #变量定义的规则:

    • Rules for variable definitions
      • Variable names can only be 字母、数字或下划线 any combination of
      • The first character of a variable name cannot be a number
      • Write the variable name to have meaning, otherwise you and others can not understand
      • Variable names are best not Chinese or pinyin, with multiple words separated by underscores
      • The following 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‘, ‘in‘, ‘is‘, ‘lambda‘, ‘not‘, ‘or‘, ‘pass‘, ‘print‘, ‘raise‘, ‘return‘, ‘try‘, ‘while‘, ‘with‘, ‘yield‘]

# # #什么是常量?

Constants: The amount that is not changed after the definition, such as π is 3.14 ...

Python defines constants, and variable names are capitalized such as:PIE = "em"


# # #2) variable assignment:

name = "byh"name2 = nameprint(name,"-----",name2)name = "em"print(name,"-----",name2)

Print: Output character


Output Result:

byh ----- byhem ----- byhProcess finished with exit code 0

# # # #为什么第二个name2输出的是 byh, not em?

    • Because:
      • Name2 just found byh by name, Name2≠name.
      • Name = em is just a new definition of name,name2 or the first name variable to find BYH

# # #注释:
When line comments "#" identifies when the line
Multi-line comments "or" "means multiple lines of comment

# # #3) ternary operation

a = 1b = 5c = 9d = a if a > b else cprint(d)d = a if a < b else cprint(d)

Output Result:

9        #如果a > b条件不成立,结果就是c的值1        #如果a < b条件成立,结果就是a的值




# #3. User Input # # #1) Simple user input

username = input("username:")password = input("password:")print("Hellow",username)

When entering a password, if you want the password to be invisible, you need to use getpass the Getpass method in the module:

import getpassusername = input("username:")password = getpass.getpass("password:")print("Hellow",username)

# # #2) user input, Output call variable

Method One:

name = input("name:")age = int(input("age:"))print(type(age))job = input("job:")salary = int(input("salary:"))print(type(salary))info = ‘‘‘-------- info of %s--------Name:%sAge:%dJob:%sSalary:%d‘‘‘ %(name,name,age,job,salary)print(info)
%s represents string String
%d Represents an integer
%f Represents a number that has a decimal point
Int () Cast type is integer
STR () Cast type is string
Print (Type (salary)) Output String type

Output Result:

name:emage:19<class ‘int‘>job:ITsalary:1234567<class ‘int‘>-------- info of em--------Name:emAge:19Job:ITSalary:1234567Process finished with exit code 0

> method Two: "#Author: Byhname = input (" Name: ") age = Int (input (" Age: ")), print (type (age)) job = input (" job: ") salary = Int ( Input ("Salary:")) print (Type (salary))

info = "--------info of--------Name:Age:Job:Salary:". Format (_name=name,_age=age,_job=job,_salary=salary)

Print (info)

>输出结果:

Name:emage:19<class ' int ' >job:itsalary:1234567<class ' int ' >

--------Info of em--------name:emage:19job:itsalary:1234567

Process finished with exit code 0

<br/>>方法三:

#Author: Byhname = input ("Name:"), age = Int (input ("Age:")), print (type (age)) job = input ("job:") salary = Int (input ("Salary: ")) Print (Type (salary))

info = "'--------info of {0}--------name:{0}age:{1}job:{2}salary:{0}". Format (name,name,age,job,salary)

Print (info)

>输出结果:

Name:emage:19<class ' int ' >job:itsalary:1234567<class ' int ' >

--------Info of em--------name:emage:emjob:19salary:em

Process finished with exit code 0

<br/><br/>---<br/><br/>##4.表达式if ... else###场景一 : 用户登陆验证

_username = "Byh" _password = "123" username = input ("username:") password = input ("Password:")

If _username = = Username and _password = = Password:print ("Welcome User Login ...". Format (Name=_username)) Else:print (" Invaild username or password! ")

elif|如果这个条件不成立,那么下个条件是否成立呢---|--->输出结果:

#验证成功输出username: Byhpassword:123welcome user byh Login ...

#验证失败输出username: Empassword:123invalid username or password!

###场景二 : 猜年龄游戏

_myage = 22myage = Int (Input ("Myage:"))

if myage = = _myage:print ("Yes, it is") Elif myage > _myage:print ("should be smaller..") Else:print ("Should is more big..")

>输出结果

Myage:17should is more big.

Myage:23should be smaller.

Myage:22yes, it is

<br/><br/>---<br/><br/>##5.while循环###1)简单while循环

Count = 0while True:print ("Count:", count) count +=1if count = = 1000:break

>当这个条件成立时:True(永远为真),如果没有定义 `break`条件结束循环,则会一会循环下去。<br/>###2)while循环猜年龄游戏

#实现用户可以不断的猜年龄, up to 3 opportunities, continue pressing the Ruyi key, Exit Press "N"

_myage = 22count = 0

While count < 3:myage = Int (Input ("Myage:")) if myage = = _myage:print ("Yes it is.") Breakelif myage > _myage:print ("should be smaller ...") Else:print ("Should is more big ...") count +=1if count = = 3:countin E_config = input ("Does want to keep gussing?") If countine_config! = "N": Count = 0

break|结束当前整个循序---|---continue|跳出本次循环,进入下次循环count|添加计数>输出结果:

#继续猜: Myage:1should is more big...myage:2should is more big...myage:3should is more big...do your want to keep gussing?myage : 12should was more big...myage:22yes it was.

Process finished with exit code 0

#不猜退出: Myage:1should is more big...myage:2should is more big...myage:3should is more big...do your want to keep gussing?n

Process finished with exit code 0

<br/><br/>---<br/><br/>##6.for循环###1)简单for循环

#0, 10 is range, 1 is increment for I in range (0,10,1):p rint ("number", I)

>输出结果:

Number 0number 1number 2number 3number 4number 5number 6number 7number 8number 9

Process finished with exit code 0

###2)for循环猜年龄游戏

#用户最多猜3次_myage = 22

For I in range (3): myage = Int (Input ("Myage:")) if myage = = _myage:print ("Yes it is.") Breakelif myage > _myage:print ("should be smaller ...") Else:print ("Should is more big..")

Else:print ("You have tried too many times")

>输出结果:

Myage:1should is more big. Myage:2should is more big. Myage:3should is more big. You have tried too many times

Process finished with exit code 0

##7.作业###1)作业三:多级菜单* 三级菜单* 可一次选择进入各子菜单* 使用知识点:列表、字典

#Author: byh# defines a level three dictionary data = {' Beijing ': {"changping": {"Shahe": ["Oldboy", "Test"], "Tian Tong Yuan": ["Ikea", "big Run Hair"],}, "Chaoyang":, "Haidian":,}, ' Shandong ': {"Texas":, "Qingdao" :, "Jinan":,}, ' Guangdong ': {"Dongguan":, "Guangzhou":, "Foshan":,},}exit_flag = False

While not exit_flag:for i in data: #打印第一层print (i)

Choice = input ("Select enter 1:") If choice in data: #判断输入的层在不在 and not exit_flag:for i2 in Data[choice]: #打印第二层 Print (i2) Choice2 = input ("Select Enter 2:") if Choice2 in Data[choice]: #判断输入的层在不在 and not E Xit_flag:for i3 in Data[choice][choice2]: #打印第三层 print (i3) Choice3 = Input ("Select Enter 3:") if Choice3 in Data[choice][choice2]: #判断输入的层在不在 for I4 in Data[choice                    ][CHOICE2][CHOICE3]: #打印最后一层 print (i4) Choice4 = input ("Last layer, press B to return:") if Choice4 = = "B": #返回 pass #占位符, or later may add code elif Choice4 = = "Q": # Exit Exit_flag = True if choice3 = = "B": Break Elif             Choice3 = = "Q": Exit_flag = True if Choice2 = = "B": break elif Choice2 = = "Q": Exit_flag =True 

Python Learning Note--day1

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.