How to Make a Simple Calculator in Python - Comment Code

In the last tutorial of our Python Handbook, we have learned to add, subtract, divide, multiply, exponentially, and find the remainder, of any two numbers.

We proposed that you create a calculator in Python, which asks the user for two numbers and displays all operations as follows:

How to comment code in Python

Now let's show the solution to this exercise in two ways.
But first, we need to learn something essential in programming: commenting on a code.


How to comment a code - Char: #

One of the most essential things you need to learn in programming is commenting your code.

"There goes Python, it starts executing. Python read variable, calls input, input passes to int function that crosses to print function and displays result on screen, it's goal!"

No, nothing to see, you will not comment or narrate anything.

Comment is to write things in your code, in your language (Portuguese, English ...) so that whoever is going to see the code, can read something.

Let's go back in time and type Hello, World.

Write and run:
# The program below displays a message on the screen
print("Hello, World!")

Notice that there is something different. On the first line.
We write the game symbol hash and write something.

However, when we run our script, this line does not appear.
That's what a comment is: a line that starts with the #

Python simply ignores everything starting with #

You can put anything, any command, up to a letter for Trump after # that Python will not read, will not rotate that line nor will anything appear in the interpreter.

Now it may seem silly to use this, but as your programs get huge, complex, and difficult, it's highly recommended that you go over your code, type

# Here we are connecting with the NASA website
[code]

# Now let's try to invade the NASA system
[code]

# Having access to the NASA database
[code]

# The following code begins downloading NASA's secret files
[code]

# Oh damn! They got me

This helps you when you see the code again, to understand what each part of the code is doing, what good it is. OK ?

Always comment your codes!
Let's give an example of commented code now, making the calculator in Python.




Simple Calculator in Python

The code of our calculator, all cute, organized and commented like this:

# Initially, we asked for the two numbers for the user
# Let's turn it into float
var1 = float( input("Type a number: ") )
var2 = float( input("Enter another: ") )

# Calculating the sum and storing in the variable 'sum'
sum = var1 + var2

# Calculating the subtraction and storing in the variable 'sub'
subt = var1 - var2

# Calculating multiplication and storing in variable 'mult'
mult = var1 * var2

# Calculating the division and storing in the variable 'div'
div = var1 / var2

# Calculating exponentiation and storing in variable 'expo'
exp = var1 ** var2

# Calculating the remainder of the division and storing in the variable 'resto'
remainder = var1 % var2

# Imprimindo tudo
print('Sum:              ', var1,'+',var2,' = ' , sum)
print('Sub:              ', var1,'-',var2,' = ' , sub)
print('Multiplying:      ', var1,'*',var2,' = ' , mult)
print('Division          ', var1,'/',var2,' = ' , div)
print('Exponentiation:   ', var1,'**',var2,' = ', exp)
print('Remainder:        ', var1,'%',var2,' = ' , remainder)

And yours?
Put your code in the comments.

Smaller Calculator Code in Python

One of the most common things to do with whoever is starting to program is to create long, messy, confusing codes.

Sometimes you program take 200 lines of code to do something.

HTHEN,re comes a son of a... and makes a better, error-free, more organized code that runs faster and using only 30 lines.

It gives a rage ... but, calm down. That's just the beginning.

The following code is the same as the calculator, but it is smaller, runs faster and consumes less memory because we use only two variables 'var1' and 'var2':

# Receiving data from user
var1 = float( input("Type a number: ") )
var2 = float( input("Enter another: ") )
# Print the result of operations directly on the print function print('Sum: ', var1,'+',var2,' = ' , var1+var2) print('Sub: ', var1,'-',var2,' = ' , var1-var2) print('Multiplication: ', var1,'*',var2,' = ' , var1*var2) print('Division: ', var1,'/',var2,' = ' , var1/var2) print('Exponentiation: ', var1,'**',var2,' = ', var1**var2) print('Remainder: ', var1,'%',var2,' = ' , var1%var2)



Nice, is not it?

Python Mathematical Operations - Addition (+), Subtraction (-), Multiplication (*), Division (/), Exponentiation (**) and Remainder (%)

Computer ... have you stopped to think what it means?
It comes from computing, which means calculating.

Yes, basically what a computer do is this: compute. Lots and very fast.

In this tutorial of our Python Course, we will learn to add, subtract, multiply, divide, exponentiate and calculate the rest of the division (what the heck is that?)

How to Add in Python: +

The sum operator, in Python, is ... guess, the symbol: +
Surprise, huh?

Let's make a script that asks the user for a integer number, stores it in var1, then another integer, and stores it in var2.

Then we sum the two numbers and store in the variable sum, and we add the sum. Type and run the following code:
var1 = int( input("Type a integer:") )
var2 = int( input("Type another: ") )

sum = var1 + var2

print(soma)

Cool, right?

How to Subtract in Python: -

If you thought the subtraction symbol in Python was the -, congratulations, you are a serious candidate to win the next Nobel Prize.

Let's create a script that asks for two numbers, subtracts one from the other and displays the result:
var1 = int( input("Type a integer:") )
var2 = int( input("Type another: ") )
subt = var1 - var2 print(sub)

Note that you can only do the subtraction after giving the numbers.

