In this article, we will how to assign values to variables in Python and other languages also.
Below are the steps and methods by which we can assign values to variables in Python and other languages:
Assign Values to Variables Direct Initialisation Method
In this method, we will directly assign the value in Python but in other programming languages like C, and C++, we 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. We 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>
|
Output
The value of a is: 5
Python Variables – Assign Multiple Values
Unlike other languages, we can easily assign values to multiple variables in python easily.
Python3
a,b,c = "Beginner" , "for" , "Beginner"
print (a + b + c)
|
Assign Values to Variables 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, we 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>
|
Output
The value of a is: 1
Python One liner Conditional Statement Assigning
Python3
a = 1 if 20 > 10 else 0
print ( "The value of a is: " + str (a))
|
Output
The value of a is: 1
Contact Us