How to assign values to variables in Python and other languages

Course Curriculum

How to assign values to variables in Python and other languages

How to assign values to variables in Python and other languages

This article discusses methods to assign values to variables.

Method 1: Direct Initialisation Method

# 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))
Output:
The value of a is: 5

Method 2: Using Conditional Operator (?:)
Below is the syntax in other popular languages.

// C code to demonstrate variable assignment
// upon condition using Conditional Operator

#include <stdio.h>

int main()
{
// initialising variables using Conditional Operator
int a = 20 > 10 ? 1 : 0;

// printing value of a
printf("The value of a is: %d", a);
}
Output:
The value of a is: 1

One liner if-else instead of Conditional Operator (?:) in Python

# 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))
Output:
The value of a is: 1

How to check if a string is a valid keyword in Python? (Prev Lesson)
(Next Lesson) How to print without newline in Python?