Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,150,184 members, 7,807,613 topics. Date: Wednesday, 24 April 2024 at 04:10 PM

Learn Python- Introduction To Programming - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Learn Python- Introduction To Programming (9484 Views)

My Journey To Programming / Are You New To Programming? Want To Learn But Do Not Know How? Come In! (2) (3) (4)

(1) (2) (3) (Reply) (Go Down)

Learn Python- Introduction To Programming by stealthtiger(m): 8:45am On May 03, 2017
Hi to everyone who opens this thread.
I'm Emmanuel Olatunde Bashorun and I'm 19 years also an undergraduate of the Univerisity of Lagos, and I love coding.
I'm so glad you're here and I'm assuming you're here to get a basic understanding about Python.

For those asking what language should I learn first let me give it to you bluntly and authoritatively learn Python if you want your life to be easier as you brave through the jungle of coding. I say Python because that's the best way to learn programming
Thank me later wink

What's Python;
Python is a high level language created by Guido Von Rossum in the late 1980's.
It has an efficient high level data structure and a simple but effective approach to object oriented programming. Python's elegant syntax and dynamic typing together with its interpreter makes it an ideal language for scripting and rapid application development in many areas and on most platforms.

Python is used in big multi organizations for software development and data management, Artificial Intelligence(on which lies my intrest). Its popular in companies and gorvernment organizations like CIA, disney, Google, Yahoo, Instagram, NASA, CERN etc.

Why learn programming: Programming is a skill which would determine your employability in the future in whatever field you're in. This is due to the increasing complexity of machines that'd be built and task's that needs to be solved. Let's say a sociologist is doing a Social computing test on Facebook and needs to know the most used words in a series of posts. Let's say 1million posts. It'd be so difficult but not impossible for the Sociologist to carry out that manually. It'd take a lifetime to get the required info from that task.
So if the person had a basic idea of programming say Python, within a couple of minutes the Sociologist would have written a program that solved that task elegantly.
In essence, you don't have to be a computer scientist to learn programming. After all the purpose of this tutorial is not to make you an accomplished Python developer but give you the required knowledge in getting started with python and doing some really incredible stuffs. At least it'd be a launch pad to lift your self into levels that will make you an accomplished Python developer.

The version of Python that would be used in this tutorial is version 3.4.5.
You can download and install Python on your PC as www.python.org.
CPython is the flavor of Python we'd be coding with.

Interpreter: Computers don't understand the normal language we speak so we have to communicate to them in a way they understand which is zero and ones called machine language which is represented by the switching on and off of the electrical circuits in the computer's memory. But it's difficult to write a string of zeros and ones telling a machine to get data from a user, process it and send it to the server which then gives any one who requests for it. Only a few people can do that now.
So how do we go round this problem. A high-level language is needed of which we understand .
High level languages are good because they require a shorter amount of time to write a program, they're portable, meaning they can run on different computers without modifications unlike machine language written on an Intel x84 based PC which has to be rewritten to run on an Intel x64 based PC.

Two programs process high level languages into machine language. 1. Interpreter 2. Compiler
The interpreter reads a high level language and executes it. It processes a program little at a time. Alternatively reads the code line by line and performing computations.

The compiler reads the whole program and translate everything before it starts running. In context the high-level program code is called SOURCE CODE and the translated code is called OBJECT OR EXECUTABLE CODE.

What is a program: [/b]A program is a series of instructions that tells a computer how to perform a computation.

[b]Tutorial Outline:

1. Variables, expressions and statements
2. Numerical Operations
3. Conditional statements
4. Functions
5. Loops
6. Strings
7. Dictionaries
8. Tuples
9. Files
10. Exception handling


PLEASE AND PLEASE NOTHING SHOULD BE POSTED ON THIS THREAD THAT IS OUT OF CONTEXT OF IT'S CONTENT AND THAT HAS THE ABILITY TO DERAIL THIS THREAD OF IT'S PURPOSE OTHERWISE A BAN WOULD BE GIVEN TO SUCH INDIVIDUAL.

