[Part I] Introduction to Python ๐Ÿ

[Part I] Introduction to Python ๐Ÿ

ยท

7 min read

A few days back I was scrolling through my Twitter feed when I caught sight of this tweet by Catalin Pit๐Ÿ‘‡

This inspired me to start this series .I will try to release two blogs every week, and talk about concepts that I learn on the go. Let's make fresh and new mistakes and learn from them together.

Let's start our journey ! ๐Ÿš‚

Why Python ๐Ÿ?

A perfectly valid question! Of all the languages why did I choose to learn Python all of a sudden?

The popularity of Python has been increasing day-by-day. It is being used in Data Science, Machine Learning, AI, Cloud Computing, Web Development, you name it! It is also being used to automate DevOps and various day-to-day activities.

We'll surely get there!

Python was designed by Guido van Rossum in the late 1980s. You might be thinking he must really like these ๐Ÿ๐Ÿ๐Ÿ๐Ÿ , right? Well, may be not! Taking a direct quote from the documentation

"When he began implementing Python, Guido van Rossum was also reading the published scripts from โ€œMonty Pythonโ€™s Flying Circusโ€, a BBC comedy series from the 1970s. Van Rossum thought he needed a name that was short, unique, and slightly mysterious, so he decided to call the language Python."

Let's keep the humor alive while learning it too!

As is customary for all programmers when starting a new language, let's say hello to the world.

I am using PyCharm as my IDE. If you want to download it too, follow the installation guide .

def main():
        print("Hello,World!)
# This provided line is required at the end of a Python file
# to call the main() function.
if __name__ == '__main__':
    main()

After running the program, the terminal looks like this.

2021-04-29 (2).png

Let's break down the above program from the top.

def main(): -> This is how we write the main function in Python. def -> keyword defines a function. main-> is the function name. ()->opening and closing parenthesis is always placed after the function name. We end it all with a :.

Now let's come inside main(). How do I know it is inside main()? The indentation shows it to us. The indentation in Python is 4 spaces by default. If you are familiar with curly braces {} , we do not use it in Python. Indentation, in Java , C, JavaScript, etc does not cause any problems in the running of the program. Now, it will. The 4 space indentation helps the computer to understand that those are statements within the function.

# -> hash or pound sign is used to add single line comments in Python.

""" """ -> Triple quotes are used to add multi-line comments in Python.

print("Hello,World!") -> The print command prints text to the terminal. Text printed is between "" double or '' single quotes.

Which quotes do I use?

def main():
    # Used double quotes because didn't has a single quote in it.
    print("I didn't steal the cookie from the cookie jar")

    #Used single quotes because we used double quotes within the statement to be printed
    print('He said,"Yes, you did!".')

if __name__ == '__main__':
     main()

Let's run the program and have a look at the terminal.

2021-04-29 (4).png

So, we use double quotes when we have a single quote present inside the text to be printed and vice versa.

Look at the next piece of code.

if __name__ == '__main__':
    main()

First of all, do you think this statement is within the main() function?

If your answer is no, then you are absolutely correct. Look at the indentation. It is at the same level as the function header. It checks if the program is being run by the 'main' module. If yes, then it calls our main() function.

Let's go to the next step. This program will now take an input from the user. We are going to perform the Herculean task ๐Ÿ’ช of adding two numbers. Don't worry, we will break it down to make it simpler.

def main():
    # We will add two numbers here
    num1 = input("Enter first number: ")
    num1 = int(num1)
    num2 = input("Enter second number: ")
    num2 = int(num2)
    total = num1 + num2
    print("The total is " + str(total) + ".")

if __name__ == '__main__':
    main()

Let's understand the program in parts.

input -> takes text input from the user.

What does input do?

  • Prints the text within double(or single) quotes inside it in the terminal.

  • Then, waits for the user's input.

  • The user's input is then assigned to the variable.

For those who are new to programming, you might be thinking๐Ÿค” What is a variable? and What does assigning a variable even mean?

What is a variable?

It is a place to store information in a program. It associates a name with the value. The value inside a variable can be manipulated as and when required.

Assigning a variable?

You can think of assigning a value to a variable as creating a box with the name equal to the variable name and adding the value inside the box.

= is used as the assignment operator. The value to the right of it is stored inside the variable present in the left. First time we use it, it creates the variable. Subsequent usage, will update the value of the variable. The variable can change value with just another assignment.

Let's take an example,

num1 = 2 -> assigning a variable num1 with 2.

num1 = num1+1 -> Suppress the mathematician in you, I am not crazy, yet๐Ÿ˜. Look at the right side, num1+1 will give you 3(= 2+1) which will then be updated inside num1. Hence, if we now print(num1) we will get 3 as the output.

Run this program and check the output for yourself๐Ÿ‘‡

def main():
    num1 = 2
    print(num1) #Gives output 2
    num1 = num1 + 1
    print(num1) #Gives output 3

if __name__ == '__main__':
    main()

A few more points about variables....

Variables are visible only inside the function in which they are declared called "scope" of the variable.

Naming of Variables:

  • Variables start with letters or underscore.
  • Contains only letters, digits and underscore.
  • "keywords" or built-in commands in Python cannot be used as variables.
  • Variable names are case-sensitive.

Variables should :

  • Variables also should be descriptive(because remember we are trying to make programs that are readable to human beings, that is, a human being should understand what you were trying to do)
  • Variables in python are written in snake case for good programming style. eg, turn_left or country_name.

When you store variables in Python it is a object.

What types of information can Python store?

  • int -> Integer, eg:- 20, 4, -2, -3 etc (real numbers with no decimal points)

  • float -> Floating Point values, eg:- 20.0, 4.5, 3.14159 etc.

  • str ->string, text characters(between either " " or ' ') eg, "hello", 'hello', '10'

Note: - '10'(str) is not the same as 10(int) . '10' cannot be added to 20 to give us 30, whereas 10 can.

  • bool -> Boolean, logical values - either True/False.

Note:- Capital 'T' in True and capital 'F' in False.

Now that we are familiar with the data types, we can go back to adding to numbers. After inputting a number, why are we writing num1 = (int)num1 or num2 = (int)num2?

Note that input takes text or string values. We are assigning the integer form of the number into our variable, so that we can perform integer operations on it, in this case, Addition.

total = num1 +num2 -> total stores the summation of num1 and num2. Easiest statement in the whole program. ๐Ÿ˜ƒ

print("The total is " + str(total) + ".")

What is happening inside print ?

  • The + is being used to concatenate two strings.

  • "The total is " ->is a string.

  • str(total) -> Converts total which is an int (since, it stores the addition of two int values) to string. Why do we need to convert it to string? Because we can only concatenate two strings (and not a string and an int)

  • "." prints the last full stop.

Congratulations!!! We now know every part of our program.

Let's run it. 2021-04-29 (6).png

You might wonder, can we never print a string and an integer value together, without conversion? Well, yes you can.

print("hello" ,1 ,2) solves our problem. The comma in between, will print the space automatically.

Output : - hello 1 2

This was an Introduction to Python. Play around with what you have learnt. You may ask questions in the Comments below. Let's learn together!

Next -> Operators and Random Function in Python๐Ÿ

Happy learning!!

ย