Python - Strings and Variables

Programming PYTHON CORE SERIES Image

    Till the last part, we had discussed about the basic concepts in Python. In this part, we'll discuss about Strings and Variables.


    If you want to use text in Python, you have to use a string.
    string is created by entering text between two single or double quotation marks.

    print("Python is fun!")
    print('Always look on the bright side of life')


    The delimiter (" or ') used for a string doesn't affect how it behaves in any way.



    Some characters can't be directly included in a string. For instance, double quotes can't be directly included in a double quote string; this would cause it to end prematurely.

    Characters like these must be escaped by placing a backslash before them.
    Double quotes only need to be escaped in double quote strings, and the same is true for single quote strings. 

    print('Brian\'s mother: He\'s not an angel. He\'s a very naughty boy!')
    # OUTPUT
    Brian's mother: He's not an angel. He's a very naughty boy!


    Backslashes can also be used to escape tabs, arbitrary Unicode characters, and various other things that can't be reliably printed.


    \n represents a new line.
    It can be used in strings to create multi-line output:

    print('One \nTwo \nThree')
    # OUTPUT


    Similarly, \t represents a tab.

    Newlines will be automatically added for strings that are created using three quotes.
    For example:

    is a
    # OUTPUT
    is a


     This makes it easier to format long, multi-line texts without the need to explicitly put \n for line breaks.


    As with integers and floats, strings in Python can be added, using a process called concatenation, which can be done on any two strings.

    print("Spam" + 'eggs')
    # OUTPUT


    Even if your strings contain numbers, they are still added as strings rather than integers.

    print("2" + "2")
    # OUTPUT


    Adding a string to a number produces an error, as even though they might look similar, they are two different entities.

    String Operations 

    Strings can also be multiplied by integers. This produces a repeated version of the original string. The order of the string and the integer doesn't matter, but the string usually comes first.

    print("spam" * 3)
    print(4 * '2')
    # OUTPUT


    Strings can't be multiplied by other strings. Strings also can't be multiplied by floats, even if the floats are whole numbers.


    variable allows you to store a value by assigning it to a name, which can be used to refer to the value later in the program.
    For example, in game development, you would use a variable to store the points of the player.
    To assign a variable, use one equals sign

    user = "Ashutosh"


    In given example we assigned string "Ashutosh" to user variable.

    Variable Names

    Certain restrictions apply in regard to the characters that may be used in Python variable names. The only characters that are allowed are lettersnumbers, and underscores. Also, they can't start with numbers.
    Not following these rules results in errors.

    this_is_a_normal_name = 7
    123abc = 7
    # OUTPUT
     File "", line 3
        123abc = 7
    SyntaxError: invalid syntax


    Python is a case sensitive programming language. Thus, Lastname and lastname are two different variable names in Python.

    Working with Variables 

    You can use variables to perform corresponding operations, just as you did with numbers and strings:

    x = 7
    print(x + 3)
    # OUTPUT


    As you can see, the variable stores its value throughout the program.

    Variables can be reassigned as many times as you want, in order to change their value.
    In Python, variables don't have specific types, so you can assign a string to a variable, and later assign an integer to the same variable.

    x = 123.456
    x = "This is a string"
    print(x + "!")
    # OUTPUT
    This is a string!


    However, it is not good practice. To avoid mistakes, try to avoid overwriting the same variable with different data types.

    Taking User Input


    To get input from the user in Python, you can use the intuitively named input function.
    For example, a game can ask for the user's name and age as input and use them in the game.
    The input function prompts the user for input, and returns what they enter as a string (with the contents automatically escaped).

    x = input()


    Even if the user enters a number as input, it is processed as a string.

     The input statement needs to be followed by parentheses.
    You can provide a string to input() between the parentheses, producing a prompt message.

    For example:

    name = input("Enter your name: ")
    print("Hello, " + name) 


    The prompt message helps to clarify what input the program is asking for.

    Working with Input

    Let's assume we want to take the age of the user as input.
    We know that the input() function returns a string.
    To convert it to a number, we can use the int() function:

    age = int(input())

    Similarly, in order to convert a number to a string, the str() function is used. This can be useful if you need to use a number in string concatenation.
    For example:

    age = 42
    print("His age is " + str(age)) 


    You can convert to float using the float() function.

    You can use input() multiple times to take multiple user inputs.
    For example:

    name = input()
    age = input()
    print(name + " is " + age)   


    When input() function executes, program flow stops until a user enters some value.

    In-Place and Walrus Operators

    In-Place Operators

    In-place operators allow you to write code like 'x = x + 3' more concisely, as 'x += 3'.
    The same thing is possible with other operators such as -, *, / and % as well.

    x = 2
    x += 3

    These operators can be used on types other than numbers, as well, such as strings

    x = "spam"
    x += "eggs"


    In-place operators can be used for any numerical operation (+, -, *, /, %, **, //).

    Walrus operator 

    Walrus operator := allows you to assign values to variables within an expression, including variables that do not exist yet.
    Let's suppose we want to take an integer from the user, assign it to a variable num and output it:

    num = int(input())

    The walrus operator accomplishes these operations at once:



    The walrus operator makes code more readable and can be useful in many situations.


    Let's end this part right here and we'll discuss about Control Structures in the next part of the series.
    Till then, stay tuned. 


    To add a comment, please Signup or Login