Contextual and related contributions are welcome.

I'd be pleased if my errors can be pointed out during the cause of this tutorial since no one is perfect.

Every example that'd be given here has been tested. But self testing the examples is highly encouraged to see if it truly works and also to increase the rate of learning.

Before we get started let me leave you with one of my favorite quotes 'every skill you acquire doubles your odd of success' Scot Adams.

So at least we have a basic idea of what python is. So it's time to start getting our hands dirty in code.

1. Variables, Expressions and Statements
Let's hink of variables as containers. They hold values.
Variables in python are capable of holding different datatypes. Data types are types of data.
In python there are different data types such as int(integers=>they hold decimal numbers), float(floats=> numbers that contain decimal parts eg 8.76), str'(=> they are characters made up of a string of text eg 'good', 'Hello') there are other datatypes​ but we'd talk about them later

As I said earlier on that variables hold values.
Just like a jug holding some water or juice. Water andjuice are different types of liquid.
You don't have to tell the jug what substance your filling it with. It just holds it for you.

Same way with python. Python is an untyped language meaning you don'thave to specify to Python what type of value you're storing in the variable.

Eg.
>>> python = 'language'
>>>print(python)
>>>language
From the above example you can see that I didn't have to tell python what type of variable language is. Python automatically new that it's a string.

Check this out to confirm my statement above
>>>type('language')
>>>('type str')
So Python's so smart that it knows 'language' is a string. This ability is due to the fact that Python has an in-built function called type[\b]

In programming context storing a value in a variable is called [b]assigning a value to a variable
. So we assigned language to python.

Naming variables
In Python a variable name can not start with a number. That's an illegal variable name.
A variable name can contain an underscore, lower case, upper case.
You can't use a key word as a variable name. There are about 31 keywords in python (reserved words)
I strongly advise you to start your variable​ with a small letter.


>>>7_wonders= 'pyramid of Egypt'
SyntaxError: invalid syntax

>>> my_name = 'Bashorun'
>>>

>>> print = 'print is a keyword'
>>> SyntaxError: invalid syntax


Operator's:
These are symbols used to perform numerical operations like addition,subtraction, multiplication, division.

Expressions:
An expression is a combination of values, symbols and variables, operator's
16+2, 18-9 are expressions.

Statements: A statement is a unit of code that a python interpreter can execute.
Eg print statement and assignment statement.
Statements do not contain values while expressions do.

In Python there are different ways in which you can write your code. Either in the interactive mode or script mode.
Interactive: You write directly in the interpreter thereby make the interpreter execute your code line by line.

>>> pizza = 2.0
>>>people = 8.0
>>>shared_pizza = pizza/people
>>>print(shared_pizza)
>>>0.25

So you can see that Python keeps track of every line in the interactive mode

Script: in script mode each computation performed on a line doesn't show but it's actually calculated but doesn't display it's self until you tell Python to.
The final answer would be displayed after running the program written in the editor.
This is unlike the interactive mode where a result would be displayed for every computation performed on a line.
A text-editor is usually used in script mode, and Python comes with that editor which also has a debugger.

pizza = 2
shared = pizza * 8

After you run the code
16 would be printed on the IDLE interpreter.

Order of Operations:
PEMDAS
P: Parentheses
E: Exponentiation
M: Multiplication
D: Division
A: Addition
S: Subtraction
The first Operation takes precedence over the succeeding operation in an expression .

String operation: There are ways to manipulate string's both legal and illegal.
'school'/2 is an illegal operation. You can't divide a string

'school' * 2 is a valid operation which prints=> school school

There's a technique in programming called CONCATENATION. This means you can add two strings together to give the sum of the two strings
'spam' + 'spam' = spamspam

NB=> Anything​ enclosed in a single quote or double quote in python is called a string.

Eg. '32' is a string.
Since it's in a single quote python doesn't regard it as an integer