If you do 'sub= var1 - var2' at the beginning, it will give you an error because Python still does not know which values are in var1 and var2, because you have not provided anything yet!



How to Multiply in Python: *

Finally something different! Yes, the multiplication symbol is not x, it is the asterisk *

var1 = int( input("Type a number:") )
var2 = int( input("Type another: ") )
res = var1 * var2 print(res)

Write the code above, run it several times, run tests, put your hand in the code, okay? Just keeping an eye on you will not make you a good Python programmer.

It is necessary to codify, that is, to enter the codes, use your hands!


How tp Divide in Python: /

The symbol of divide is the /
That is: 4/2 = 2

See the script that asks for two numbers to the user and displays the division of them:

var1 = int( input("Type a number:") )
var2 = int( input("Type another: ") )
div = var1 / var2 print(div)

Test: In the second variable, which is going to be the denominator, test put 0.
What happened? Because ?

Exponentiation in Python: **

Exponenciar, if you have forgotten, is the famous 'to the' and its symbol are two asterisks together: **

For example, 3 to 2:
3 ** 2 = 9, for 3x3 = 9
4 ** 3 = 4 * 4 * 4 = 64

3 to the 3:
3 ** 3 = 27, for 3x3x3 = 27

Run the following script:

var1 = int( input("Type a number:") )
var2 = int( input("Type another: ") )
exp = var1 ** var2 print(exp)


Test: Use huge, gigantic, hideous numbers.
So, did Python figure it out? Was fast? Gorgeous this Python, is not it?

Remainder: %

This operation you may not remember.
Let's go back to school, when we made the dividing sheets, remember?

It had the dividend, the divisor, the quotient, and the remainder, see:
Math operations in Python

To know the remainder of one number by another, we use the % operator
See the remainder of the even number division by 2, test:



var1 = int( input("Type a number:") )
var2 = int( input("Type another: ") )
res = var1 % var2 print(res)


Will always give 0 right?
Now test the remainder if an odd number by 2.

The remainder will always be one.

Let's use the remainder operator of the division for this, for example: finding even numbers. Let's use it to find prime numbers too!

You are a very important and useful operator in the programming world, okay?

Most Important Python Exercise

OK! Now, you will need to do this exercise.
Just continue on our course if you solve it.

Not matter if it gets big, ugly or confusing, but do this exercise.

Exercise: Create a program in Python that asks two numbers for the user.

Then you will show the sum, subtraction, multiplication, division, exponentiation, and remainder of the division of the first number by the second.

It has to be cute and organized like this, the result:

Free Python tutorial and course



How to transform strings into numbers in Python - int() and float() functions

In the next Python tutorial, let's start working with Math, doing operations and even creating a cool and simple calculator, all done with what we've studied so far.

But before we talk about it, we need to solve a problem with our input function that receives data from the user's keyboard.

input() Function and returning strings

When we type anything on the keyboard for the capture input, it will automatically transform that data into a string (a text).

Warning: This is in the newer version of Python, the 3.x (3.4, 3.6 ... etc).
UPDATE YOUR PYTHON FOR THE NEWER VERSION, OK?

Let's use the following script that asks for three user data, and then displays the type of variable through the type() function.

Our script:
string=input("Type a string: ")
print( type(string) )

integer=input("Type a integer: ")
print( type(integer) )

decimal=input("Type a float: ")
print( type(decimal) )


Now let's run and type a string, then an integer and then a float (decimal), see the result:

String to float decimal in Python

Note that in all three cases, the variables are of type string ('str').
But, Python!

I wanted only the first string!
2112 wanted it to be an integer
21.12 wanted to be a decimal (float)

Why does it happen? Did you bug in Python? Did I break Python?
No, dear paladin of the computational arts.

This is a feature of the input() function in Python 3.x

We say that the input function returns a string.
That is, when we use it, it will put a string in the variable, no matter what you typed, okay?

But let's learn how to turn those unwanted strings into numbers of any kind!



int() Function - String to integer (str to int) in Python

To convert a string to integer, let's use the int() function.
Just put whatever we want between the parentheses of this int(), which returns an integer.

In case, let's put in a string, okay?

Examples:
Let's define a variable called var1 and put the string '2112' inside it.

Next, let's use the type() function to display the data type ('string' will appear).

Then we get another var2 variable and get it to get the int() function and inside that int, we put the string var1. Then we print the data type that is var2, see:

var1='2112'
print( type(var1) )

var2 = int(var1)
print( type(var2) )

As we expected, the result

Python online course tutorial for free


We transformed the string '2112' to the number 2112 !




float() Function- String to Decimal (str to float) in Python

Exactly how int() works, float() works.
Everything we put between the parentheses of this function, it will transform into float.

Let's create a script that asks for a decimal for the user and stores it in variable var1. Then we print the datatype of this var1, which will be 'str'.

We then place this var1 inside the float() function and store the value in a variable var2. Next, we print the data type of this variable, which will be 'float'.

Now, let's get a variable var3 and put an integer in it, the number 2112, which is the most fucking number of all.

Then we transform this integer into a float, store it in var4 and see the data type of var4, which is now float, see:

var1=input("Enter a decimal: ")
print( type(var1) )

