美文网首页
Python:input() 和while 循环

Python:input() 和while 循环

作者: 庭阶 | 来源:发表于2020-04-16 18:30 被阅读0次

    1.用户输入input()

    input()函数,python 将用户输入解读为字符串。

    message=input("Tell me something,and I will repeat it back to you:")
    print(message)
    
    prompt="If you tell us who you are,we can personalize the message you see"
    prompt+="\nWhat is your first name?"
    name=input(prompt)
    print("Hello "+name+"!")
    
    image.png

    1.1.使用int() 将input的输入转换成数字

    用int()将input 的输入转换为数字后才能用于数值的计算和比较等。

    height=input("How tall are you,in inches?")
    height=int(height)
    if height>=36:
        print("\nYou're tall enough to ride!")
    else:
        print("\nYou're be able to ride when you're a little older")
    
    

    1.2求模运算符:%

    求模运算符:%,将两个数相除并返回余数

    number=input("Enter a number,and I'll tell you if it's even or odd:")
    number=int(number)
    if number%2==0:
        print("\nThe number "+str(number)+" is even")
    else:
        print("\nThe number "+str(number)+" is odd")
    
    

    2. while 循环

    for 循环用于针对集合中的每个元素的一个代码块,while 循环是不断的运行,直到指定的条件不能满足位置。

    2.1使用while 循环:

    prompt=input("\nTell you something,and I will repeat it back to you:")
    prompt+="\nEnter 'quit' to end the program!"
    message=''
    
    while message!='quit':
        message=input(prompt)
        print(message)
    
    #使用标志,将while 的条件设置为一个变量,成为标志,只要比较这个标志是True
    #还是False 来判断循环条件是否满足
    prompt=input("\nTell you something,and I will repeat it back to you:")
    prompt+="\nEnter 'quit' to end the program!"
    active=True
    
    while active:
        message=input(prompt)
        if message=='quit':
            active=False
        else:
            print(message)
    
    

    2.2 使用break 退出循环

    要立即退出while 循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可以使用break 语句。
    break 语句用于控制程序流程,可使用它来控制哪些代码将执行,哪些代码不执行,从而让程序按你的要求执行代码。
    break 语句可以使程序退出遍历列表或字典的for 循环。

    #以True 大头的循环会一直执行下去,直到遇见break.使用break 控制流程,退出程序
    prompt=input("\nTellyou something,and I will repeat it back to you:")
    prompt+="\nEnter 'quit' to end the program!"
    while True:
       city=input(prompt)
       if city=='quit':
           break
       else:
           print("I'd love to go to "+city.title()+"!")
    

    2.3 在循环中使用continue

    #输出<10的奇数
    current_number=0
    while current_number<10:
        current_number+=1
        if current_number % 2==0:
            continue
        else:
            print(current_number)
    

    相关文章

      网友评论

          本文标题:Python:input() 和while 循环

          本文链接:https://www.haomeiwen.com/subject/suqdvhtx.html