Comments
As you write complex programs, you'd need to know what a certain function does or what a certain variable stores just to remember. You'd be surprised 6 months later that you wouldn't be able to recognize your own code.
So this is where the comments shines.
A comment is created by using a # sign
#my_name is a comment which stores Bashorun
my_names = 'Bashorun'

When you run the following code, the python interpreter ignores the line that starts with a #

7 Likes 2 Shares

Re: Learn Python- Introduction To Programming by promisedeco(m): 2:31pm On May 03, 2017
really interesting. count me as your number 1 student
Re: Learn Python- Introduction To Programming by stealthtiger(m): 2:43pm On May 03, 2017
promisedeco:
really interesting. count me as your number 1 student
Cool to hear from you. I really thought people were not interested. But you commenting gives me more morale to continue.
I hope my tutorials would be of great help to you
Re: Learn Python- Introduction To Programming by stealthtiger(m): 3:13pm On May 03, 2017
2. Numerical Operations
In Python there are different Numerical Operations and we're going to talk about them.

1. Simple operations:

>>> 1 + 2 + 8
11
>>> 5+4-3
6
>>> 2*(3+4)
14
>>> 10.0/2
5.0

Dividing a number by zero in Python produces an error

>>> 10/0
Traceback(most recent call last):
ZeroDivisionError: division by zero


More on operations

Exponentiation:
To raise a number to a power supply denoted by x**2 in Python.

>>> 2**2
4
>>> 8-(2**2 + 1)
3


Quotient and remainder:
In Python quotient and remainder are denoted using the floor and modulo sign respectively (// and %)


>>> 13//5
3
>>> 7//5
1

From the above example it can be inferred that the quotient is the number of times a divisor can divide a number.

>>> 8%6
2
>>> 100%10
0

So the remainder is remaining value you get after dividing a number

I hope we beginning to get a hang of python. Please feel free to ask questions.

So let's talk about inputs and outputs in Python.
To get data from your user would require you to provide a means to get data from the user.
So you do this using input.


>>>my_name = input('Enter your name: ')
Enter name:

So the input statement tells Python to get data from the user.

And don't forget. Input statement accepts only string values. Buts there's a way to solve that by doin this


>>>my_age = int(input('Enter age: '))
Enter age:

Here, we told Python to only accept an integer.
So if the user inputs a string, python would throw an error saying it can only accept an integer.

Output
If you can scroll upwards you'd notice that we've been using a function called PRINT.
This print is used to output a statement in Python

We should also note that's it's possible to convert types in Python.


>>> my_age = '19'
>>> you_age = '17'
>>> total = my_age + your_age
>>> print(total)
1917

int('3')+ int('4')
7
float('6')/float('6')
1.0

Python has the capability of converting an integer into a string by just using a single or double quote.
'19' is no longer 19 as a number, instead it's now a string that's why '19'+'17' is 1919.

NB: it's better to use a double quote when declaring q string. So we'd be using a double quote henceforth when we are dealing with strings.

We can still convert that string to an integer by using an int function.

The same thing applies to float.

NB: not everything can be taught. So please try out things yourself because that's the best way to learn .
Keep on experimenting and you'd see that they're lots of ways to do task even more simple and elegant ways that'd make a fellow programmer say 'wow'

1 Like

Re: Learn Python- Introduction To Programming by stealthtiger(m): 9:18am On May 04, 2017
3. Conditional statements
First of all let's talk about Boolean and Comparisons.
Boolean statements are basically Yes or No statements. True or False


>>> 5 ==5
True
>>> 6 == 7
False

So it's either true or false.
== is a relational operator. We're going talk about that in a bit.

>>> (type True)
<type 'bool'>


There are different relational operator's and we've seen one which is ==. There rest are

x > 5 => x is greater than 5
x < 5 => x is less than 5
x != 5 => x is not equal to 5
x >= 5 => x is greater than or equal to 5
x <= 5 => x is less than or equal to 5
x == 5 => x is equal to 5


BEWARE: x == 5 is different from x = 5.
The former is a relational operator and the latter is an assignment operator. It assigns 5 to x.

5==5
The two values on the left are right are called operands. L-operand and r-operand.

LOGICAL OPERATORS:
There are 3 types of logical operators in Python. And, Or, Not.

AND

>>> 7==7 and 4>1
True
>>> 6 < 1 and 4 <2
False

In the and operator the two sides should be true for the statement to be True. If one is true and the other is false as in the second example it returns False.

OR
n%2 == 0 or n%3 == 0 is true if either of the statements is true. So if one is true and the other is false. It stills returns True as long as one is true.

NOT
This basically negates a Boolean statement. Eg

>>> not 1 == 1
False
>>> not 7!=8
False
>>> not 8 > 100
True

So not takes a true statement and makes it false, a false statement and makes it True.

CONDITIONALS:
One capability computers have which is very useful us their ability to make decisions after giving them a set of instructions.

In Python you can also arm your program with the ammo of decision making capabilities.
So there might be a condition that need to to occur before the computer does something.

For example: A lecturer might tell a class rep that until the class has may be say 70% attendance before I come to lecture. So the lecturer has given a condition.
Until that condition is met before the lecturer comes to class.
I know no one wants that kind of lecturer​ to take that crazy 4 units course.

So let's start with the IF statement
Out of all conditional statements the IF execution is the simplest.


>>> if x>5:
print ('yes')

This means that the code in the indented block should display 'yes' if x>5.

We can have an alternative form of execution to the if called ELSE

>>>if x % 2 == 0:
print('even number')
else:
print ('odd number')

Python understands that if x modulo 2 isn't zero then it's odd. So it leaves the if statement and executes the indented code at the else statement.
NB: X%2 is a way of checking if a number is even or odd. Since all even numbers are divisible by 2 without a remainder.

1 Like

Re: Learn Python- Introduction To Programming by promisedeco(m): 4:54pm On May 04, 2017
stealthtiger:

Cool to hear from you. I really thought people were not interested. But you commenting gives me more morale to continue.
I hope my tutorials would be of great help to you
am enjoying every bit of it.
Re: Learn Python- Introduction To Programming by promisedeco(m): 5:02pm On May 04, 2017
please , there are 3 things I didn't understand...

1). input statement- what confused me is ' To get data from your user would require you to provide a means to get data from the user.' what's the user here, is it the normal computer user profile?

