转载 原文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