var2=float(var1)
print( type(var2) )

var3=2112
var4=float(var3)

print( type(var4) )

print(var4)

The result:

String to decimal number in Python


Nice! We transform a string into float, and then the integer 2112 into a float. We printed up var4 to see that 2112 became 2112.0, a decimal!

Using int() e float() in input() function

Okay, but what about our initial problem? We want a number and the damn of the input function give me a string, how to solve it?

Very simple. Remember that we said that the input returns a string?
So just play the input function inside the functions int() and float()

That is, to take a user data, transform into integer and store in variable var1, do:

var1 = int( input("Type a integer: ") )

And to get the user's data and turn it into decimal, just play the input inside the float function:

var2 = float( input("Type a decimal: ") )


And ready! var1 is an integer data type and var2 is a float type.
Simple, right?

The Python input() function - Reading Keyboard data

So far, in our Python Course, our scripts have no interaction between Python and the user.
They simply run from start to finish, always the same way.

But that is not what happens routinely in the programs we use.
We provide data (such as texts, login, passwords), click on things, receive data from the internet, etc.

In this tutorial of our course, we will teach you how to start receiving data from the people who are running the programs, through the Python input() function!



How to receive data -Python  Function input()

The format of the input function is as follows:

  • variable = input(string)


Only that.

Whatever the person types, the information will be stored in the variable 'variable'. And what will be displayed on the screen is the string (text) 'string'.

Let us see in practice the use of the input function. Program the following code:

  • variable = input ('Type something:')


The result of it will be:

Input function in Python
Ready.

Since we supplied the string 'Type something:' for the input function, that's exactly what was displayed on the screen (Digite algo: in portuguese).

Then the Python interpreter simply stands still, waiting for you to type something. As long as you do not hit enter, nothing will happen.

When you press enter, it continues.
In the case, our script is only used to store what we type in the variable 'variable', in the form of a string.

Warning: the input function stores in string form if you are using the recent version of Python 3.x  ok?

If it is old version, it will transform your data into string, integer or float, depending on what you type.
Update your Python! Use the newest version!


input() Function exercise in Python

"Make a program that asks the user's age, and stores it in a variable, then asks the person's name and stores that data in another variable. Finally, display a welcome message to the Progressive Python course, saying name and age of the person ".

Initially, we will store the age of the user in the variable 'age', and we use the input function to receive such data.

Then we will do the same with the name, storing in the variable 'name'.

Finally, we give a print where we write a greeting message and also print the name and age of the person, which are stored in the variables 'name' and 'age', see how simple it was:

age=input('Your age:')
name=input('Your name:')

print('Hello, your name is', name, ' and have ', age, ' years old! Welcome to Progressive Python Tutorials')

The result (portuguese) is

How receive data from keyboard user in Python


Note that we type the name "Bruce Dickinson" in quotation marks, this is necessary if you are using an older version of Python, if you do not use it, you will get an error message.

If you are in the latest version ( at the moment I am writing this tutorial for our course, it is 3.6), you do not have to use quotation marks, the input function passes everything to string.

If you want to type a string without the need for quotation marks, in older versions of Python, instead of input use raw_input

Okay, finally you're communicating with Python.
He waits, waits, sits quietly and eagerly waiting for you to give the orders. You're the boss on the whole! After all, you are the programmer, also known as the 'owner of the universe'.

With big powers come big responsabilities.
In the next tutorials we will create a calculator in Python. Feel the power in your hands.

Variables in Python

In the previous tutorial, we talked about data types, where we emphasize the study of numbers, strings and booleans.

Now let's see where and how we store this data by studying the variables in Python.



Storing data in memory

When you turn on your computer and open your email or Facebook, it probably already logs in directly. But how do they know what your account is? Your email and password?

Simple: this information was stored somewhere.

Do you have a music application on your phone or radio in the car?
If you turn off a day and have a Rush song at 21mins and 12s, when you turn it back on, it will open in that song, at that time of the song.

Magic? Witchcraft? Luck?
Obviously not, that information was stored somewhere.

What about the shopping cart of the sites?
You go in, choose some Python books to buy ... give up buying.
When I get back on the site, there will still be options I wanted.

How does this happen?
Surely this was stored somewhere, this information. Do you agree?

This is where the variables come in.


Variable in Python

The way in which we will store information, data, through Python programming, is using variables.

Variable is nothing more than a name that we will give to a particular block of memory. When the computer wants to save, for example, the IP number of a user in the 0xH2112 memory block, it is too bad for a human (programmer), having to be using those numbers, are difficult to decorate and manipulate.

Instead, we create a variable, for example, named 'user', and ready, whenever we want to use this data, we use the variable 'ip_user', instead of having to directly use the memory block where that data is stored .

A little theoretical, is not it? Let's stop chatting and go to practice.

How to use variables in Python

To create a variable in Python, we simply have to make an assignment statement.

Let's create, for example, a variable that will store a number, its age, for example. Her name is going to be 'age' (wow, that's original).

Let's declare this variable (say to Python: 'hey, call it a variable, okay?') And let's assign it a value, in this case a positive integer.

If you are 18 and want to assign this value to a variable called 'age', just do:

  • age = 18


