python全栈开发学习 02

本节内容

一些学习笔记

death_age=80
name=input("your name:")
age=input("your age:")
#input接受的所有数据都是字符串,即便你输入的是数字,也会被当作字符串处理
print(type(age))
print("your name:",name)
print("you can still live for",str(death_age - int(age)),"years...")
#删除str()也可以运行

关于python中 if 语句    http://www.runoob.com/python/python-if-statement.html

score = int(input("your score:"))
if score > 90:
      print("A")
elif score > 80:
      print("B")
elif score > 70:
      print("C")
elif score > 60:
      print("D")
else:
      print("滚")

用 if 语句猜年龄

age_of_princal = 56
guess_age = int( input("input your guess age:"))
'''
if guess_age == age_of_princal then

    print ("yes")
else
    print("no")
'''
if guess_age == age_of_princal:
      print("yes,you got it..")
else:
      print("no,it's wrong.")


age_of_princal = 56
guess_age = int( input("input your guess age:"))
'''
if guess_age == age_of_princal then

    print ("yes")
else
    print("no")
'''
if guess_age == age_of_princal:
      print("yes,you got it..")
elif guess_age > age_of_princal:
      print("should try samller..")
else:
      print("should try bigger...")

找出三个数中最大的:

a = int(input("please input number 1:"))
b = int(input("please input number 2:"))
c = int(input("please input number 3:"))
int(max_num = 0)
if a>b:
      max_num = a
      if max_num > c:
            print("Max_num is",max_num)
      else:
            print("Max_num is",c)
else:
      max_num = b
      if max_num > c:
            print("Max_num is",max_num)
      else:
            print("Max_num is",c)

利用while语句猜年龄:

'''
age = 50
flag = True
while flag:
       user_input_age = int(input("Age is :"))
      if user_input_age == age:
            print("Yes")
            flag = False
      elif user_input_age > age:
            print ("Is bigger")
      else:
            print("Is smaller")
print("End")            
'''
age = 50


#break


while True:
      user_input_age = int(input("Age is :"))
      if user_input_age == age:
            print("Yes")
            break
      elif user_input_age > age:
            print ("Is bigger")
      else:
            print("Is smaller")
print("End")   


#continue

num = 1
while num <= 10:
      num += 1
       if num == 3:
             continue
      print(num)
      
#结束当次循环,继续下一次循环。当continue之前的那条语句为真,不执行它后面的语句

'''
while 条件:
      .....
else:
      ......
'''
num = 1
while num <= 10:
      num += 1
       if num == 3:
             continue
      print(num)
else:
      print("bulabula")

#想要打印出来的东西变成一行
print("hello,world.")
print("hello,world.")
print("hello,world.")
只需要
print("hello,world.",end="")
print("hello,world.",end="")
print("hello,world.",end="")

换行符 linux下 \n  windows下 \r\n  MAC下 \r

# 利用while语句实现 用#输出一个长方形,高和宽由用户指定

heigth = int(input("Heigth:"))
width = int(input("Width:"))


num_heigth = 1
while num_heigth <= heigth:
      num_width = 1
      while num_width <= width:
            print("#",end="")
            num_width += 1
      print()
      num_heigth += 1
      
