Complete Python Tutorials For Free.
Learn Python easily.
What’s so different about this blog anyway, there are tons of resources out there? But have you ever seen Python Tutorials through Anime/Manga? I guess not. This is part one of a five-part blog article that shares Beginner’s Guide to get started with Python.
Since you are already here, there is no need to mention, Why you need to learn Python. But at the end of part 5, I will let you know what to do next and where to implement it. Without wasting time, let’s dig in👨💻
How To Install Python?
Installation of Python is quite easy. You can download Python for Windows, macOS, and Linux for free. Most Linux distributions have Python pre-installed, and I prefer Linux as well. Make sure you download the latest version of Python. To check the Python version in your system, enter the following command in CLI.python –version. (there are two – before version)
animevyuh@trj:~$python --version Python 3.8.5
If the python –version doesn’t work, enter the python3 –version. I recommend you to install the latest version or any version above 3.6+. Python 2 has very few dissimilarities from Python3.
- sudo apt-get python3 (for ubuntu)
- sudo apt-get install python3-pip (for ubuntu)
- dnf install python (for fedora)
- Install Python on Windows
- Install Python on Mac
One strange word, you might have noticed, PIP what is this PIP? PIP(PyPI) is nothing but Python Package Index, this helps you to install new packages which are later used by Python. In simple words, pip is used to install third-party modules. Check out more information here https://pypi.python.org/.
What Are The Prerequisites Required To Start Python?
You need no prerequisites to get started with Python. It’s perfectly fine if Python is your first programming language, you needn’t have knowledge of other programming languages to start Python. Unless you don’t understand English and syntax, you are doing good🙌
IDE Setup To Write Python Programs
Writing Python Programs only on an interactive shell is not a good idea, as a Python interpreter checks each line by line and executes it becomes difficult to use the interactive shell for larger problems. Thus you need to install an IDE or powerful editors to write a Python program. I would recommend you to install PyCharm for writing larger programs. Now coming to text editors you can install VS Code/Sublime/Atom all these editors are very powerful. I could recommend VS Code, even Sublime/Atom is good, it depends from person to person based on how they use it.
It’s time to write the first program in Python. Here are three different methods to execute Python Programs. If you are unable to download Python, Contact Me.
First, Using Interactive Shell
Open your terminal or command prompt and type “python”, in some system “python3”.Now just write your first program, using print() statement.
>>>print(‘This is my first Python Program’) This is my first Python Program>>>print("Anime is the greatest")Anime is the greatest>>>print("I'm getting started") I'm getting started
print() statement is used to display the output which is written inside the parenthesis (). If you noticed the above examples, the first statement is written inside single quotes(‘ ’), whereas in the second statement the display message is written inside double quotes(” “). In python, both single quotes and double quotes are treated the same inside print() statement. But if you used single quotes in the third example it could have thrown an error e.g.
>>>print('I'm getting started') SyntaxError: invalid syntax
SyntaxError: You get this error when you don’t follow the syntax(procedure) of writing a program, in simple words, there are rules for writing Python programs, if you don’t follow those rules you get SyntaxError.
Examples for SyntaxError
print('Monkey D Luffy, Future Pirate King' print("Naruto successfully achieved his dream)
Both the above example give us SyntaxError because in e.g.1 we missed closing bracket )in e.g.2 we missed double quotes “. Correct Syntax print(‘’) or print(” “)e.g. print(“Luffy and Naruto never give up”)
Second, Using Text Editors
Open your text editor and create a new file with extension .py.
print("Now this is written using text-editor, dattebayo")
Save the file and open terminal/cmd. The syntax to run the program: python filename.py$ python first.pyNow this is written using text-editor.
Output: Now this is written using text-editor, dattebayo
Third using PyCharm
print(‘I love watching Anime.’) print('I read Manga everyday')
Now you can run this program directly in PyCharm using run which is located at the top-right of the IDE.
Output: I love watching Anime. I read Manga everyday
How to print Multiple Lines In One Line?
If you notice the output of the above example, the second print statement prints the output in a new line. What if you need to print it in the same line?
print('I love watching Anime.',end=" ") print('I read Manga everyday')
Output: I love watching Anime. I read Manga everyday
Using end=” “, you can print the next line in the same sentence. Note: end=””, provides no whitespace between two statements. But end=” ” provides whitespace, here is another example:
print("Three Anime With Good Comedy",end=":") print("Gintama",end=', ') print("Grand Blue",end=' & ') print("Konosuba.")
Output Three Anime With Good Comedy:Gintama, Grand Blue & Konosuba.
If you provide end=”&”, then the next line will be merged with & symbol.
It sounds weird when someone calls you without calling out your name, this naming act gives rise to a concept known as Variable. Variable Is nothing but assigning names to a value. Now this variable is responsible for creating a memory to its value. Creating a memory is like a box. You store something inside a box, in the same way, a variable is a box and the value is the item inside the box.
>>>name = "Sakata Gintoki" >>>age = 30 >>>weight = 69.5
Here name, age, and weight are variables. And Sakata Gintoki, 30, 69.5 are the values assigned to it. Now here arise a new topic- Why is name been assigned within double quotes and age, weight is assigned directly🙄
Different categories of Data Types:
1. Integer Data Type:
An integer is a numeric value without any fractional part. You can assign integer values without double-quotes. Example for integer data types:
>>>age = 20 >>>episodes = 12 >>>seasons = 2
You now know the age, episodes and seasons are variables, and 20,12, and 2 are values that are integer. How to know if the given value is an integer? There is a method known as type() which checks which data type variable belongs to.
‘int’ signifies that the variable belongs to an Integer type.
2. Float Data Type:
Float is a numeric value with decimal/fractional parts. You can assign float values without double-quotes. Example for float data types:
>>>weight = 72.6 >>>time_per_episode = 24.23 >>>height=5.3
Now I hope you know which is variables and values in the above example. To check if the variable is float, the syntax is already mentioned:
‘float’ signifies that the variable belongs to the Float type.
3. String Data Type:
The string can be a letter or a word or a paragraph or a complete essay. In simple words, anything enclosed within single quotes or double quotes is treated as a string. Example for String data types:
>>>weight = "72.6" >>>age = "21" >>>name = "Itachi Uchiha" >>>female_main = "Jabami Yumeko"
So even if you provide integer and float values inside quotes then it is treated as String. To check if the variable is String:
‘str’ signifies that the variable belongs to the String type.
4. Boolean Data Type:
Boolean only represents values either True or False only. This is a very important data type that will be used in control statements. Example for Boolean data types:
>>>watch_anime=True>>>reads_manga = True>>>study_daily = False
Boolean has only two values either True or False.
>>>to_trick_you="False" #you should notice this small things
To check if variable is Boolean:
type(watch_anime)<class 'bool'>type(study_daily)<class 'bool'>
‘bool’ signifies that the variable belongs to the Boolean type.
Anything enclosed with quotes belongs to the string class. Now that you know: how variables are declared and used, there are certain rules for naming a variable.
Rules For Naming A Variable
Variable should not start with a number
9anime = "Watch anime here" #this is invalid, you get SyntaxError
No special character should be used in variable except underscore(‘_’).
steins;gate = 25 #invalid one_piece = "World’s Best Show/Anime" #valid
In the above example, one variable contains a special character; which is invalid. Whereas the other example contains _ which is accepted.
No whitespace can be used in variable
strongest character = "Can he beat Goku?" #invalid
No space should be used between variables. In the above example, there is a white space between the variable strongest character.
Variable can be any word even if it has no meaning
ehdefrgrbvfvew = 10 #valid
Note: Yes you are allowed to choose any name for a variable but try to choose the variable meaningful so that when someone reads your code, they should understand it just by seeing the variable.
#declare age as 20 age = 20 #sounds good something_i_gave = 20 #sounds weird
Variables are case sensitive
Case-sensitive means two similar words with different caps are considered to be case-sensitive variables.
>>>name = “Edward Elric” >>>Name = “Alphonse Elric” >>>nAme = “Winry”
All the above three variables are the same in the English language but are completely different for Python interpreter.
‘#’ : I hope you did notice this ‘#’ hash symbol in above examples, what was its purpose? Comments are most useful and very much required while writing larger or smaller codes. Comments are not executable lines in the program. What are non executable lines? The statement is non executable means the interpreter ignores the statement and doesn’t run that line.
Interpreter neglects comments but comments give meaning to your code. Sometimes you write a large code after some time you tend to forget it. This happens with every programmer, everyone tends to forget things. Thus its better practice to use comments in your program.
#this doesn’t do anything just like King from One Punch Man. #this will not print anything, but I am Useful
Note: ‘#’ is used to add comment for single line only.
You go to college that means you will be provided with id card or unique code given to you. In same way in Python, every variable as a unique id assigned to it. Here is the examples to check the id of variable.
>>> mc = "Asta" >>> id(mc) 140090471626928 >>> mc = "Deku" >>> id(mc) 140090471627248 >>> mc = "Tanjiro" >>> id(mc) 140090471626224
Notice that eventhrough the variable is same, the returned id value is different all the time.
>>> name = "Yuji" >>> jjk = "Yuji" >>> id(name) 140090471627504 >>> id(jjk) 140090471627504 #the variable is different but it as same value and id
Operators and Expressions
Expression is the collection of Operator and Operands. Here Operands means variable and Operator is mathematical operations such as addition, multiplication, subtraction and many more. You will learn more about operators in coming module.
>>> x=15 >>> y=12 >>> add = x+y >>> subtract = x-y >>> mult = x*y >>> power = x**y >>> divi_quotient = x/y #return value is float >>> quotient_in_int = x//y #return value is int >>> modulus_reminder = x%y >>> print("Add",add) Add 27 >>> print("Subtract",subtract) Subtract 3 >>> print("Multiply",mult) Multiply 180 >>> print("Power/Exponent",power) Power/Exponent 129746337890625 >>> print("Division",divi_quotient) Division 1.25 >>> print("Division in Int",quotient_in_int) Division in Int 1 >>> print("Reminder",modulus_reminder) Reminder 3
There shall be criteria where you have to use multiple operator in one program. Precedence i.e., the order of operations concept for correct format of execution. Order goes like this:
- Parenthesis ()
- Multiplication *, Division / // and Modulus % (from left to right)
- Addition and Subtraction comes next (from left to right)
More Examples On Operators
>>>10 + 54 - 7 57 >>>10 + 5 * 6 #first 5*6 40 >>>5/2 * 10 +5 # ‘/’ and ‘*’ as same order but first come first serve (left to right) 30.0 >>>5/3 1.6667 >>>5//3 #see the difference between ‘/’ and ‘//’ 1 >>> 3**3 27
Still confuse on the order?, then check out the flow:
>>>56//23+5*10-6 51 Here is now 51; 56//2**3+5*10-6 First: Power or exponent: 2**3 = 8 56 // 8 +5*10-6 Second: Division: 56//8 will return integer that is 7 7+5*10-6 Third: Multiply: 5*10 = 50 7+50-6 Fourth: Addition and Subtraction are of same order but from left to right thus 7+50 57-6 = 51. Here is the output.
Concatenation is used to merge two or more String Variables. As in addition, we used the “+” operator to add between two integer variables, in String variable “+” operator is used to merge to a variable.
first_name = "Monkey D" last_name = "Luffy" full_name = first_name+last_name print(full_name) Output: Monkey DLuffy
“+” merges two variables without any spaces in between. In the above example, once the first name is to merge with the last name, there will be no space in between the two merged variables.
player1 = "Hinata" player2 = "Kageyama" player3 = "Tsukishima" #concatenate all three variable into new variable first_years = player1+player2+player3 print(first_years)
#directly concatenate without new variable print(player1+player2+player3)
While using ‘+’ to concatenate it won’t provide whitespace between. So you should manually provide space after the name.
>>>name = "Naruto" >>>age = 19 >>>bio=name+age TypeError: unsupported operand type(s) for +: 'int' and 'str'
It is not possible to concatenate string and integer variables but there are some cases where we do require to concatenate string and variable and at those times type conversion concept comes into the picture.
By the name goes conversion, we are converting something here, and that something is variable. Here is how you can convert from one type of variable to another type.
>>> age = 20 >>> type(age) <class 'int'> >>> age = str(age) >>> type(age) <class 'str'>
Now by using str() you can convert the integer variable to the string variable. You can also convert a string variable into an integer variable only if its value is a digit. By this I mean:
age = "20" #this is string variable age = int(age) type(age)
Initially, age was a string, then it is converted into an integer. This process of conversion goes smoothly. Because the value is an integer.
name = "Killua and Gon" #this is string variable #the value is not digit so this gives an error name = int(age) ValueError: invalid literal for int() with base 10: 'Killua and Gon'
Float to Integer and Vice Versa Conversion
As already discussed Float deals with numeric values with fractional parts. You can convert float to integer and vice versa.
area = "96.75" #float variable print("Before:",area) area = int(96.75) #now int print("After:",area) Output Before: 96.75 After: 96
When you convert float variable to integer variable and print the data the interpreter ignores the fraction part and prints just integer value. Now here is how you convert integer to float.
height = 168 #integer variable height = float(height) print(height) Output: 168.0
When you convert integer variable into float variable there is .0 added to suffix.
Now back to square one how to concatenate between string variable and integer variable. So it’s very simple to concatenate. You can convert int value into a string variable and then concatenate these two string variables.
name = "Yellow Flash" age = 38 #you can now successfully merge a int and string bio = name+str(age) print(bio) Output: Yellow Flash38
The * operator is used for multiplication between two integer or floating-point values. But when the * operator is used between string value and one integer value, it becomes the string replication operator. Example for String Replication.
name = "Zura" #string replication * operator between string and integer value print(name*3) output "ZuraZuraZura"
joi = "Katsura" yorosuza = "Gintoki" print(joi*yorosuza) #gives error Output TypeError: can't multiply sequence by non-int of type 'str'
name = "Takasugi" print(name*5.0) #invalid; Output: TypeError: can't multiply sequence by non-int of type 'float'
In the above e.g., you can see how you can repeat the same string value multiple times. String replication only works between string and integer, you can’t use float variables for string replication. Syntax: string value * integer value.
Apply the knowledge you gained so far. Check out my GitHub repo to try a few assignments.
Can I know what is your name?
Can I know do you watch Anime?
Now, Why am I asking you the questions? Weird right.
There are many situations where you need to ask the user to enter the input, there is a method that carries out this task easily. By using input() you can ask your users to enter or prompt the input. From now on we will use Text Editor or PyCharm to write the programs. An interactive shell is not recommended but you are free to choose.
Syntax for user input input("Message to ask user") #remember input() Return type is String
name = input("Enter your name:") print("Konnichiwa",name) Output: Enter your name:Satoru Gojo Konnichiwa Satoru Gojo
year = input("Enter Death Note released year:") total_episode = input("What is the total number of Death note episodes? ") main_char = input("Enter Main Protagonist: ") print(type(year)) print(type(total_episode)) print(type(main_char)) Output: Enter Death Note released year:2006 What is the total number of Death note episodes? 37 Enter Main Protagonist: Light yagami <class ‘str’> <class ‘str’> <class ‘str’>
Now as mentioned in syntax input() returns string value. Now in above e.g., when a user is prompt to enter year it’s obvious that year is supposed to be integer value but when you use type() to check the year variable it returns class str. We know that we can convert string to integer if the value inside the double quotes is numeric. While asking the user for integer input you can type cast the input, here is how you do it:
num1 = input("Enter a number:") #note this will return string value num2= input("Enter a number:") addition = num1+num2 #since ‘+’ is used between two strings concatenate will occur print("Sum is "+addition) output: Enter a number:5 Enter a number:10 Sum is 510 num1 = int(input("Enter a number:")) #now input returns integer value num2= int(input("Enter a number:")) addition = num1+num2 #simple addition of two numbers print("Sum is "+addition) output: Enter a number:5 Enter a number:10 Sum is 15
This was the first part of learning to code Python through Anime. For part 2 check this article: Learn Python Through Anime Part 2.
In addition, part 2 and 3 consists of ProTips and Hands-on practice. Follow us on Twitter to stay Tuned.
The best way to learn is through practice. Start 30DaysOfPython that will be added to Anime Vyuh GitHub profile. Check that out and Stay Tuned for the next 4 parts.