Performing string and integer comparison & printing variables with text in python.

Till now we have learned how to use variables, how to run a python script, and other small things.

Suppose you want to compare if a is equal to b or not, then how will you do that in python.

So here comes the tip, how to compare string or integer values and print them in python.

Lets see an example below.

Python Script to compare and print Variables

user@ngelinux$ cat sixth.py 
#!/usr/local/bin/python3 
var1= "hi"  ### define string
var2=2.1  ### define float
var3=10   ### define integer

### print var1 if it is equal to "hi"
if var1=="hi":
    print("The string value is = %s" % var1)

### print var2 if its a float and equal to 2.1
if isinstance(var2, float) and var2==2.1:
    print("The float value is = %f" % var2)

if var3==10:
    print("The integer value is = %d" % var3)
user@ngelinux$ 

Output

user@ngelinux$ ./sixth.py 
The string value is = hi
The float value is = 2.100000
The integer value is = 10
user@ngelinux$ 

In the similar fashion above, we can use the variables and print them with strings in output.

The % operator is used to find the modulus of two integers.
a % b returns the remainder after dividing a by b.

However in Python it is also used for the early age style of string formatting.
Hence a % b can return a string if “a” is a string and b is a value (or set of values) which can be inserted into a.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments