SyntaxError:无效的令牌python 3

2024-10-02 08:27:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我的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),我得到了一个错误

^{pr2}$

为什么会这样?在


Tags: nameself脚本idobjinitdefphone
3条回答

在python3中,不能使用016165544来创建一个整数变量。在其他编程语言中,它是一个八进制数,例如C。在Python中,应该使用0o16165544或{}。在

但是,您想要创建的是一个学生ID和电话号码,所以我建议您使用string。在

像这样:

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

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

  • x(用于十六进制)后跟十六进制数字范围内的任何数字0-9或{}或{}。

  • 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.

^{pr2}$

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
>>> 

以数字0开头的数字使其成为八进制数,但行为有一些细微差别。请参阅此解决方案:Invalid Token when using Octal numbers

相关问题 更多 >

    热门问题