如何在Python中为变量赋值

本文讨论了将值分配给变量的方法。

方法1:直接初始化方法

# Python 3 code to demonstrate variable assignment  
# upon condition using Direct Initialisation Method 
  
# initialising variable directly 
a = 5
  
# printing value of a 
print ("The value of a is: " + str(a)) 

输出:

The value of a is: 5

方法2:一行if-else(类似C/C++的条件运算符(?:)

# Python 3 code to demonstrate variable assignment  
# upon condition using One liner if-else 
  
# initialising variable using Conditional Operator 
# a = 20 > 10 ? 1 : 0 is not possible in Python 
# Instead there is one liner if-else 
a = 1 if 20 > 10 else 0
  
# printing value of a 
print ("The value of a is: " + str(a)) 

输出:

The value of a is: 1

六一编程网

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Next Post

如何在Python中不使用换行符进行打印?

周六 3月 21 , 2020
通常人们从C/C++到Python切换,不知道如何打印两个或多个变量或语句,而不必在Python中输 […]