1. 程式人生 > >python1----variable,condition,function and loop

python1----variable,condition,function and loop

cto works font ppi support ket circus 記憶 iter

Python is like a programming language that‘s based on a snake. It is a weird language,is is strange,is‘s not easily understood by others.Welcome to being a PythonisaIt turns out that what Python was named for was Monty Python‘s Flying Circus.let‘s make it powerful and enjoyable?
Now.As you learn Python,remember you ‘re talking to a snake and this is a language that you dont already knowyou will learn the word "syntax error" a lot
Syntax error simply means that Python is lost.That means you cna learn ,but Python can not.,and your syntax is not something that Python undertands.

Install Python and atom

Python:https://www.python.org/downloads/
atom(Test editor):https://atom.io/

maybe you can add Python to PATH
print(‘hello from a file‘)
then using command f:
cd f:\python-study\py4e>
.\first.py
first.py --->because this file association has happenned in Windows and this does not work in Macintosh
python first.py

Windows:snipping tool (截圖工具)

the first thing we have in every programming language is what‘s called reserved words(預定字).

False    class    return    is    finally
None    if     for     lamdba    continue
True    def    from    while     nonlocal
and     del    global   not      with
as      elif    try     or      yield


assert   else    import   pass
break   except   in     raise

Sentences or Lines

x = 2 <------------Assignment statement
x = x + 2 <------------Assignment with expression
print(x) <------------Print function

Variable Operator Constant Function

Constants:we call it contants because they dont change.
Numeric constants are as you expect

