返回介绍

Variables

发布于 2025-02-25 23:43:35 字数 1624 浏览 0 评论 0 收藏 0

Variables in Python are defined and typed for you when you set a value to them.

my_variable = 2
print(my_variable)
type(my_variable)
2
int

This makes variable definition easy for the programmer. As usual, though, great power comes with great responsibility. For example:

my_varible = my_variable+1
print (my_variable)
2

“If you leave out word, spell-check will not put the word in you” – Taylor Mali, The the impotence of proofreading

If you accidentally mistype a variable name, Python will not catch it for you. This can lead to bugs that can be hard to track - so beware.

Types and Typecasting

The usual typecasting is available in Python, so it is easy to convert strings to ints or floats, floats to ints, etc. The syntax is slightly different than C:

a = "1"
b = 5
print(a+b)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

<ipython-input-3-6463279979e9> in <module>()
      1 a = "1"
      2 b = 5
----> 3 print(a+b)


TypeError: cannot concatenate 'str' and 'int' objects
a = "1"
b = 5
print(int(a)+b)

Note that the typing is dynamic. I.e. a variable that was initally say an integer can become another type (float, string, etc.) via reassignment.

a = "1"
type(a)
print(type(a))

a = 1.0
print(type(a))

Python has some other special data types such as lists, tuples and dictionaries that we will address later.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文