Python_学习_字符串和数字

来源:互联网 发布:数据库报表是什么 编辑:程序博客网 时间:2024/06/10 04:07

作为Python的小白,许多知识需要一点点的积累:


1,在Python语句里,if 语句后需要加上冒号,否则会报错:

>>> myval=None
>>> print(myval)
None
>>> if myval == None
SyntaxError: invalid syntax
>>> print(myval)
None
>>> if myval==None:
print("The variable myval doesn't have a value")



The variable myval doesn't have a value


2,在Python中‘10’和10的意义不同,前者作为字符串,而后者作为数字。前者不可以直接比较大小,后者是可以的。

需要转换的话,可以使用int函数和str函数进行转化。

>>> age='10'
>>> converted_age=int(age)
>>> if converted_age==10:
print("Hello")



Hello


>>> age=10
>>> converted_age=str(age)
>>> if converted_age==10:
print("Fail")


需要注意的是,如果想要转换带小数点的数字,会得到一条错误的提示:

>>> age='10.5'
>>> converted_age=int(age)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    converted_age=int(age)
ValueError: invalid literal for int() with base 10: '10.5'


改正的方法是,用float来代替int  。 float函数可以处理不是整数类型的数字。


>>> age='10.5'
>>> converted_age=float(age)
>>> print(converted_age)
10.5

如果要把没有数字的字符串改成数字,也会得到错误的提示:

>>> age='ten'
>>> converted_age=int(age)
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    converted_age=int(age)
ValueError: invalid literal for int() with base 10: 'ten'

0 0