String constants use single quotes(‘) or double quotes(")

Variables:
A varible is a named place in the memory where a programmer can store data and later retrieve the data using the variable "name"
Programmers get to choose the names of the variables
You can change the contents of a variable in a later statement

Python Variables Name Rules:
Must start with a letter or underscore_
Must consist of letters,numbers,and underscores
Case Sensitive

GOOD: spam eggs spam23 _speed
BAG : 23spam #sign var.12
DIFFERENT: spam Spam Spam

we have a technique called Mnemonic(記憶的).The idea is when you choose a variable name,you should choose a variable name to be sensible and Python doesnt care whether you choose mnemonic variable names or not.

Assignment Statements:
An assignment statement consists of an expression on the right-hand side and a variable to store the result
x = 3.9 * x * ( 1 - x ) (overwrite x on the left-hand with right-hand side )


operator Operation
+       Addition
-       Subtraction
*       Multiplication
/       Division 8/4=2.0 [Integer division produces a floating point result]
**       Power
%      Remainder

Order of Evaluation:
When we string operators together - Python must know which one to do first,which is called "operator precedence"
Parenthesis-----Power-----Multiplication-----Addition-----Left to Right

What does "Type" Mean?
In Python variables,literals,and constants have a "type".
Python knows the difference between an interger number and a string

For example "+" means "addition" if something is a number and "concatenate" if something is a string
>>>ddd=1+4
>>>print(ddd)
5
>>>eee=‘hello‘+‘there‘
>>>print(eee)
hellothere#+ means string1string2 without space!
#you can have as many things as you want with commas in print,and every comma adds a space , and ,so it‘s kind of friendly.

eee = eee + 1 #error
Python knows what ‘type‘ everything is and you can ask Python what type something is by using the type() function

>>> type(eee)
< class ‘str‘ >

Type Conversions:
when you put an interger and floating point in an expression,the interger is implicitly converted to a float
You can control this with the built-in functions int() and float()
99 and 99.0 are not the same.99.0 is a floating point number and 99 is a int one.
>>>i=42
>>>type(i)
<class ‘int‘>
>>>f=float(i)
>>>type(f)
<class ‘float‘>
>>>print(f)
42.0
what will be the value of x when the following statement is executed:
x=int(98.6) #print(x)---->98


String Conversions
You can also use int() and float() to convert between strings and integers
You will get an error if the string does not contain numeric characters.
>>>sval=‘123‘
>>>type(sval)
<class ‘str‘>
>>>print(sval + 1) %error
blablabla
>>>inval = int(sval)
>>>type(ival)
<class ‘int‘>
>>>print(ival + 1)
124
>>>nsv= ‘hello ssozh‘
>>>niv=int(nsv)#error
blablabla

User Input
input() function like scanf,but it have a liite different
The input() function returns a string,and input() will print things in brackets
attention:if I typed in 1,2,3,4 , it would be the string 1,2,3,4 not 1234.
Eg:
>>>nam=input(‘Who are you?\n‘)
>>>print(‘welcome‘,nam)#you can have as many things as you want with commas in print,and every comma adds a space , and ,so it‘s kind of friendly.
Who are you?
Bob
welcome Bob

Comments in Python
Anything after a # is ignored by Python
to Descirbe what is going to happen in a sequence of code
Docunment who wrote the code or other ancillary information
Turn off a line of code - perhaps temporarily



3 chapter conditional-statements

Comparison Operation(Boolean expression)      Python Meaning

    <                        less than
    <=                    less than or Equal to
    ==                        Equal to
    >=                    Greater than or Equal to
    >                        Greater than
    !=                       Not Equal

then return true or false
In python the spacing does matter!we indicate when it is that we want to get out of this block and then continue by de-indenting.
Warning:Turn off Tabs!
Although tab and spaces look tge same on your screen,but to Python,they may or may not be equivalent.And you can up with spurious errors that Python will give you
The idea is dont puy tabs in your document when you‘re writing Python programs.
Atom automatically uses spaces for files with ".py"extension.it automatically just uses,you can hit the tab key and it moves in spaces.
Nested decisions that works like the Russian dolls,and sometimes re-indenting as the end of both this block and the end of this block.
EG:

x = 42
if x>1 :
print(More than one)
if x < 100:
print(less than 100)
print(all done)

Two-way decisions:
if [conditions]:
[printcxxxxx]
else :
[sadsagfdsad]
print all done



multi-way if:

x = 15
if x < 2 :
print(small)
elif x < 10 :
print(medium)
elif x < 20 :
print(large)
elif x < 40 :    #although x=15<40 but ,it dosent matter,the next thing to do is exit 
print(Huge)
print(all done)

# No Else
x = 5
if x < 2 :
print(small)
elif x < 10 :
print(medium)
print(all done)




Question:which will never print regardless of the value for x ?

if x<2 :
print(below 2)
elif x>=2 :
print(Two or more)
else :
print(something eles)# this will never print

if x<2 :
print(below 2)
elif x < 20 :
print(below 20)
elif x < 10 :
print(below 10)#this will never print
else :
print(something else) 

The try/except Structure

$ cat notry.py
astr = hello bob
istr = int(astr)    #This program stops here
print(First,istr)    #So that code,it‘s as if it‘s not there
astr = 123
istr = int(astr)
print(Second,istr)

There is always blow up and then trace back.So we have to be able to compensate for situations that we know might cause errors.Especially those where the user can type something that can cause my program to blow up
So,here‘s how it works.

astr = Hello bob
try:
istr= int(astr)
expect:    #when the first conversion fails - it just drops into the expect:clause and the program continues.
istr = -1
print(First,istr)
astr = 123
try:
istr = int(astr)
except:
istr=-1

print(Second,istr)

#Sample try/except
rawstr = input(Enter a number:)
try:
ival = int(rawstr)
except:
ival = -1

if ival > 0:
print(Nice work)
else:
print(Not a number)


4 chapter Using-functions[store and reuse,other is sequential,conditional,iterations
Stored(and reused) step
Program:

def thing():
print(hello)
print(Fun)
#there is no output

thing()    #hello,fun
print(zip)    #zip
thing()#hello,fun

Building our Own Functions.We create a new function using the def keyword followed by optional parameters in parentheses.We indent the body of the function.This defines the function but does not execute the body of the function
Argements is input.A parameter is a variable which we use in the function definition.
Return Value : Often a function will take its arguments,do some computation,and return a value to be used as the value of the function call in the calling expression.The return keyword is used for this.

EG:
def greet():
return "Hello"

5、Loop


Loop:
Repeated Steps:
while:

if it is true ,this code executes and if it is not true,the code is skipped.This keyword is a lillte like if.an important part of any loop is what we call the iteration variable.if the iteration variable does not change,the loop will become a inifinte of zero loop.

EG:

n = 5
while n > 0 :
print(n)
n = n - 1
print(blastoff!)
print(n)

Break:
the break statement ends the current loop and jumps to the statement immediately following the loop.
attention,it‘s not to go a different place in the loop.It‘s escape the loop directoryly and instantancely.

continue:
it dose something like break statement,so it basicall says quit on the current iteration and go to the next iteration.

for:
Definete loops(for loops )have explicit iteration that change each time through a loop.These variables move through the sequence or set.
for dose a few thing for you ~!!

Making "smart" Loops:The trick is "knowing" something about hte whole loop when you are stuck writing code that only sees one entry at a time.
This is the iteration that get us to know the answer.But they dont instantly know the answer.We can using if,sum and count to solve sum,arg,count and filtering


None type: None,we think of it as the absence of a value,before this loop starts,the smallest number we‘ve seen is nothing.It can avoid we set a smallest number.
But we will find:TypeError: ‘<‘ not supported between instances of ‘int‘ and ‘NoneType‘
So,EG:

smallest_so_far = None#you will find -1
print(Before,smallest_so_far)
for the_num in [9,41,12,3,74,15] :
if smallest_so_far is None:    ##################this is very important
smallest_so_far = the_num
elif the_num <smallest_so_far:
smallest_so_far=the_num
print(smallest_so_far,the_num)
print(After,smallest_so_far)


The ‘is‘ and ‘is not‘ Operators
Python has an <is> operator that can be used in logical expressions .Implis "is the same as",Similar to,but stronger than ==
<is not> also is a logical operator

Question:Write a program that repeatedly prompts a user for integer numbers until the user enters ‘done‘. Once ‘done‘ is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.

largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" : break
#print(num)
try:
n=int(num)
except:
print("Invalid input")
continue
if largest==None:
largest=n
elif largest<n:
largest=n
if smallest==None:
smallest=n
elif smallest>n:
smallest=n

print("Maximum is",largest)
print("Minimum is",smallest)

python1----variable,condition,function and loop