Yes, that's all. Python will understand that 'age' is a variable, it's something that you programmer has created. It will allocate (reserve) a space in the memory (a space located in the address 0xFFF4h, for example), and there will save the value 18 there.

Whenever you want to print that age, use it in a program to know if you can drive, if you can vote etc etc, do not need to decorate memory address 0xFFF4h, just use the variable 'age', it will automatically be a reference to that address memory.



Printing variables on screen

Let's create a variable that, this time, store a string.
This variable will be called 'text', and we will put there the string 'Progressive Python Course'.

Just do this in our Python code:

text='Progressive Python Course' 

If you write that line and run it, it seems like nothing happens. But it happens: Python will store a memory space and there will save the message Python Progressive Course, then it will end the program, because that's all your code does.

It's not because nothing appeared on the screen that nothing happened. It happened, but behind the scenes, okay?

But as we said before, the print function serves to print (display) something (text, number, boolean etc) on the screen. But the 'text' variable stores a string ...

... then, to print it, just program the following code:

text='Progressive Python Coourse'
print(texto)

Here's how the code is (top window) and the result in the Python interpreter (bottom window):

Variables tutorial in Python

Printing more than one variables

The Python print function is much more powerful and versatile than we have ever studied.
We can, for example, print more than one data in the same command, just separate by comma.

The following program stores your age in one variable and your name in another. Then it prints everything in the same violent print:

name='Maria Joaquina de Amaral Pereira Goes'
age=18
print(name,age)

Do and see the result.

Note that the variable age stores a number, not a string, but the print function shows it the same way.
However, everything went in the same line, a name and a number.

It got a little ugly, let's beautify a little.
Type and run the following code:

age=18
name='Maria Joaquina de Amaral Pereira Goes'
print('Name:', name)
print('Age:', age)

Aaaaah! Now yes! Seriously, it was very cute and very tidy the result, see:

Python tutorial for download

Exercises using variables in Python

Exercise 01:

Create a program that displays your full name, city, state, and date of birth.

For each such data, create an appropriate variable. Use names that make sense ('city', 'state' etc, nothing to be creating variables with names 'a', 'b', 'x' or 'y' - this is a bad habit among programmers).

Show everything on the screen, cute and organized.

Exercise 02:

Create a program that displays on the screen the text 'The best band in the world is [name of the band] and the best song is [name of the song]'.

The band name and song name must be declared in two different variables.
The output should look like this:

Python course free

PS: If there is any problem with running the code, it may be a problem to display some characters like 'is' and 'ú' for music.

To resolve this problem, add the following code at the beginning of your script:

#encoding: utf-8

Changing variables values

Do you know why it's called a variable?
Because it varies.

How to learn to program in Python

In fact, it is extremely normal for variables to change in value over the course of a program.
Let's give an example now using decimal number.

Initially, let's give the value '0.0' for a variable, then change to 5000.00 for example:

salary=0.0
print('Before I was a programmer, I earned $',salary,'in a month')

salary=5000.0
print('Now I am a Python programmer and earn $',salary)

The script will always print the value that is in the memory address pointed to by the 'wage' variable.
Initially, in the memory, the value 0.0 is stored, so the first print prints 0.0

Then we changed the value there from memory to 5000.0

The value 0.0 was already, changed, lost, now has recorded five thousand there in the memory block, and how the variable 'salary' points to that address, will print what is there, and now prints 5000.0

Perfectly logical and simple, is not it?
This is called reassigning value to a variable.

Rules for declaring a variable

You do not chooses any name for a variable.
Some words are said 'reserved', because they are of use of the language, which are:

