首页 » Python » Python基础(if,while,for)

Python基础(if,while,for)

 

1、#!/usr/bin/env   python这个比#!/usr/bin/python要好,因为python命令的路径不一定是在/usr/bin目录下面,所以用#!/usr/bin/env   python根据系统的环境变量去找。

2、# -*- coding: utf-8 -*-这条命令是先搞python解释器,用什么编码来执行源码,当然你程序也要保存为utf-8无bom格式啊。

3、python 2里的raw_input和python3里的input是一样的,python2里的input一般不用,它是让你输入变量名,而且你这个变量名要事先定义,不然会报错,所以在python2里一般不使用input。

让用户输入内容,但输出的内容都是字符串,假设你输入的是数字的话,想要让其变成int类型的话,可以用int(input(“pls you old year:”)),转换,查看类型type(变量)
4、for 和 while循环都可以使用else,shell至少是没有这样的,如果for下面有break结束循环,那么else后面的语句是不会执行的,只有for条件不满足的时候,会跳到下面执行else语句;遇到continue的时候是跳本次循环,进行下一次,也就是continue之下的语句都没有执行了。

5、for i in range(1,10,2)==》(起始,结束,步长)

 

分支与循环举例:

1、if分支,猜数字

number = 23
guess = int(input('Enter an integer: '))

if guess == number:
    print('Congratulations,you guessed it.')
    print('(but you do not win any prizes!)')
elif guess < number:
    print('No,it is a little highter thant that')
else:
    print('No,it is a little lower than that')
print('Done')

2、while循环

number = 23
running = True

while running:
    guess = int(input('Enter an integer:'))
    if guess == number:
        print('Congratulations,you guessed it.')
        running = False
    elif guess < number:
        print('No,it is a little lower than that.')
    else:
        print('NO,it is a little higher than that.')
else:
    #while循环可以使用else语句,很奇怪。
    print('The while loop is over.')
print('Done')

i = 1
while i<10:
    print('the number is ',i)
    i +=1
print('Over')

#for ...in循环也可以用else,
#for i in rang(1,5):
    #print(i)
#else:
    #print('Over')

for j in range(1,13,2):
    print(j)

guess高兴玩:

#!/usr/bin/env python
# -*- conding: utf-8 -*-
# Author:Sacus
age_of_jim = 18
i = 0
while i < 3:
    age = int(input("pls guess age:"))
    if age_of_jim == age:
        print("you got it ,great!!!")
        break
    elif age_of_jim > age:
            print("think bigger!")
    else:
        print("think smaller")
    i += 1
    if i == 3:
        continue_confirm = input("Do you want to keep guessing ? ")
        if continue_confirm != 'n':
            i = 0
else:
    print("you have tried too many times,fuck off!!!")

3、for循环:

#!/usr/bin/env python
# -*- conding: utf-8 -*-
# Author:Sacus
for i in range(0,10):
    if i < 5 :
        print("loop",i)
    else:
        continue
    print("hehe...")


for i in range(10):
    print("-------",i)
    for j in range(10):
        print(j*i)
        if j > 5:
            break

 

 

 

原文链接:Python基础(if,while,for),转载请注明来源!

0