Python-Day2

python3 中默认采用utf-8编码,不需要添加

# -*- coding:utf-8 -*-

python2 中默认ascii编码,需要添加.

import example 时,会把example.py 转成字节码文件 example.pyc 再使用example.pyc 。所以可以不存在 .py 文件,只存在 .pyc 文件。

import getpass

pwd = getpass.getpass('Password:')

#使输入密码不可见

  

python3 中输入函数用  input() ,若使用 raw_input() 会报错 NameError: name 'raw_input' is not defined

python2 中输入函数用raw_input()  (有时,如2.7.11也可以用input() )

作业:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

#输出 1-100 内的所有奇数

n = 1
while True:
	if n % 2 == 1:
		print(n)
	if n == 100:
		break
	n += 1
print('End')

#!/usr/bin/env python
# -*- coding:utf-8 -*-

#输出 1-100 内的所有偶数

n = 1
while True:
	if n % 2 == 0:
		print(n)
	if n == 100:
		break
	n += 1
print('End')

  

#!/usr/bin/env python
# -*- coding:utf-8 -*-

#上一题略加改进
 
n = 1
while n < 101:
    if n % 2 == 1:
        print(n)
        #pass
    else:
        pass #表示什么也不执行,当然可以不加else
        #print(n) #两者对调可以输出偶数,自己咋就没想到呢
    n += 1
print('END')

  

#!/usr/bin/env python
# -*- coding:utf-8 -*-

#求1-2+3-4+5 ... 99的所有数的和

n = 1
sum = 0
while True:
	if n % 2 == 1:
		sum += n
	elif n % 2 == 0:
		sum -= n
	if n == 100:
		print(sum)
		break
	n += 1
print('End')
#!/usr/bin/env python
# -*- coding:utf-8 -*-

#改进上一题

s = 0
n = 1
while n < 100:
	tem = n % 2
	if tem == 1:
		s += n
	else:
		s -= n
	n += 1
print(s)

  

  

#!/usr/bin/env python
# -*- coding:utf-8 -*-

#用户登陆(三次机会重试)

import getpass

n = 1
while True:
	user = raw_input('Input Your name:')
	pwd = getpass.getpass('Input Your Password:')
	if user == 'root' and pwd == 'toor':
		print('Success')
		break
	else:
		print('Try Again')
	if n == 3:
		print('3 Times Used')
		break
	n += 1
print('END')

  

#!/usr/bin/env python
# -*- coding:utf-8 -*-

#改进上一题

i = 0
while i < 3:
	user = raw_input("Username: ")
	pwd = raw_input("Password: ")
	if user == "h" and pwd == "1":
		print("Success!")
		break
	else:
		print("Tyr Again!")
	i += 1

  

--------------------------------------------------------------

原文地址:https://www.cnblogs.com/freelandun/p/6536761.html