Python之路,Day1

本文详细介绍Python在Windows下的安装步骤及环境变量配置,并演示了第一个Python程序的编写与运行,包括变量使用、用户输入处理及基本的条件判断逻辑。

一、Python安装
windows:
1、下载安装包
https://www.python.org/downloads/
2、安装
默认安装路径:C:\python27
3、配置环境变量
【右键计算机】--》【属性】--》【高级系统设置】--》【高级】--》【环境变量】--》【在第二个内容框中找到 变量名为Path 的一行,双击】 --> 【Python安装目录追加到变值值中,用 ; 分割】
如:原来的值;C:\python27,切记前面有分号

linux、Mac:
无需安装,原装Python环境    ps:如果自带2.6,请更新至2.7

二、Hello World程序

1.在linux 下创建一个文件叫hello.py,并输入

1 print("Hello World!")

然后执行命令:python hello.py ,输出

localhost:~ lidun$ vim hello.py
localhost:~ lidun$ python hello.py
Hello World!

三、变量\字符编码  
Variables are used to store information to be referenced and manipulated in a computer program. They also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves. It is helpful to think of variables as containers that hold information. Their sole purpose is to label and store data in memory. This data can then be used throughout your program.

1.声明变量

#_*_coding:utf-8_*_
name = "Alex Li"

上述代码声明了一个变量,变量名为: name,变量name的值为:"Alex Li" 

2.变量定义的规则:

变量名只能是 字母、数字或下划线的任意组合
变量名的第一个字符不能是数字
以下关键字不能声明为变量名

['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

3.变量的赋值

name = "Lidun"
 
name2 = name
print(name,name2)

name = "Jack"

print("What is the value of name2 now?")

 

四、用户输入

 

#!/usr/bin/env python
#_*_coding:utf-8_*_
 
 
#name = raw_input("What is your name?") #only on python 2.x
name = input("What is your name?")
print("Hello " + name )

 输入密码时,如果想要不可见,需要利用getpass 模块中的 getpass方法,即:

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-
  
import getpass
  
# 将用户输入的内容赋值给 name 变量
pwd = getpass.getpass("请输入密码:")
  
# 打印输入的内容
print(pwd)

五、表达式if ... else

 

场景一、用户登陆验证

 

# 提示输入用户名和密码
  
# 验证用户名和密码
#     如果错误,则输出用户名或密码错误
#     如果成功,则输出 欢迎,XXX!
 
 
#!/usr/bin/env python
# -*- coding: encoding -*-
  
import getpass
  
  
name = raw_input('请输入用户名:')
pwd = getpass.getpass('请输入密码:')
  
if name == "alex" and pwd == "cmd":
    print("欢迎,alex!")
else:
    print("用户名和密码错误")

场景二、猜年龄游戏

在程序里设定好你的年龄,然后启动程序让用户猜测,用户输入后,根据他的输入提示用户输入的是否正确,如果错误,提示是猜大了还是小了

#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
 
my_age = 28
 
user_input = int(input("input your guess num:"))
 
if user_input == my_age:
    print("Congratulations, you got it !")
elif user_input < my_age:
    print("Oops,think bigger!")
else:
    print("think smaller!")

 

转载于:https://www.cnblogs.com/lilidun/p/5488298.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值