'''
在python2的版本中,应尽量使用raw_input
如果在2中使用了input
则输入的数据得加引号

name = input('please input your name:')
运行
please input your name:'bulabula'
注意得加引号,而raw_input则不用



pyton初学常见的报错:

在运行或编写一个程序时常会遇到错误异常,这时python会给你一个错误提示类名,告诉出现了什么样的问题(Python是面向对象语言,所以程序抛出的异常也是类)。能很好的理解这些错误提示类名所代表的意思,可以帮助你在最快的时间内找到问题所在,从而解决程序上的问题是非常有帮助的。

搜集了一些python最重要的内建异常类名,并做了简单的介绍:

AttributeError:属性错误,特性引用和赋值失败时会引发属性错误

NameError:试图访问的变量名不存在

SyntaxError:语法错误,代码形式错误

Exception:所有异常的基类,因为所有python异常类都是基类Exception的其中一员,异常都是从基类Exception继承的,并且都在exceptions模块中定义。

IOError:一般常见于打开不存在文件时会引发IOError错误,也可以解理为输出输入错误

KeyError:使用了映射中不存在的关键字(键)时引发的关键字错误

IndexError:索引错误,使用的索引不存在,常索引超出序列范围,什么是索引

TypeError:类型错误,内建操作或是函数应于在了错误类型的对象时会引发类型错误

ZeroDivisonError:除数为0,在用除法操作时,第二个参数为0时引发了该错误

ValueError:值错误,传给对象的参数类型不正确,像是给int()函数传入了字符串数据类型的参数。

1)忘记在 if , elif, else , for , while , class ,def 声明末尾添加:(导致 “SyntaxError :invalid syntax”)

该错误将发生在类似如下代码中:

if spam == 42

    print('Hello!')

2)使用 = 而不是 ==(导致“SyntaxError: invalid syntax”)

 = 是赋值操作符而 == 是等于比较操作。该错误发生在如下代码中:

if spam = 42:

    print('Hello!')

3)错误的使用缩进量。(导致“IndentationError:unexpected indent”、“IndentationError:unindent does not match any outer indetation level”以及“IndentationError:expected an indented block”)

记住缩进增加只用在以:结束的语句之后,而之后必须恢复到之前的缩进格式。该错误发生在如下代码中:

print('Hello!')

    print('Howdy!')

 

或者:

 

if spam == 42:

    print('Hello!')

  print('Howdy!')

 

或者:

 

if spam == 42:

print('Hello!')

4)在 for 循环语句中忘记调用 len() (导致“TypeError: 'list' object cannot be interpreted as aninteger”)

通常你想要通过索引来迭代一个list或者string的元素,这需要调用 range() 函数。要记得返回len 值而不是返回这个列表。

该错误发生在如下代码中:

spam = ['cat','dog', 'mouse']

for i inrange(spam):

    print(spam[i])

5)尝试修改string的值(导致“TypeError: 'str' object does not support itemassignment”)

string是一种不可变的数据类型,该错误发生在如下代码中:

spam = 'I have apet cat.'

spam[13] = 'r'

print(spam)

而你实际想要这样做:

spam = 'I have apet cat.'

spam = spam[:13] +'r' + spam[14:]

print(spam)

6)尝试连接非字符串值与字符串(导致 “TypeError: Can't convert 'int' object to strimplicitly”)

该错误发生在如下代码中:

numEggs = 12

print('I have ' +numEggs + ' eggs.')

 

而你实际想要这样做:

numEggs = 12

print('I have ' +str(numEggs) + ' eggs.')

 

或者:

 

numEggs = 12

print('I have %seggs.' % (numEggs))

7)在字符串首尾忘记加引号(导致“SyntaxError: EOL while scanning string literal”)

该错误发生在如下代码中:

 

print(Hello!')

 

或者:

 

print('Hello!)

 

或者:

 

myName = 'Al'

print('My name is '+ myName + . How are you?')

8)变量或者函数名拼写错误(导致“NameError: name 'fooba' is not defined”)

该错误发生在如下代码中:

foobar = 'Al'

print('My name is '+ fooba)

 

或者:

 

spam = ruond(4.2)

 

或者:

 

spam = Round(4.2)

9)方法名拼写错误(导致 “AttributeError: 'str' object has no attribute'lowerr'”)

该错误发生在如下代码中:

spam = 'THIS IS INLOWERCASE.'

spam =spam.lowerr()

10)引用超过list最大索引(导致“IndexError: list index out of range”)

该错误发生在如下代码中:

spam = ['cat','dog', 'mouse']

print(spam[6])

11)使用不存在的字典键值(导致“KeyError:‘spam’”)

该错误发生在如下代码中:

spam = {'cat':'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}

print('The name ofmy pet zebra is ' + spam['zebra'])

12)尝试使用Python关键字作为变量名(导致“SyntaxError:invalid syntax”)

Python关键不能用作变量名,该错误发生在如下代码中:

class = 'algebra'

Python3的关键字有:and, as, assert, break, class, continue, def, del, elif,else, except, False, finally, for, from, global, if, import, in, is, lambda,None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield

13)在一个定义新变量中使用增值操作符(导致“NameError: name 'foobar' is not defined”)

不要在声明变量时使用0或者空字符串作为初始值,这样使用自增操作符的一句spam += 1等于spam = spam + 1,这意味着spam需要指定一个有效的初始值。

该错误发生在如下代码中:

spam = 0

spam += 42

eggs += 42

14)在定义局部变量前在函数中使用局部变量(此时有与局部变量同名的全局变量存在)(导致“UnboundLocalError: local variable 'foobar' referencedbefore assignment”)

在函数中使用局部变来那个而同时又存在同名全局变量时是很复杂的,使用规则是:如果在函数中定义了任何东西,如果它只是在函数中使用那它就是局部的,反之就是全局变量。

这意味着你不能在定义它之前把它当全局变量在函数中使用。

该错误发生在如下代码中:

someVar = 42

def myFunction():

    print(someVar)

    someVar = 100

myFunction()

15)尝试使用 range()创建整数列表(导致“TypeError: 'range' object does not support itemassignment”)

有时你想要得到一个有序的整数列表,所以 range() 看上去是生成此列表的不错方式。然而,你需要记住 range() 返回的是 “range object”,而不是实际的 list 值。

该错误发生在如下代码中:

spam = range(10)

spam[4] = -1

也许这才是你想做:

spam =list(range(10))

spam[4] = -1

(注意:在 Python 2 中 spam = range(10) 是能行的,因为在 Python 2 中 range() 返回的是list值,但是在 Python 3 中就会产生以上错误)

16)不错在 ++ 或者 -- 自增自减操作符。(导致“SyntaxError: invalid syntax”)

如果你习惯于例如 C++ , Java, PHP 等其他的语言,也许你会想要尝试使用 ++ 或者 -- 自增自减一个变量。在Python中是没有这样的操作符的。

该错误发生在如下代码中:

spam = 1

spam++

也许这才是你想做的:

spam = 1

spam += 1

17)忘记为方法的第一个参数添加self参数(导致“TypeError: myMethod() takes no arguments (1 given)”)

该错误发生在如下代码中:

class Foo():

    def myMethod():

        print('Hello!')

a = Foo()

a.myMethod()
'''

