Python学习2——几个简单的语句

本文从Python的HelloWorld开始,逐步介绍条件语句如IF-ELSE和IF-ELIF-ELSE,循环语句如FOR和WHILE,通过实例帮助读者理解和掌握Python的基础语法。

转载 原文Python学习之路【第一篇】-Python简介和基础入门:https://www.cnblogs.com/linupython/p/5713324.html

1、Hello World

#!/usr/bin/env python
# -*- coding:utf-8 -*-
print("Hello World!")

2、IF ELSE

#!/usr/bin/env python
# -*- coding:utf-8 -*-
username=input("PLease input your username:\n") # \n表示换行?
passwd=input("Please input your passwd:\n")
if username=="HH" and passwd=="HH":             # if后面接冒号,==
    print("welcome logon!%s"%username)          # %s占位符,后接%username
else:                                           # else后面接冒号
    print("Invalid username or password,please check your input!")

3、IF ELIF ELSE

#!/usr/bin/env python
# -*- coding:utf-8 -*-
age=int(input("Please input your age\n"))    # \n换行
if age<=14:                                  # elif增加判断条件
    print("You are so young!\n")             # else后面没有条件
elif age>14 and age <=20:
    print("Now you are a boy!\n")
elif age>20 and age <=40:
    print("Hei,man!\n")
elif age>40 and age<=60:
    print("Oh,man!\n")
else:
    print("BYE\n")

4、FOR

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import random               # 导入随机数模块
age=random.randrange(10)    # 随机生成小于10的整数
for i in range(3):          # i取值0,1,2
    if i<2:
        guess_number=int(input("Please input the age of my dog you guess:\n"))
        if guess_number>i:
            print("The age you guess is a little bigger,think smaller!\n")
        elif guess_number<i:
            print("The age you guess is a little smaller,think bigger!\n")
        else:
            print("bingo,you guess!")
            break                     # break
    else:
        guess_number=int(input("Please input the age of my dog you guess:\n"))
        if guess_number==age:
            print("bingo,you guess!\n")
        else:
            print("Game over!You failed!")

5、FOR(advanced)

#!/usr/bin/env python
# -*- coding:utf-8 -*-
age=25
count=0
i=0
while count<10:
    if i<3:
        guess_number=int(input("Please input the age you guess:\n"))
        if guess_number==age:
            print("You won!\n")
        elif guess_number>age:
            print("guess smaller!\n")
        else:
            print("guess bigger!\n")
        i +=1
    else:
        continue_flag=input("Do you want to continue?Please type Y to continue,type N to quit:\n")
        if continue_flag=="Y":
            i=0
        else:
            print("BYE")
            break
    count +=1

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值