Assigning Values in Python and Other Languages

Here we will discuss how to assign values to variables.

Method 1: Direct Initialization method

#Code to demonstrate variable assignment in Python 3

# Using Direct Initialisation Method

# initialising variable directly

a = 10

# print value 

print (“value of a is: ” + str(a))

Output:

value of a is: 10

 

Method 2: Using conditional operator

Below is a code in C++

// C++ code to demonstrate variable assignment

// upon condition using Conditional Operator

#include <bits/stdc++.h>

using namespace std;

int main()

{

            // initialising variables using Conditional Operator

            int a = 20 > 10 ? 1 : 0;

            // printing value of a

            cout<< “The value of a is: ” << a;

}

Output:

The value of a is: 1

One liner if-else in place of Conditional Operator in Python

# Code for demonstrating variable assignment

# by using One liner if-else

# initialising variable using Conditional Operator

# a = 30 > 20 ?1 : 0 is not possible in Python

# Instead there is one liner if-else

a = 1 if 30 > 20 else 0

 

# printing the value of a 

print (“Value of a is: ” + str(a))

Output:

Value of a is: 1

 

Leave a Reply

Your email address will not be published. Required fields are marked *