gpt4 book ai didi

python - 语法错误: invalid token python 3

转载 作者:行者123 更新时间:2023-12-01 08:05:36 24 4
gpt4 key购买 nike

我的 Python 脚本有问题。当我运行这个Python脚本时:

class Student:
def __init__(self,student_name,student_id,student_phone):
self.student_name = student_name
self.student_id = student_id
self.student_phone = student_phone

obj = Student("ELizaa",1253251,16165544)

print("student name",obj.student_name,"\nstudent id",obj.student_id,"\nStudent phone",obj.student_phone)

工作正常。我得到了预期的输出。 但是student_phone0开头(例如0124575)时,我收到错误:

obj = Student("ELizaa",1253251,016165544)
^
SyntaxError: invalid token

为什么会发生这种情况?

最佳答案

在Python中,在任何数字前面添加0都需要额外的

  • x(对于十六进制)后跟任意十六进制数字范围 0-9a-fA-F .

  • o(八进制)后跟八进制数字范围 0-7 中的数字。

请看下面:

>>> 0o7
7
>>> 0o71
57
>>> 0o713
459
>>>
>>> 0xa
10
>>> 0xA
10
>>> 0x67
103
>>>

» If you exceed the range or if you don't use x | o after 0.

>>> 0o8
File "<stdin>", line 1
0o8
^
SyntaxError: invalid token
>>>
>>> 08
File "<stdin>", line 1
08
^
SyntaxError: invalid token
>>>

Suggestion: If you are still willing to use 0 & want to perform operations on phones (for testing) then you can use the below approach to update the numbers.

Here we will store phone number as string & whenever we will update that, we will remove 0 from front, convert the remaining part into an integer, add (any operation) ant convert back to its original (0 in front) form & I think it is good.

>>> student_phone = "016165544"
>>>
>>> # Add 3 to this
...
>>> student_phone = "0" + str(int(student_phone.lstrip("0")) + 3)
>>>
>>> student_phone
'016165547'
>>>

最后,您可以通过这种方式调用(就像您在问题中已经做的那样,除了第二个)。

>>> class Student:
... def __init__(self, student_name, student_id, student_phone):
... self.student_name = student_name
... self.student_id = student_id
... self.student_phone = student_phone
...
>>> obj = Student("ELizaa",1253251,16165544)
>>> print("student name",obj.student_name,"\nstudent id",obj.student_id,"\nStudent phone",obj.student_phone)
student name ELizaa
student id 1253251
Student phone 16165544
>>>
>>> obj = Student("ELizaa",1253251,"016165544")
>>> print("student name",obj.student_name,"\nstudent id",obj.student_id,"\nStudent phone",obj.student_phone)
student name ELizaa
student id 1253251
Student phone 016165544
>>>

关于python - 语法错误: invalid token python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55551063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com