2). I have once hear of 'Float' but couldn't grasp the concept. since you used it in one of your examples can you explain what this 'Float' means

3). in the OR example what does "%" mean?

1 Like

Re: Learn Python- Introduction To Programming by 144(m): 8:41pm On May 04, 2017
following with knee interest
Re: Learn Python- Introduction To Programming by ANTONINEUTRON(m): 9:14pm On May 04, 2017
if u can complete diz tutorial,

it'll be really helpful

1 Like

Re: Learn Python- Introduction To Programming by stealthtiger(m): 11:00pm On May 04, 2017
promisedeco:
please , there are 3 things I didn't understand...

1). input statement- what confused me is ' To get data from your user would require you to provide a means to get data from the user.' what's the user here, is it the normal computer user profile?

2). I have once hear of 'Float' but couldn't grasp the concept. since you used it in one of your examples can you explain what this 'Float' means

3). in the OR example what does "%" mean?
1. The user here is the person making use of your program. Let's say you need the name person making use of your program to output Hello + the persons name.
name = input('Enter your name: ')
print ("Hello", name)

When you run this code it asks for your name. Which is the person using the code

Enter name: Satya Nadella
Hello Satya Nadella.

Remember: inputs normally accept string characters. But they can be tweaked to accept float and integers.

age = int(input("Enter age: "wink
So if you enter an integer Python doesn't throw an error because you told the input function to accept an integer.

2. Floats are numbers that have non whole numbers attached to them . They're non integers ie they're are not whole numbers because they contain decimal points in them.
Eg 0.5, 0.67, 43.78 are floats

3. % means modulo. The modulo works on integers and yields the remainder when the first operands s divided by the second.
6%4 would yield 2. Because 2 is the remainder

The or means if either one of the conditions is true then the statement is True.

7<5 or 5==1 this statement is true because the first condition is true irrespective of the fact that the second is false.
As long as on condition is True either first or second then the whole statement is True.
Re: Learn Python- Introduction To Programming by 4kings: 10:17am On May 05, 2017
Following...
Re: Learn Python- Introduction To Programming by mickybabs: 11:24am On May 05, 2017
God bless you sir. i'm really grabbing alot. following!

1 Like

Re: Learn Python- Introduction To Programming by ANTONINEUTRON(m): 10:40pm On May 05, 2017
@op U Can Use Ideone.com For Writing The Code And Posting The Link Here

*suggestion*

2 Likes

Re: Learn Python- Introduction To Programming by 4kings: 10:58pm On May 05, 2017
Seun can you disable the emoticons code when inside a code tag?

1 Like

Re: Learn Python- Introduction To Programming by stealthtiger(m): 6:45pm On May 06, 2017
ANTONINEUTRON:
@op U Can Use Ideone.com For Writing The Code
And Posting The Link Here


*suggestion*
Thanks
Re: Learn Python- Introduction To Programming by Luckygurl(f): 10:53am On May 07, 2017
Somehow I've shyed away from developing my coding skills but it's right here in front of me and I can't avoid it much longer.

Brb!!
This could serve as a motivation smiley

3 Likes

Re: Learn Python- Introduction To Programming by 4kings: 11:42am On May 07, 2017
stealthtiger please continue na...

Meanwhile Seun, you've not answered me oo: can you disable the emoticons code when inside a code tag?

1 Like

Re: Learn Python- Introduction To Programming by stealthtiger(m): 2:25pm On May 07, 2017
4kings:
stealthtiger please continue na...

Meanwhile Seun, you've not answered me oo: can you disable the emoticons code when inside a code tag?
I'd continue the tutorial in no time.
Please forgive
Re: Learn Python- Introduction To Programming by stealthtiger(m): 5:26pm On May 07, 2017
CHAINED CONDITIONALS:
Sometimes you might have more than a possibility and we now need more branches.

For example:
We'd write a code that prints the age of students in a class of 4, when we input their first name.
If there's no such name the program NB prints out that there's no one with such name in the class.

The names are Bill, Zuck, Elon, Emma

NB: this code would be written in script mode and then interpreted by the Python IDLE. You can directly write it in the IDLE.


name = input('Enter name: ')
if name = 'Bill':
print('61')
elif name = 'Zuck':
print('32')
elif name = 'Elon':
print = ('45')
elif name = 'Emma':
print = ('19')
else:
('No such name')

When we run this code, Python interpreter tells us to enter a name. If we enter Bill the interpreter spits out 61. If we enter any other name that's part of the class, the interpreter spits the corresponding age.

So here, we're testing for more than one instance. Not just BILL, but for the remaining students.

And if the name we enter isn't part of the class, then the indented code in the else statement would be executed.

ELIF is the same as else if just like in Visual Basic programming language. Se was removed and concatenated with if.

Obviously I'm the youngest in that class. grin
A business class or something cool
Re: Learn Python- Introduction To Programming by stealthtiger(m): 5:47pm On May 07, 2017
4. FUNCTIONS
Code reuse: A word that's common among programmers. What comes to your mind when you here about code reuse is Functions.
Just imagine you're writing a complex piece of program of about 4000lines. This is large to an extent at least to your level of programming.

Debugging this kind of program even among Senior developers can be a night mare.

But breaking this program into separate parts by encapsulating them in a function would make your life a whole lot easier.

So if the program does numerous things, like updating a server. You can write a code that does that an ld encapsulate it in a function. By the time you've written about 10 functions that makes the program do what you want it to do, then you can start wiring the functions together.
So it makes your life easier.

Back to code reuse. Imagine you're writing another program that computes the payroll of a company and sends it's to the employees mail.

If you've written a program before that computes the payroll of employees in another company and does something else to it. You can just take the function that computes the payroll and use it in your new programming job.
Viola!! You don't have to write any code that does it again because you've encapsulated that capability in a function in another program.
So using functions encourages code reuse

Let's do something.
To declare a function in Python we make use of the def keyword.

def pay_roll():

This kind of function has a zero argument.

Functions and Arguments:
We've seen variables above. But you can also have a variable in between the parentheses of the function
Eg

[color=#990000][
def pay_roll(x):
/color]
X acts as variable
Re: Learn Python- Introduction To Programming by omoikea(m): 11:18pm On May 07, 2017
nice job....
i don't really have time, would have done something like this long time ago

but i am here to support you

1 Like

Re: Learn Python- Introduction To Programming by Nobody: 11:55pm On May 07, 2017
following, learning JavaScript... will learn this later
Re: Learn Python- Introduction To Programming by Nobody: 2:42pm On May 08, 2017
which of the source code can i download is it 3. or 2. and which will i download from anyone under the two.
Re: Learn Python- Introduction To Programming by phililp(m): 9:08pm On May 08, 2017
please OP or anyone who can help me.... am tryna get this code into ma head.. but cant

doo = [i**3 for i in range(5)]

print(doo)

and it gave :
[0, 1, 8, 27, 64]

please help me understand it...what happens when u give a char a power... i only know about numbers and powers; like 2**3 == 8
but this one been turning ma head around

pls ansa ASAP
Re: Learn Python- Introduction To Programming by phililp(m): 9:16pm On May 08, 2017
phililp:
please OP or anyone who can help me.... am tryna get this code into ma head.. but cant

doo = [i**3 for i in range(5)]

print(doo)

and it gave :
[0, 1, 8, 27, 64]

please help me understand it...what happens when u give a char a power... i only know about numbers and powers; like 2**3 == 8
but this one been turning ma head around

pls ansa ASAP

lol ... i got it hahah.... programming can be so funny.... immediately i left the forum i re-reasoned and got it...

i think it means this: since it said that [quote]for i in range(5)[/quotel] i.e for every number in the range of 5; let the number be raised to power 3...

my bad...
Re: Learn Python- Introduction To Programming by Nobody: 12:10am On May 09, 2017
opaniyi12:
which of the source code can i download is it 3. or 2. and which will i download from anyone under the two.
go for 3.x, the latest is 3.6.1.
Am learning mine cos I need django.

1 Like

Re: Learn Python- Introduction To Programming by stealthtiger(m): 10:55am On May 09, 2017
CONTINUATION OF FUNCTIONS.
The x is an argument which is used as a variable.


def product (x, y)
print(x*y)

product(8, 3)


By the time you run this program, 24 would be printed on screen.
Let me explain how it works:

firstly, we defined the function using the def keyword. We named the function as product.

The function contains to Arguments that would be assigned values.

The second line multiplies the 2 arguments and prints it.

But for it to get printed we have to call the function.
Also we have to assign the values to the variables in the function when calling it. This was done on the 4th line.

You can also call another function within a function
Eg.


def states():
print('Lagos')
print('Ogun')
def states_again():
states()
states()

states_again()

Lagos
Ogun
Lagos
Ogun

So we defined a function called statesand told it to do something. Which is to print Lagos and Ogun.
We also defined another function called states_again containing the first function twice.

So when we called the second function, Python immediately read what was in the second function and discovered it's also a function. Python looks for where that function was defined and read the indented code. Which it to print it twice.

This is called flow of execution.
You don't have to read a code in a top-down manner. You might get confused. A part at the top might link to another part at the bottom and another part somewhere making it difficult to understand.

What you then do is to follow the flow of execution. How one parts calls another. Find the coherence in the code. Immerse yourself and you'd see how it moves.

MATH FUNCTIONS
There's a module in Python called math. This module object provides us with mathematical functions.

You have to import the module before it can be used.

>>> import math

This imports the module object called math.
To make use of the module you have to specify the module followed by a dot and by the function you want to make use of. This is called the dot notation Eg let's find the square root of 16

>>> import math
>>>math.sqrt(16)
4

We import the module first, then a dot followed by the function and our value as argument in a parentheses.
So these functions we've seen are in-built functions. You don't have to write a code to fine the sqrt of a number or logarithm of a number. You can just use their functions on the fly.


RETURN VALUES: in Python you can also return values. Any code after the return statement​ is called dead code, because it never executes.
A return statement can't be used outside a function.


def product (x, y):
if x*y >=2:
print ('product of x, y is greater than 2')
return x
else:
return y

print(product (5, 4))

Product of x, y is greater than 2
5

We told Python that if the product of x,y is greater than 2 it should print the above and return x to the product, else it should do the contrary.
Re: Learn Python- Introduction To Programming by uzoexcel(m): 12:20pm On May 09, 2017
Gd job stealthtiger

stealthtiger:
CONTINUATION OF FUNCTIONS.
The x is an argument which is used as a variable.


def product (x, y)
print(x*y)

product(8, 3)


By the time you run this program, 24 would be printed on screen.
Let me explain how it works:

firstly, we defined the function using the def keyword. We named the function as product.

The function contains to Arguments that would be assigned values.

The second line multiplies the 2 arguments and prints it.

But for it to get printed we have to call the function.
Also we have to assign the values to the variables in the function when calling it. This was done on the 4th line.

You can also call another function within a function
Eg.


def states():
print('Lagos')
print('Ogun')
def states_again():
states()
states()

states_again()

Lagos
Ogun
Lagos
Ogun

So we defined a function called statesand told it to do something. Which is to print Lagos and Ogun.
We also defined another function called states_again containing the first function twice.

So when we called the second function, Python immediately read what was in the second function and discovered it's also a function. Python looks for where that function was defined and read the indented code. Which it to print it twice.

This is called flow of execution.
You don't have to read a code in a top-down manner. You might get confused. A part at the top might link to another part at the bottom and another part somewhere making it difficult to understand.

What you then do is to follow the flow of execution. How one parts calls another. Find the coherence in the code. Immerse yourself and you'd see how it moves.

MATH FUNCTIONS
There's a module in Python called math. This module object provides us with mathematical functions.

You have to import the module before it can be used.

>>> import math

This imports the module object called math.
To make use of the module you have to specify the module followed by a dot and by the function you want to make use of. This is called the dot notation Eg let's find the square root of 16

>>> import math
>>>math.sqrt(16)
4

We import the module first, then a dot followed by the function and our value as argument in a parentheses.
So these functions we've seen are in-built functions. You don't have to write a code to fine the sqrt of a number or logarithm of a number. You can just use their functions on fly.


RETURN VALUES: in Python you can also return values. Any code after the return statement​ is called decade code, because it never executes.
A return statement can't be used outside a function.


def product (x, y):
if x*y >=2:
print ('product of x, y is greater than 2')
return x
else:
return y

print(product (5, 4))

Product of x, y is greater than 2
5

We told Python that if the product of x,y is greater than 2 it should print the above and return x to the product, else it should do the contrary.
Re: Learn Python- Introduction To Programming by Nobody: 1:22pm On May 11, 2017
i'm following.. Never
knew python is so easy to understand

1 Like

Re: Learn Python- Introduction To Programming by phililp(m): 11:34pm On May 11, 2017
pls someone help... whats the difference between mutable and immutable in python..


a detailed explanation will be highly appreciated

thanks
Re: Learn Python- Introduction To Programming by uzoexcel(m): 11:52am On May 13, 2017
lyrrex:
i'm following.. Never
knew python is so easy to understand
I 'll start following from next week
Re: Learn Python- Introduction To Programming by Nobody: 7:03pm On May 13, 2017

(1) (2) (3) (Reply)

Is Anything Better Than The Netbeans Ide? / Using Finger Print Scanner On PHP / Is 5 Months Enough To Learn Java?

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 99
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.