Python入门之if和while语句

if语句和While语句

if语句,如果满足某种情况就继续往下执行代码块,break表示跳出循环,continue表示重新开始循环

while语句,用来在任何条件为真(需要定义iteration variables)的情况下重复执行一个代码块,一般用作无限循环

a = "python","php"
type(a)
tuple
s = "python"
if "p" in s:
    s = "you need " + s 
    print(s)
you need python

break表示跳出循环

a = 0
while a < 3:  #a表示iteration variables
    s = input("input your language:")
    if s == "python":
        print("your lang is {0}".format(s))
        break
    else:
        a += 1
        print("a = ",a)
input your language:1
a =  1
input your language:python
your lang is python

continue表示继续重新开始循环


a = 11
while a > 0:
    a -= 1
    if a%2 == 0:
        continue
    else:
        print(a)
9
7
5
3
1
#随机数
import random
number = random.randint(1,100)#创建从1开始的100的元素的行列式,即low=1,size=100

guess = 0

while True:
    num_input = input("please input an iteger(1-100):")
    guess += 1
    if not num_input.isdigit():
        print("please input integer")
    elif int(num_input) < 0 or int(num_input) >= 100:
        print("the number should be in 1-100.")
    else:
        if number == int(num_input):
            print("Ok.it\'s only {0}".format(guess))
            break
        elif number > int(num_input):
            print("your number is smaller.")
        else:
             print("your number is bigger.")
            
    
please input an iteger(1-100):4
your number is smaller.
please input an iteger(1-100):50
your number is bigger.
please input an iteger(1-100):25
your number is smaller.
please input an iteger(1-100):38
your number is smaller.
please input an iteger(1-100):40
your number is smaller.
please input an iteger(1-100):45
your number is bigger.
please input an iteger(1-100):43
your number is bigger.
please input an iteger(1-100):42
Ok.it's only 8
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值