This article discusses methods to assign values to variables.
Method 1: Direct Initialisation Method
In this method, you will directly assign the value in python but in other programming languages like C, and C++, you have to first initialize the data type of the variable. So, In Python, there is no need for explicit declaration in variables as compared to using some other programming languages. You can start using the variable right away.
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a = 5;
cout << "The value of a is: " << a;
}
|
C
#include <stdio.h>
int main()
{
int a = 5;
printf ( "The value of a is: %d" , a);
}
|
Java
import java.io.*;
class GFG {
public static void main(String args[])
{
int a = 5 ;
System.out.println( "The value of a is: " + a);
}
}
|
Python3
a = 5
print ( "The value of a is: " + str (a))
|
C#
using System;
class GFG{
public static void Main(String []args)
{
int a = 5;
Console.Write( "The value of a is: " + a);
}
}
|
Javascript
<script>
var a = 5;
document.write( "The value of a is: " + a);
</script>
|
OutputThe value of a is: 5
Assigning multiple values to different variables :
Unlike other languages, we can easily assign values to multiple variables in python easily.
Java
import java.io.*;
class GFG {
public static void main (String[] args) {
String a= "geeks" ,b= "for" ,c= "geeks" ;
System.out.println(a+b+c);
}
}
|
Python
a,b,c = "geeks" , "for" , "geeks"
print (a + b + c)
|
Javascript
# Assigning multiple values in single line
let [a,b,c]=[ "geeks" , "for" , "geeks" ]
console.log(a+b+c);
|
Method 2: Using Conditional Operator (?:)
This method is also called Ternary operators. So Basic Syntax of a Conditional Operator is:-
condition? True_value : False_Value
Using Conditional Operator, you can write one line code in python. The conditional operator works in such a way that first evaluates the condition, if the condition is true, the first expression( True_value) will print else evaluates the second expression(False_Value).
Below is the syntax in other popular languages.
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a = 20 > 10 ? 1 : 0;
cout << "The value of a is: " << a;
}
|
C
#include <stdio.h>
int main()
{
int a = 20 > 10 ? 1 : 0;
printf ( "The value of a is: %d" , a);
}
|
Java
import java.io.*;
class GFG {
public static void main(String args[])
{
int a = 20 > 10 ? 1 : 0 ;
System.out.println( "The value of a is: " + a);
}
}
|
Python3
a = 1 if 20 > 10 else 0
print ( "The value of a is: " , str (a))
|
C#
using System;
class GFG {
public static void Main(String []args)
{
int a = 20 > 10 ? 1 : 0;
Console.Write( "The value of a is: " + a);
}
}
|
Javascript
<script>
var a = 20 > 10 ? 1 : 0;
document.write( "The value of a is: " + a);
</script>
|
OutputThe value of a is: 1
One liner if-else instead of Conditional Operator (?:) in Python
Python3
a = 1 if 20 > 10 else 0
print ( "The value of a is: " + str (a))
|
OutputThe value of a is: 1