记录博客 ZH-BLOG

python第一个小程序

时间:2018-07-16 15:32:11分类:python 基础

本次输入不再使用交互式环境,编写完整的 Python 程序,需要在文件编辑器中输入指令。在 IDLE 中打开文件编辑器,选择 FileNew File. 快捷键 Ctrl+N.

print('Hello world!')
print('What is your name?')
myName=input()
print('It is good to meet you,'+myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?')
myAge=input()
print('You will be '+str(int(myAge)+1)+' in a year.')	

然后保存为hw.py文件。运行 RUN  RUN Module. 快捷键 F5.

在交互式环境中, 程序输出应该看起来像这样:

Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ====================== RESTART: E:/python/project/hw.py ======================
Hello world!
What is your name?
zhanh
It is good to meet you,zhanh
The length of your name is:
5
What is your age?
10
You will be 11 in a year.

print()函数:打印字符串

input()函数:等待用户在键盘上输入一些文本,并按下回车键。

len()函数:字符串长度。

注意:转换函数的使用

>>> float(1)
1.0
>>> int(10.1)
10
>>> int('10')
10
>>> int('10.1')
Traceback (most recent call last):
File "", line 1, in 
int('10.1')
ValueError: invalid literal for int() with base 10: '10.1'
>>> int(float('10.1'))
10