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.

    Strings

    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.

     

    Backslash

    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.


    Newlines 

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

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

     

    Similarly, \t represents a tab.

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

    print("""this
    is a
    multiline
    text""")
    
    # OUTPUT
    this
    is a
    multiline
    text

     

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


    Concatenation 

    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
    Spameggs

     

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

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

     

    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
    spamspamspam
    2222

     

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


    Variables 

    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 "file0.py", 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)
    print(x + 3)
    print(x)
    
    # OUTPUT
    7
    10
    7

     

    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
    print(x)
    
    x = "This is a string"
    print(x + "!")
    
    
    # OUTPUT
     
    
    123.456
    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

    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()
    print(x)

     

    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())
    print(age)  

    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
    print(x)
    
    x += 3
    print(x)

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

    x = "spam"
    print(x)
    
    x += "eggs"
    print(x)

     

    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())
    print(num)

    The walrus operator accomplishes these operations at once:

    print(num:=int(input())) 

     

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

     
    Conclusion

    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. 
    Thanks!

    0 Comments

    To add a comment, please Signup or Login