Python Tutorial 3 : Variables, String and String Operations

Posted on Posted in Software

In the previous tutorial, we discussed data types, some basic arithmetic operations, and type conversion. In this one, we are going to talk about variables, strings and it’s operations. So let’s begin!

In any programming language, variable plays a crucial role and Python is no exception. A variable allows you to store a value which can be used later in a program. Variables can be reassigned as many times as you want. The best thing is that variable doesn’t require to be declared with a specific data type, so initially, if you use a variable to store an integer, then you can reuse that variable for a string as well.

You can use letter, number and underscore to declare a variable but you cannot start with a number. It will give you syntax error. Even spaces are not allowed.

Accepted variables: var_1_accepted, this_var_is_valid, thisOneToo

Variables not accepted: 123_sorry, not this one either

Also remember that python is a case sensitive language and hence ‘Being’ and ‘being’ are two different variable names in Python. You can also take value of variable from user input. So you can write:

x = input(‘Enter the value: ‘)

If you try to reference a variable that you haven’t assigned yet, then it will give you an error. However, if you try to access an assigned variable after deleting it using del, then once again error. See the video.

Text parts can be done using string which is created between two single or double quotation marks. Some characters known as escape characters can’t be directly included in string like single quote in a single quote string, causing it to end prematurely. Same goes for double quote. Check the video to understand.

This can be avoided using a backslash before the characters. Python provides an easy way to avoid manually writing “\n” to escape newlines in a string. As you can see, we are writing a string with three sets of quotes and new lines are created by pressing enter.

When it comes to operations, we can add two strings which is known as concatenation. We have previously shown that ‘2’+’3’ gives ‘23’ since it is in string but adding a string to a number gives an error. Strings can be multiplied by integers, producing a repeated version of same string. Of course you can’t multiply two strings, nor can you multiply a string with a float.

print(‘hello’*3)

hellohellohello

So that’s it for this tutorial. I hope you have enjoyed it. Make sure you subscribe to our channel and press the bell icon so that you don’t miss the next video. Peace! 🙂

Spread it!

Leave a Reply