'''
利用* 输出一个直角三角形,行数可以由用户指定(倒直角三角形)
*
**
***
****


#倒直角三角形


line = int(input("please input line:"))
while line > 0:
      tmp = line
      while tmp > 0:
            print("*",end="")
            tmp = tmp-1
      print()
      line -= 1
      

#通过对以上内容的思考,写出倒着的99乘法表


num1 = 9

while num1 > 0:
      num2 = 1
      while num2 <= num1:
            print(  str(num2)+"*"+ str(num1) +"="+ str(num2 * num1),end="\t")       # \t表示制表符可以让它变得整齐
            num2 += 1
      print()
      num1 -= 1

'''


#通过对以上内容的思考,写出99乘法表

num1 = 1

while num1 <= 9:
      num2 = 1
      while num2 <= num1:
            print(  str(num2)+"*"+ str(num1) +"="+ str(num2 * num1),end="\t") # \t表示制表符可以让它变得整齐
            num2 += 1
      print()
      num1 += 1


      
'''
听说有一行代码实现99乘法表的:

print('\n'.join('   '.join(['%sX%s=%-2s' % (y,x,x*y) for y in range(1,x+1)]) for x in range(1,10)))     #就能一行代码打印出99乘法表


'''
 #while 实现99乘法表01
num1 = 0
while num1 <= 5:
      print(num1,end="$")
      num2 = 0
      while num2 <= 7 :
            print (num2,end="-")
            num2 += 1
      num1 += 1
      print()  #等价于print(end"\n")

运行结果:
0$0-1-2-3-4-5-6-7-
1$0-1-2-3-4-5-6-7-
2$0-1-2-3-4-5-6-7-
3$0-1-2-3-4-5-6-7-
4$0-1-2-3-4-5-6-7-
5$0-1-2-3-4-5-6-7-

'''

i = 1

while i <= 9:
      j = 1
      while j <= i:
            z = i*j
            print("%d*%d=%d"%(i,j,i*j),end = ' ')
            j += 1
      print()
      i += 1

'''
运行结果:

1*1=1
2*1=2 2*2=4
3*1=3 3*2=6 3*3=9
4*1=4 4*2=8 4*3=12 4*4=16
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81




i = 1
while i <= 9:
    j = 1
    while j <= i:
        print("%d*%d=%-2d"%(i,j,i*j),end = ' ')  # %d: 整数的占位符,'-2'代表靠左对齐,两个占位符
        j += 1
    print()
    i += 1

'''

更多关于python中while语句:http://www.runoob.com/python/python-while-loop.html

猜你喜欢

转载自www.cnblogs.com/root1/p/9255197.html