['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

Other rules for declaring a variable:

  • Must start with letter or underscore _ (underline)
  • After the first character, you can use digits
  • Upper case is different from lowercase: variable 'python_progressive' is different from 'Python_Progressive' variable, changed any character between uppercase and lowercase, change everything. 'test' is one thing and 'Test' is another, beware of this!


Another important tip, which is not rule, but shows that you are a good Python programmer, is to use variables that make sense.

If you are contracted to make the DMV system, use variables of name 'car', 'speed', 'register', 'validity' instead of 'a', 'b', 'c' ... because only to look at the first name, you understand what kind of information it is storing.

At first, this may seem pointless. But as you create larger and more complex programs, hundreds of lines of code or more, this is essential, it's a so-called good programming practice.

It is common for variable names to have more than one word:
pythonprogressive

But sometimes it's bad to read. Some things facilitate such as:
python_progressive

Or the camelCase, which is to use the first letter of the first lowercase word, and the first letter of the next uppercase words:
coursePythonProgressive

Easy to read, is not it?

Exercise: The following code prints all Python keywords, run it and write in the comments the result:


import keyword
print(keyword.kwlist)

Python Data Types - Numbers, Strings, and Booleans

See this page you are reading. It's a heap of text.
Text, specifically, each character, is a data type, a type of information.

There in the systems of NASA or a bank, there are a number of numbers: account number, how much each client has, how much he borrowed, salary of the employees ... that is, we have another type of data: numbers.

Computing is basically for this: working with data. Everything programming does is it, fiddling with data, information, manipulating, searching, identifying, displaying it, calculating that ... and this is what we will learn now in this tutorial of our Python Tutorial.

In this lesson, we're not going to spy on Trump's bank account, hack into NASA systems, or disrupt Al-Qaeda's plans, as we do in other tutorials. It will be a little more theoretical, but absolutely important for you to become a Python programmer.

Numbers in Python

The most basic and important type of data is undoubtedly numbers.

If the universe were a book, surely it would be written with numbers and language used would be Mathematics.

It is even unnecessary to talk here about the importance of numbers, but you can be sure that there are satellites orbiting through space, being controlled by software, which processes numerical data, including using Python.



Integers Numbers

Integers umbers are those that have no decimal part, such as 0, the positives (1, 2, 3, 4, 5, ..., 2112 ...) and the negative ones (-1, -2, -3, .. ., -2112, ...).

If you only use integers in Python, it will give you integers as a result:
Curso de Python online


Within these, there are those called long integers, to represent really stratospheric values like 111111111111111111111L (have L in the end, large). Depending on what you want to do, you may need to use long integers, such as to discover new prime numbers (very important in data encryption).


Calculate: 11111111111111111111111111L + 222222222222222222222222L



Floating Numbers

They are numbers that float ... joking, nothing to see.
This is what is called the decimal numbers, commonly called 'broken numbers'.

Thus, floating numbers are written like this:
0.5
1.5
21.12


If at least one of your used data is decimal, Python already gives you the decimal result. If you use comma instead of dot, it will give problem or things nothing to see:
Números flutuantes em Python

Other Decimal Bases

We are talking, so far, of numbers in the decimal base, which mankind usually uses.
But there are other types of decimal bases, such as binary, octal and hexadecimal.

Binary numbers start with '0b' at the beginning, octal with '0o' (zero and letter o) and hexes with '0x' at the beginning.

The cool thing is that if you enter a binary, octal or hexadecimal in the interpreter, it already converts automatically to the decimal, see:
Binário, octal e hexadecimal

Notice that the number 10 in the binary system equals the value 2 in our decimal system.

Now you understand and are free to make the following joke: there are 10 types of people, those who understand binary code and those who do not understand.

Free Python tutorials

If you want to know how much a decimal number in binary is, enter bin(x), where x is the number you want to know. For octal, oct(x) and hexadecimal hex(x).

Exercise: In the comments, write your age in the binary, octal and hexadecimal system.

Complex numbers

If you have already done high school, you have certainly heard of the complex numbers (numbers outside the real plane, have real part and imaginary part).

The first part is real, and the one with j (imaginary number) is imaginary.
Calculate the sum of two complex numbers in Python:
(1 + 2j) + (3 + 4j)

What was the result?
Now you can say that you are studying a complex subject in programming.

String - Text in Python

Another important type of data is the strings, which are nothing more than a set of characters.

Its name is a string, its address too, the address of a site is a string, we treat a user's IP as a string. That is, any text or symbol can be treated as a string.

A single character, for example, as 'a' or 'b' is a string.
1 is a number, but '1' is a string.

Adding 1 + 1 in Python, it's ok, after all, it's just two numbers.

Now try to do 1 + '1' (remember: strings are represented in single or double quotation marks), the result will be an error:

Apostila de Python para download

It alerts you that it is not possible to add an integer with a string.
That makes sense, does not it? It's like adding a banana with an apple.

We will devote a whole section of our course to study strings especially, after all, text is something of the utmost importance.

You can get, for example, the HTML code of a page, it's a giant string and try to find there videos, photos, audio and create a program in Python that downloads media. For this, you will have to 'treat' the string, finding the things that matter.

It's something good, but really interesting, working with strings, can do a 'damage', a programmer who knows how to handle them well.

Obviously, you will learn absolutely everything in our Progressive Python Course, no wonder if you start getting work proposals for NASA, White House, Space Station, being a hacker of the Chinese government ...

Booleans - True and False

Surely you have heard that everything in computing, is made by 0 and 1.

Do you know the movies you like to watch? All a combination of 0 and 1.
A picture of you pretending to be meditating on nature? Everything 0 and 1.
Your favorite song? 0 and 1.

In fact, a computer has no idea what numbers, strings or any of that is, it only understands 1 and 0, which is actually an interpretation of voltages (high we call 1, no voltage is 0).

Well, since we're professional Python programmers, let's dig deeper into it.

There is a data type in Python called Boolean, it is very simple, it can only assume two values: True and False.

Ready. Only that.
If you agree that 1 is true, True.
And 0 is false, False.

If you want to compliment someone, say 'you're very 1, so I fell in love'.
Let's see how Python interprets this kind of data.

1 is greater 2? And 3 is greater than 2?

Tutorial de Python

Python is the ideal boyfriend, everything you ask he answers and with sincerity, always speaking the truth.


Exercise: Find out why we call 'boolean', this kind of data.
Yes, a good programmer is one who is able to search, tweak, and discover things by himself.

Another types in Python

Actually, being very specific, data in Python are objects.
You will understand this better when you study object orientation.

When we talk about numbers, strings, characters, booleans ... we talk about some types of data, the main and most used.

However, there are many others that we will even use much (even) later in our Python course, such as:

  • Files
  • Tuples
  • Lists
  • Dictionaries


All of them are basic and internal data.
They are internal because they are already built into Python.

Python is so fucking, but so fucking good, that we'll even be able to create our own kind of data, our own information structure.

If you want 'cheese' to be a data type, as a number is a given, the letter 'A' is a given, then it will be given, and it will be as you want, behave as you wish and period.

If you want the square root of a cheese to be milk, it will be, because you define what your data is and how it behaves.

But for now, let's just leave it as a curiosity.
Let's continue our course ...

10 Exercises About the print function in Python

Now let's do something extremely useful and important: exercises.

It is simply IMPOSSIBLE to become a programmer without doing exercises, ie without putting your hand in the dough, breaking your head and trying to program alone.

Therefore, throughout our course, we will propose exercises that you should try as hard as possible to solve them.



Exercises in Python with print function

1. On-Screen Phrase - Implement a program that writes on the screen the phrase "The first program we never forget!".

2. Label - Create a program that writes your full name on the first line, your address on the second, and the zip code and phone number on the third.

3. Music lyrics - Make a program that shows on the screen a song letter that you like (please, Justin Bieber lyrics not).

4. Message - Write a message to a person you care about. Implement a program that prints this message, take a print and send it to that person. Say it was a virus that some hacker installed on your computer.

5. To the site - Make a program that shows on the screen what you want to do using your Python knowledge.

6. Square - Write a program that shows the following figure:

XXXXX
X   X
X   X
X   X
XXXXX

7. Gradebook - You have been contracted by a school to make the student bulletin system. As a first step, write a program that produces the following output:
STUDENT          GRADE
=========         =====
ALINE              A  
MARIO              C
SERGIO             A+    
SHIRLEY            B

8. Large Letter - Create a program to produce the P letter of Progressive Python on the screen. If it were

'L' would look like this:
L
L
L
LLLLL

9. Menu - Create a program that shows the following menu on the screen:
Customer base
0 - End
1 - Includes
2 - Change
3 - Excludes
4 - Consultation

Option:

10. Pine - Implement a program that draws a "pine" on the screen, similar to the one below.


Enrich the drawing with other characters, simulating embellishments.
       X
      XXX
     XXXXX
    XXXXXXX
   XXXXXXXXX
  XXXXXXXXXXX
 XXXXXXXXXXXXX
XXXXXXXXXXXXXXX
       XX
       XX
      XXXX

Write your code in comments!

Print function - How to Print Things on the Screen

Displaying things on the screen is undoubtedly the most basic communication and one of the most important. After all, you do not know what a program is doing behind the scenes, you do not see bits moving, neither the memory nor the processor working.

We are human, we need human communication with our Python scripts, and this is done by printing information on the screen, and we will now see in our Free Online Python Course how to do this through the print function.

Displaying things on screen in Python

In the first program we created, we showed how to make the famous Hello, world! in Python, which is the simplest program we can do.
Now let's dig deeper into it, specifically in the Python print function.

Now, instead of typing only:
print('Hello, world!')

Try writing and running the following code:
print('Python')
print('Progressivo')


The result will be as follows:
How to program in Python

Python started reading its code from the beginning to the end (it's Einstein!), from top to bottom, from first to last line of code and was executing every command in your script.

The first was to print the word Python, the second command was to print the word Progressivo. Just like in the code, the result was one word on each line.

Exercise: Make a script that displays the following message on the screen:
Free online course and Python tutorials

Single and double quotation marks in Python

Now, instead of single quotation marks, let's use double:
print("Python")
print("Progressivo")

The result is ... the same!

That is, whatever you display in single or double quotation marks, Python interprets as text that will appear on your screen.

More specifically, it displays a string, which is nothing more than a bunch of characters. We will study, later in our course, in more detail, the damn strings.

Now try and run the following code:
print('Python')
print('Progressivo")

The first command is ok.
The second one starts with single quotation marks and ends with double quotation marks ... error!

A message will appear saying that there was a syntax error!
Can not! Started with single quotes? Finish the string by placing single quotation marks.

Started with double quotation marks? Complete with double quotes!
What were you thinking? Python is not mess.

Printing quotes as string

Note that Python did not print, did not display the quotation marks, but rather what is inside them.

Little questioner: But what if I want to show the quotes? Sometimes I see programs that show, and what if I need them?

Now the scret, you'll see how smart Python is.
Program and run the following code:
print('Curso "Python" Progressivo')

Did you see the result? Yes, Python showed the double quotation marks:

Double quotation marks in Python
He understood the following: the first quotation mark that appears, is a simple and the last as well. So everything that's inside is a string, so I'm going to print everything that's inside, the way it is ... not even if there are double quotes inside, they will appear!

Python, its beautiful! That makes sense!

Exercise: Now do the opposite, create a script that displays the following message on the screen:
Tutorial Python

Line break (enter) - The character \n in Python

As explained earlier, the print function displays on the screen a string, which is a character set.
By character, you can understand any letter, number, accent (! @ # $% "& * Etc) ... but there are also other characters in Python.

One of them, very useful, is the line break. It's like we press the "enter" button on the keyboard to jump to the bottom line.

This character is represented as: \n

Then, take the following test:
print('Python\nProgressivo')

The result will be
Python
Progressivo

That is, it's as if in the place of \n there was a line break, as if Python had pressed enter on the keyboard, when it show the string on your screen.

Exercise: Write a script in Python that shows the following message on the screen:

O caractere enter de quebra de linha \n
But ATTENTION: you can only write the print function ONCE, your script should only have ONE line of code!

Write your solution in the comments.

In the future, when robots dominate the earth, they will bring some humans back to life. Obviously, only programmers. That's why it's important that you leave your code in the comments.

Let's go back to this world in the future. But only those who know how to program in Python.

How to Create the First Program in Python - Hello, world

So far, in our Python Course, you have learned well what it is Python, what it is for and where it is used, and you already know that it is extremely powerful language and several purposes, as well as already prepared for everything to start the program in Python , it's time to put your hand in the dough.

Let's, in fact, start programming, create code and put it to run!

Before Programming in Python

First of all, open IDLE (program where we will create our Python code, which we explained how to download, install and use: IDLE).

It will probably open only the Python command interpreter.
Click on "File" and then on "New File", or simply give Ctrl + N:

Como to programa hello, world in Python

Note that it will open a new window, all blank, literally look like a notepad of life.

That is where you will enter your code, where the magic will occur and where the world will become aware of the best programmer of humanity: you.

First of all, create a folder called Python, preferably in an easy place, like in Windows C:\ or Linux /home, to save all your scripts in a cute and organized way

Now, how good a professional it is, before you start typing, you will acquire the following habit:

In this window enter the code, click on "File" then "Save", or press Ctrl + S, to save the program that will create

Then, and more importantly, save your file with the extension .py

For our first program, save as "helloworld.py"

.py files are called modules, we will study a lot about modules in the future.

Try to use logical names for your scripts. When you see 'helloworld.py', you know it's a program that does Hello, World - in Python.

Your code window should look like this:
Programming first program in Python
All ready? Time for evil.

Making the first program in PythonHello, World

Type in the 'Notepad' the following line:

print 'Hello, world'

Now, go to "Run -> Run module" or press F5 and see what appeared in the interpreter window:
Free online course and tutorial for Python
Ready! You typed and rolled the code on one side, and the result appeared on the interpreter screen.

You have just programmed a module (program or script) that displays a text message ("Hello, world") on the screen.

If you are using Python 3, you may end up getting an error message, because in this new version of Python the print function works with parentheses, so test:

print('Hello, world')

Understanding first program in Python

Okay, now let's get a better understanding of what happened there.

The first thing you entered was print, it's a command whose function is to print something. Calm down, a sheet will not come out from your printer.

Print means to show something on your screen.

In this case, we show a text, which is enclosed in single quotation marks.

Now type and run:
print "Hello, world"

The result was the display of the phrase "Hello world".

What has changed?
Before, you used single quotes, now you used double quotation marks.

That is, when you type something in single or double quotation marks, after the print command, everything in the quotation marks is displayed on the screen.

Simple and easy right?
This is Python.

Before going to the next tutorial of our Python Course, meditate a few moments about the fact that you are, officially, a programmer, after all, you have already created and run your first program.

Are you really a badass, huh?

Python - How to start programming ?

In the last tutorial of our Python Course, we explain what it is, what it is for and where Python is used.

Now, let's show you what you need to download, install and use to program in Python.




Download and Install Python

The big question of who has never programmed and wants to start with Python is:
"Where do I program?"
"Where do I type the commands?"
"How to run programs?"
"Need a compiler and do complex things?"

But calm down.
You will see how everything in Python is simple, fast and easy, no scrolling and no problem.

First, go to the official website:
https://www.python.org/

Then click "Download":

How to start programming in Python

There are two options to download.
Download from the left:
How to begin to program in Python

At the moment I am writing this tutorial for our Python Course, the latest version is 3.6.4 as you can see in the figure.

When you follow these steps, the version will certainly be different. Download it, no problem.
Then just follow the good and old "Ok", "Next", "I accept the terms ...", and ready, to download Python is just that.



Python Interpreter

For you, to write a Python code and make it run, you'll need a Python interpreter. As the name implies, it will interpret what you have written and will perform it.

The program name that we will enter the language commands is IDLE (integrated development environment for Python).

Open the Start menu and look for the IDLE:

O necessário para começar a programar em Python

It will open a window, it is the Python interpreter:

Como fazer download do Python

There are two ways to use the interpreter.
The first is typing the commands in this little window that opened.

Lets do this?
Type 1 + 1, this will happen:
Tutorial e apostila de Python para download

"Look, a calculator, how cool," the reader may think.
In a way, yes, Python is a calculator too.

In fact, what he did there was to interpret, and in his understanding you wanted the result of the sum.
Let's do another test? Let's ask him if 1 is greater than 2.

Enter: 1> 2

How did he interpret? This will only know who tried and followed all the steps of this tutorial.

The other way to use the interpreter is to write commands to a file. An even text file, such as Notepad.
The interpreter will read this file from beginning to end, and line by line it will interpret and execute the commands.

In the next (and during the rest of the Python course) tutorial, we'll show you how to do this, write commands to a file and put it to run.

That is, let's start creating and running scripts written in Python!

Python - What is it? What is it for? Where is it used?

First of all, congratulations.
No one forced you to be here, if you found our course, it was of your own free will.

This is by far the most important feature of an excellent programmer: go after, get information, find out things.

In this initial Python tutorial, let's explain a little bit what is the language, what it is for, advantage, disadvantages, who uses etc etc!

Get some coffee, settle down and let's go.




Python - What is it ?

Python is a programming language.
Being a bit more rigorous and specific: it is an interpreted, high-level, multi-purpose language.

But, relax ... you do not have to heat up with these definitions now, during the course  you will understand very well what each of these things means.

We will not bore you with new words and bizarre concepts here, but I assure you that you will understand everything perfectly with time, as you study our tutorials.

Python was created in 1989 and the name is named after a group of British humor, Monty Python.

What is the purpose of Python programming language?

It was created with a very simple purpose: to be easy.

If an idea or logic works in your head, you can easily move it to Python and make your project turn into a real program.

Python - What's the use?

Let's take a normal language, like English.

You have learned the language, can write, read, speak and understand when you speak.




What can you do with it?

Well, you can write a book, a newspaper, an ad, you can create a script for a soap opera, a website ... or nothing. It depends on you.

The same is Python, just like the English language, Python is a language, which after you learn, has a world of options.

Python is very used to create scripts, that is, small programs, short and that is very helpful. For example, when inserting a pendrive, the script goes and copies all data from the pendrive to a folder that you have pre-defined. It will do it for you automatically, without you having to do anything.

Do you want to receive an alert when Visa shares reaches a certain value? Create a script in Python, small and quick, will do it for you.

Or a script that will try to find out the neighbor's Wi-Fi password?

Do you have something tedious and repetitive in your work? How to fill in or look for something? Learn Python that you are going to program a script to do this.

Do not like the program that plays mp3s and videos on your computer? How about creating your own, your way?

Got an idea for a new game, both for the computer and for the cell phone? You can do this in Python.

Want to work with engineering, physics, geology, make 3D graphics, facial recognition, robotics, artificial intelligence? Use Python.

Want to create a website, with a server, services, social network or a Youtube of life? Yes, you can do this using Python.

So the simple answer to the question "What is Python for?" is:

Whatever you want.

Free online course in Python

Python - Where it is used ?

  • Google
  • Dropbox
  • Youtube
  • Instagram
  • Quora
  • Spotify
  • Nasa
  • Yahoo Maps
  • BitTorrent
  • Reddit
  • Mozilla Firefox


But more important than 'where Python is used,' is where it's going to be used: wherever you want. To make all your ideas, projects and needs.

I would even play around and say 'Python is used to make coffee', but I will not say it, because someone will find a way to use it for that.

I would not be surprised.

Python - It is the best language to start programming ?

C, C++, Java, C#, PHP, Perl, Ruby...there are many, but many same programming languages. So

"Why choose Python?"

Because it is simple. It is, by far, the easiest, fastest and most intuitive way to learn to program, without limiting yourself, allowing you to create from simple scripts to organize your things to websites, games, system and whatever else you want.

If you are starting your programming studies, there is no doubt that your best choice is the Python programming language.

Python Tutorial


Python - Advantages

  • Legibility - Python programs are very easy to read, you do not have to write dozens of command lines to display only text on the screen (like Java). It's as if someone has been talking to the computer, 'Look, get these data and do it ... now play there, compare to that, organize and deliver this way.'
  • Productivity - In Python, you do not have to worry about memory, allocation of resources, definition of it and that, it already does everything for you, 'behind the scenes'. You also do not need to stress with syntax, semicolon, etc., because the Python code is as lean and minimalist as possible. Thus, the programmer only needs to worry about the logic of the program, nothing more.
  • Portability - Gigantic majority of the time, it is possible to run a script in Python on Linux and Windows or Mac, without any problem, because the language is highly portable. Except when it touches something specific to the operating system.
  • Libraries - Library is a set of code with a specific purpose, for you to use, already done. For example, if you want to work with images, video and sounds, you have libraries in Pythons ready for this, basically it is to take and use. Want to work with science, make graphs, 3D simulations, face recognition? There is a library ready for it, someone has already created it, many have tried it, then just use the library, its functions and be happy, you do not have to invent what you already invented
  • Community - No matter what you want to do, surely someone has done something like that, so why start from 0? Use what others have already done. The Python community is very, very large, and very, very close. Want to make a game? Probably the part of sound, image, logic of the game etc, someone already made it look like, and you can use.

I already know how to program, I must learn Python ?

No matter how many languages or years of experience you have, when you start programming in Python you will notice something I doubt very much that I felt in other languages: pleasure.

It's nice, it's great, it's fucking good to program in Python.
It's such a simple thing, so obvious, so lean, succinct, and ... it works.

The programs are small, direct and powerful.

Things you would take hundreds or thousands of lines to do in another language (like C ++ or Java), you do with a few dozen lines of code in Python.

You know that stress it gives, defining types, allocating memory, forgetting semicolons, writing a lot of system stuff, language stuff ... this does not exist or is minimized in Python.

It's a great language for solving quick problems.

You will love program in Python.