Uploaded by Johnry Espiritu

[PYTHON] Presentation

advertisement
History of Python:
HOW IT CAME TO BE
History of Python
developed by Guido van Rossum during the eighties
until nineties at the National Research Institute for
Mathematics and Computer Science in the
Netherlands
was officially released in the year 1991
derived from many programming languages which
include C, C++, Algol-68, Unix Shell and more
Why the name Python?
Interestingly, the name Python was not inspired of
the large snake of the same name
It was from the BBC comedy show titled Monty
Python’s Flying Circus for which’s script Rossum
was reading while creating Python
He thought the name was appropriately short and
slightly mysterious
History of Python
The fundamental philosophy of Python is guided by
the following principles:
1. “Beautiful is better than ugly”
2. “Explicit is better than implicit”
3. “Simple is better than complex”
4. “Complex is better than complicated”
5. “Readability counts”
Introduction to Python
Python Overview
a powerful multipurpose programming language
perfect for programming beginners
has a straightforward, simple, and easy-to-use
syntax
has numerous reliable built-in libraries which allows
users to not code everything by themselves
- e.g. Sorting values in an array
Python Syntax
Compared to other languages, a program can be
created in Python just by using a single line.
Example: Printing “Hello World”
#include <stdio.h>
int main(){
printf(“Hello World”);
return 0;
}
print (“Hello World”)
6 lines vs 1 line!
Python Syntax
Another interesting fact in Python is that blocks of
code are determined by indentations
Example: Block of code inside an if
if (condition){
//statement1
//statement2
//statement3
}
if condition:
#statement1
#statement2
#statement3
# signifies start of a comment in Python
Python File Extension
When saving a program written in Python, the file is
saved with a .py extension
Example:
helloworld.py
print (“Hello World”)
Running Python
To run or execute Python scripts, various ways are
available, including:
> Python Integrated Development and
Learning Environment (IDLE)
> Python Interpreter
Python IDLE
Is included in almost every installation of Python
considered as the default Integrated Development
Environment (IDE) of Python
acts as an interactive interpreter
It reads a Python statement, evaluates the result of
that statement, and then prints the result on the
screen.
Python Interpreter
Compared to the C language, Python programs are
interpreted rather than compiled
This means that the program is translated into
machine code at runtime
You can run a program even with errors.
Interpreter analyzes and executes program line-byline.
Errors will only show when the line where the error is
present is processed
Printing Outputs and Getting Inputs
Printing Values
To display a value on screen in Python, the print()
function is used
The print() function allows programs to display
strings to users on a specific interface
The parameters of this function can be of any type,
as all will be automatically converted to strings for
output.
Printing Values
Examples:
print(“Hello World”)
Hello World
result = 7 + 2
print (“The answer is ” + result)
The answer is 9
More about print()
The whole syntax of print() is given below:
print(object(s), sep=separator, end=end, file=file, flush=flush)
Parameter
Description
object(s)
Any object, and as many as you like. Will be converted to string before printed
separator*
Specify how to separate the objects, if there is more than one. Default is ' '
end*
Specify what to print at the end. Default is '\n' (line feed)
file*
An object with a write method. Default is sys.stdout
flush*
A Boolean, specifying if the output is flushed (True) or buffered (False). Default is
False
*Optional
Getting Inputs
The input() function enables program users to
insert values directly into the code
The function's parameter, known as a prompt,
displays a message to the user
The response to input() is returned as a string to
the place where input() was called
To use the input as a different data type, it must be
explicitly converted.
Getting Inputs
In C, getting inputs usually take a printf() and scanf()
combo statements
In Python, this is simplified by input()
printf(“Enter your name: ”);
scanf(“%s”, name);
name = input(“Enter your name: ”)
Getting Inputs (More Examples)
Getting an input used as an integer:
age_input = input(“Enter your age: ”)
age = int (age_input)
or merge the two lines into one:
age = int (input(“Enter your age: ”))
Data Types
Data types in Python specify
the type of data that can be
stored in a variable.
Since everything is an object in
Python, data types are actually
classes and variables are instances
of these classes.
Python Data Types
Data Types
Classes
Description
Numeric
int, float, complex
holds numeric values
String
str
holds sequences of characters
Boolean
bool
holds either True or False value
Sequence
list, tuple, range
holds collection of items
Mapping
dict
holds data in key value pair form
Set
set, frozenset
hold collection of unique items
Numeric Types
int
-
represents positive or negative numbers
without a decimal
-
can handle numbers of any length
-
the length depends on your computer
memory
Examples:
num = 10
negative_num = -13
very_long = 231549876250193745262349857
Numeric Types
float
-
represents numbers with decimal point
-
useful in representing real numbers which
includes numbers in scientific notation
-
accurate up to 15 decimal places
Examples:
num = 0.123456789012345
sci_num = 1.2e100
Numeric Types
complex - holds complex numbers
- often used in mathematical sciences
- format in writing complex number:
<real part> + <complex part>j
Alternatively, you can omit the <real part>
Note: ‘j’ indicates imaginary unit
Examples:
x = 2 + 5j
x = 4j
#<real part>+<complex part>j
#<complex part>j
String Type
str
-
represents sequences of characters
-
enclosed in either single(‘’) or double(“”)
quotation marks
Examples:
word = ‘Hello!’
word = “Hello!”
You can also make a multiline string in Python using triple
single quotes or triple double quotes
Examples:
multi = ‘‘‘This is a
multiline string’’’
We can access the characters in a string in 3 ways:
1. Indexing
word = “Hello!”
print(word[4])
#Output: o
2. Negative indexing
word = “Hello!”
print(word[-1])
#Output: !
3. Slicing
word = “Hello!”
print(word[1:4])
#Output: ell
Strings in Python are immutable. That means that the
characters of a string cannot be changed.
Example:
word = “Hello!”
word[1] = “i”
TypeError: ‘str’ object does not support item assignment
However, we can assign the variable name to a new string.
Example:
word = “Hello!”
word = “World”
print(word)
# Output: World
Python String Operations
1. Compare Two Strings
2. Join Two or More Strings
Boolean Type
bool
-
represents boolean values, either True or False
Example:
a = True
b = False
c = 10 > 5
print(c)
#Output ‘True’
d = 35
e = 20
print(d < e) #Output ‘False’
Sequence Type
list
-
represents a collection of values which are
indexed, ordered, changeable and allow
duplicate values
-
are created using square brackets
Examples:
languages = [”Java”, “C”, “Python”]
numbers = [1, 2, 3.0, 4]
Similar with strings, you can access the elements on a list
using 3 ways:
1. Indexing
numbers = [1, 2, 3.0, 4]
print(numbers[2])
# Output: 3.0
2. Negative Indexing
numbers = [1, 2, 3.0, 4]
print(numbers[-3])
# Output: 2
3. Slicing
numbers = [1, 2, 3.0, 4]
print(numbers[0:2])
# Output: 1, 2
You can change the items of a list
numbers = [1, 2, 3.0, 4]
numbers[2] = 3
print(numbers)
# Output: [1, 2, 3, 4]
You can add an item on a list using the append() method
numbers = [1, 2, 3.0, 4]
numbers.append(5)
print(numbers)
# Output: [1, 2, 3.0, 4, 5]
Use remove() method to remove an item from the list
numbers = [1, 2, 3.0, 4]
numbers.remove(3.0)
print(numbers)
# Output: [1, 2, 4]
Sequence Type
tuple
-
collection of values which are indexed, ordered,
allow duplicates but are not changeable
-
once a tuple variable is created, it cannot be
modified
-
uses parenthesis to store items
Example:
anyTuple = (“One”, “Two”, “Three”)
Three ways to access members of a tuple:
1. Indexing
anyTuple = (“One”, “Two”, “Three”)
print(anyTuple[0])
# Output: One
2. Negative Indexing
anyTuple = (“One”, “Two”, “Three”)
print(anyTuple[-2])
# Output: Two
3. Slicing
anyTuple = (“One”, “Two”, “Three”)
print(anyTuple[-3:-1])
# Output: (‘One’, ‘Two’)
Sequence Type
range -
represents an immutable sequence of
numbers and is commonly used for looping a
specific number of times in for loops
Example:
num = range(24)
Mapping Type
dict
-
collection of items, similar to lists and tuples.
However, unlike lists and tuples, each item in a
dictionary is a key-value pair (consisting of a key
and a value).
-
we create a dictionary by placing key: value pairs
inside curly brackets {}, separated by commas
Dictionary keys must be immutable. We cannot use
mutable (changeable) objects such as lists as keys.
Dictionary keys must be unique.
We use keys to access values in a dictionary, but not the
other way around.
You can add an item to a dictionary by assigning a value to
a new key.
You can use the del statement to remove an item from the
dictionary.
capital_city = {"Nepal": "Kathmandu",
"Italy": "Rome"}
del capital_city["Italy"]
print(capital_city)
# Output: {'Nepal': 'Kathmandu'}
You can change the value of a dictionary element by
referring to its key
capital_city = {"Nepal": "Kathmandu", "Italy": "Naples"}
capital_city["Italy"] = "Rome"
print(capital_city)
# Output: {'Nepal': 'Kathmandu', 'Italy': 'Rome'}
Set Type
set
-
collection of values which are unindexed,
unordered, unchangeable and don’t allow
duplicates
-
Sets are unchangeable in the sense that
the value of an element cannot be
modified. You can either remove or add
new items.
student_id = {112, 114, 116, 118, 115}
print(student_id[2])
# Output: TypeError: 'set' object is not subscriptable
student_id = {112, 114, 116, 118, 115}
student_id[2] = 117
# Output: TypeError: 'set' object does not support item assignment
student_id = {112, 114, 116, 118, 115, 114} # 114 is repeated
print(student_id)
# Output: {112, 114, 115, 116, 118}
student_id = {112, 114, 116, 118, 115}
student_id.add(125)
# add an item
print(student_id)
# Output: {112, 114, 115, 116, 118, 125}
student_id = {112, 114, 116, 118, 115, 125}
student_id.remove(114)
# remove an item
print(student_id)
# Output: {112, 115, 116, 118, 125}
Set Type
frozenset
- similar to set except that it is immutable
- cannot be modified
- frozen sets can be used as keys in a
dictionary or as elements of another set. But
like sets, it is not ordered (the elements can
be set at any index)
Example:
# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')
fSet = frozenset(vowels)
print('The frozen set is:', fSet)
print('The empty frozen set is:', frozenset())
# frozensets are immutable
fSet.add('v')
# will result in an error message
Keywords and Identifiers, Constants and
Variables + Declaration + Initialization
Python keywords are the words that are
reserved. That means you can’t use them as
name of any entities like variables, classes
and functions.
Keywords in Python is case sensitive.
So they are to be written as it is.
Python Keywords
and
Logical Operator
except
as
Alias
assert
For debugging
finally
async
Used in an asynchronous
function
To catch exceptions
nonlocal
Declare a non-local variable
not
To negate a condition
To run a code snippet when
no exceptions occur
or
Either one of the conditions
needs to be true
for
For loop
pass
Statement that will do nothing
await
Used in asynchronous
functions
from
To import only a specific
selection of a module
raise
Raise an exception
break
Break out (of loops)
global
specify a variable scope as
global
return
Exits a function and returns a
value
class
For defining classes
if
Conditional Statement
continue
To go to the next iteration of
the loop
import
Used to import modules
try
Part of the try…except
statement
while
Define a while loop
with
To make exception handling
and file operator easy
def
For defining a function
in
Checks if value is in a list,
tuple
del
For deleting objects
is
To test for equality
elif
Part of if-elif-else
lambda
Create anonymous functions yield
else
Conditional Statement
None
NULL value
Ends a function, returns a
generator operator
What are Python Identifiers?
Python Identifier is the name we give to identify a
variable, function, class, module or other object. That
means whenever we want to give an entity a name,
that’s called identifier.
What is a Variable in Python?
A variable, as the name indicates is something whose value
is changeable over time. In fact a variable is a memory
location where a value can be stored
Rules for Writing Identifiers
There are some rules for writing Identifiers. But first you
must know Python is case sensitive. That means Name
and name are two different identifiers in Python. Here are
some rules for writing Identifiers in python.
Though these are hard rules for writing identifiers, also
there are some naming conventions which are not
mandatory but rather good practices to follow.
Rules for Writing Identifiers
1. Identifiers can be combination of uppercase and lowercase
letters, digits or an underscore(_). So myVariable, variable_1,
variable_for_print all are valid Python identifiers.
2. An Identifier can not start with digit. So while variable1 is
valid, 1variable is not valid.
3. We can’t use special symbols like !,#,@,%,$ etc in an
Identifier.
4. Identifier can be of any length.
5. Class names start with an uppercase letter. All other
identifiers start with a lowercase letter.
Rules for Writing Identifiers
6. Starting an identifier with a single leading underscore
indicates the identifier is private.
7. If the identifier starts and ends with two underscores, that
means the identifier is language-defined special name.
8. While c = 10 is valid, writing count = 10 would make more
sense and it would be easier to figure out what it does even
when you look at your code after a long time.
9. Multiple words can be separated using an underscore, for
example this_is_a_variable.
Variable Declaration and Initialization
Unlike other variables such as C, Python has no
command for declaring a variable
You create one the moment you first assign a value
to it
Example: Declaring an integer variable ‘num’
int num;
num = 0
Variable Declaration and Initialization
num = 0
num is the name of the variable created
the value 0 dictates what data type the variable
num has
Hence, initializing a value of a variable is needed
upon declaration as it determines the data type
myVariable = “Hello World”
print(myVariable[0:5] + “, how are you?”) #Output
var1 = 1
var2 = 2
print(var1) #Output
print(var2) #Output
print(var1 + var2) #Output
If you run the program, the output will be like below image.
Hello, how are you?
1
2
3
Python Constants
A constant is a special type of variable whose value
cannot be changed.
In Python, constants are usually declared and
assigned in a module (a new file containing
variables, functions, etc. which is imported to the
main file).
Create a Constants.py
# Declare Constants
Pi = 3.14159235659
GRAVITY = 9.8
Create a main.py
# Import file that was created above
import Constants
print(Constants.Pi) #Output: 3.14159235659
print(Constants.GRAVITY) #Ouput: 9.8
Character Set
Character Set
A character set in Python is a collection of legal characters that
a scripting language will recognize when writing a script. We
are referring to the Python coding language in this instance.
Therefore, the character set in Python is a legitimate collection
of characters that the Python language can recognize.
These represent the Python scripting
language's supported characters.
Alphabets: These include all the small (a-z) and capital (A-Z)
alphabets.
Digits: It includes all the single digits 0-9.
Special Symbols: It includes all the types of special
characters," 'l ; : ! ~ @ # $ % ^ ` & * ( ) _ + - = { } [ ] \ .
White Spaces: White spaces are also a part of the character
set. These are tab space, newline, blank space, and carriage
return.
Other: Python supports all the types of ASCII and UNICODE
characters that constitute the Python character set.
Tokens
The smallest distinct element in a Python program is called a
token. Tokens are used to construct each phrase and
command in a program.
The different Python tokens include:
Keywords
if, else, for,
while, and,
or, True,
false, etc.
Operators
Arithmetic
Relational
Logical
Membership
etc.
Identifiers
ABC, ab123,
Ab_123, xyz,
PQ, A-1, _123,
etc.
Punctuators
[ ], { }, ( ), -=,
+=, *=, //=,
**==, =, etc.
Literals
String
Numeric
Boolean
None
Arithmetic Operations and Expressions
Arithmetic Operations and Expressions
are fundamental concepts in programming languages
which involve performing mathematical calculations.
so, when we say "arithmetic operations and
expressions," we mean the application of basic
mathematical operations to generate mathematical
statements or formulae that can be evaluated to get a
numerical result.
Arithmetic Operations
Operator
Name
+
Addition
-
Subtraction
*
Multiplication
/
Division
%
Modulus
**
Exponent
//
Floor Division
perform basic
mathematical operations
on numeric data such as
addition, subtraction, etc.
one or more of these can
be combined in a single
arithmetic expression as
long as syntax is correct
Arithmetic Operations
Addition Operator (+)
adds the two numeric operands
on either side and returns the
result.
Multiplication Operator(*)
Multiplication is the process of
calculating the product of two or
more numbers.
Subtraction Operator (-)
This operator subtracts two
operands. Result is negative if the
second operand is larger.
Division Operator (/)
performs actual division and
returns a floating-point number
regardless of operands’ numeric
data types
Arithmetic Operations
Modulus Operator (%)
It returns the remainder of
dividing the left operand by the
right operand.
Exponent Operator (**)
Python uses ** (double asterisk) as
the exponent operator (sometimes
called raised to operator)
Floor Division Operator (//)
Floor division in Python is
performed using the double
forward slash operator.
It divides the left-hand operand
by the right-hand operand and
returns the largest integer that
is less than or equal to the result.
Arithmetic Expressions
is a combination of numeric values, operators,
and sometimes parenthesis
consists of operands and operators combined in
a manner that is familiar to the algebra you
learn in math classes
Arithmetic Expressions
Remember the order of operations PEMDAS, which dictates
the sequence in which arithmetic operations are performed:
1. Parentheses
2. Exponents (**)
3. Multiplication, Division, Floor Division, and Modulus
(from left to right)
4. Addition and Subtraction (from left to right)
Arithmetic Expressions (Examples)
EXPRESSION
EVALUATION
VALUE
5 + 3 * 2
5 + 6
11
(5 + 3) * 2
8 * 2
16
6 % 2
0
0
2 * 3 ** 2
2 * 9
18
-3 ** 2
-(3 ** 2)
-9
Arithmetic Expressions (Examples)
EXPRESSION
EVALUATION
VALUE
-(3) ** 2
9
9
2 ** 3 ** 2
2 ** 9
512
(2 ** 3) ** 2
8 ** 2
64
45 / 0
Error: cannot divide by 0
45 % 0
Error: cannot divide by 0
Arithmetic Expressions
In both C and Python, arithmetic operations and expressions are
similar in terms of basic functionality, but there are differences in
syntax
Arithmetic expressions are
typically written with semicolons
at the end of each statement.
int result;
result = 10 + 5;
Python does not use semicolons
to terminate statements.
result = 10 + 5;
Increment/Decrement Operator
In C and Java, special increment and decrement operators
such as ++ and -- are available
These are not present in Python
The following examples exhibit how to increment and
decrement values in Python
x += 2
x = x + 3
x++
#increases value of x by 2
#explicit incrementation
#error in Python
Comparison operators
Comparison operators in Python, also called
relational operators, are used to compare two
operands. They return a Boolean True or False
depending on whether the comparison
condition is true or false.
These operators are important to
conditional statements and looping
statements in Python
Different Comparison Operators Present in Python
<
Less than
a<b
>
Greater than
a>b
<=
Less than or equal to
a <= b
>=
Greater than or equal to
a >= b
==
Is equal to
a == b
!=
Is not equal to
a != b
Comparison operators are binary in nature, requiring two
operands. An expression involving a comparison operator is
called a Boolean expression, and always returns either True or
False.
a = 6
b = 9
print (a > b)
print (a < b)
Output:
False
True
Both the operands may be Python literals, variables or
expressions. Since Python supports mixed arithmetic, you can
have any number type operands.
More examples of Comparisons:
Comparison of Int and Float Number :
In the following example, an integer and a float operand are
compared.
a = 10
b = 10.0
print (a > b)
print (a < b)
print (a == b)
print (a != b)
Output:
False
False
True
False
More examples of Comparisons:
Comparison of Complex Numbers :
Although complex object is a number data type in Python, its
behavior is different from others.
Python doesn't support < and > operators, but it does support
equality ( == ) and inequality ( != ) operators.
a = 10 + 1j
b = 10 - 1j
print (a == b)
print (a != b)
Output:
False
True
Logical Operators
Logical Operators
are used to combine multiple conditions together and
evaluate them as a single boolean expression
includes the operators: and, or, and not which evaluates
to either truth table based on specified conditions
must be written in lowercase
Logical Operators
Logical operators available in C are the same operators
available in Python.
But the are differences when it comes to code syntax
Operator
AND
OR
NOT
&&
||
!
and
or
not
Truth Tables
Logical "and" Operator
Logical "or" Operator
a
b
a and b
a
b
a or b
T
T
T
T
T
T
T
F
F
T
F
T
F
T
F
F
T
T
F
F
F
F
F
F
Truth Tables
Logical "not" Operator Truth Table
a
not (a)
F
T
T
F
Examples:
Logical Operators With Boolean Conditions
x = 10
y = 20
Output:
print(x > 0 and x < 10)
print(x > 0 and y > 10)
print(x > 10 or y > 10)
print(x%2 == 0 and y%2 == 0)
print(not (x+y) > 15)
False
True
True
True
False
Examples:
Logical Operators With Non-Boolean Conditions
We can use non-boolean operands with logical operators.
Here, we need to note that any non-zero numbers, and nonempty sequences evaluate to True.
Hence, the same truth tables of logical operators apply.
Examples:
Logical Operators With Non-Boolean Conditions
x = 10
y = 20
z = 0
print(x and y)
print(x or y)
print(z or x)
print(y or x)
print(x and z)
Output:
20
10
10
20
0
Selection / Conditional Statements
Conditional Statements
are statements in Python that provide a choice for the
control flow based on a condition
It means that the control flow will be decided based on the
outcome of the condition.
Primary conditional statements in Python:
if
else
elif
The if statement
used to execute a block of code if a specified condition is true.
if condition:
#Code block to be executed if the condition is true
The else statement
used to execute a block of code if the if condition is false.
if condition:
# Code block to be executed if the condition is true
else:
# Code block to be executed if the condition is false
The elif statement
Python's way of saying "if the previous conditions were not
true, then try this condition".
equivalent to else if in C
if condition1:
# Code block to be executed if condition1 is true
elif condition2:
# Code block to be executed if condition2 is true
else:
# Code block to be executed if all conditions are false
Short Hand If: If you have only one statement to execute, you can
put it on the same line as the if statement.
Example: One line if statement
if a > b : print(“a is greater than b“)
Short Hand If ... Else: If you have only one statement to execute,
one for if, and one for else, you can put it all on the same line:
Example: One line if-else statement
a = 2
b = 330
print(“A“) if a > b else print(“B“)
Nested if..else Conditional Statements in Python:
Nested conditional statements are a feature in Python that allows
for complex decision-making within a program. By nesting one
conditional statement within another
letter = “A“
if letter == “B“:
print(“letter is B“)
else:
if letter == “C“:
print(“letter is C“)
else:
if letter == “A“:
print(“letter is A“)
else:
print(“letter isn‘t A, B and C“)
Ternary Expression Conditional Statements in Python:
The Python ternary Expression determines if a condition is true
or false and then returns the appropriate value in accordance
with the result. The ternary Expression is useful in cases where
we need to assign a value to a variable based on a simple
condition, and we want to keep our code more concise — all in
just one line of code.
Example: Using Native
way
Example: Using Ternary
Operator
a, b = 10, 20
a, b = 10, 20
if a != b:
if a > b:
print(“a is greater than b“)
else:
print(“b is greater than a“)
else:
print(“Both a and b are equal“)
print(“Both a and b are equal“ if a
== b else “a is greater than b“
if a > b else “b is greater
than a“)
Best Practices for Using Conditional Statements
1. Use Clear and Descriptive Conditions
2. Avoid Complex Nested Structures
3. Prefer elif Over Nested if Statements
4. Consider Using Ternary Conditional Operator for
Conciseness
Repetition
Repetition
also referred to as “loops”
a control structure that allows a set of instructions
or a code block to be executed repeatedly until a
specified condition is met or an exit statement is
reached
In C, the following
looping constructs can
be used:
In Python, only these
two are present:
while
do-while
for
while
for
The while loop
- repeats a block of code as long as a certain condition
is true
while (condition){
//statement(s)
//update
}
while condition:
#statements
#update
The while loop
Example: Display numbers from 0 to 9 using a while
loop
0
Solution:
i = 0
while i < 10:
print(i)
i+=1
1
2
3
4
5
6
7
8
9
The while loop
In comparison with C, while loops in Python can have an
appended else statement after the while block.
This is executed once, after the condition of the loop is
no longer true.
while condition:
#statements
else:
#statements
The while loop
Example:
i = 0
while i < 10:
print(i)
i+=1
else:
print(“0-9 Complete”)
0
1
2
3
4
5
6
7
8
9
0-9 Complete
The for loop
- usually used when the number of iterations is
known
- In Python, for loops are more conveniently used to
iterate through sequence of values
The for loop
for (init; cond; upd)
{
//statement(s)
}
for value in sequence:
#statement(s)
*init = initialization
cond = condition
upd = update
*value is a variable used to index items
sequence is a structure containing
multiple elements
The for loop
The implementation of for loops in C and Python is not
so similar
NO initialization, condition, and update statements
are needed in Python
for loops in Python need a sequence of elements and
it iterates through elements on its own
The for loop
Example for loop in C
Display numbers from 0 to 9
for (int i = 0; i < 10; i++)
printf(“%d”, i);
0
1
2
3
4
5
6
7
8
9
The for loop
Example for loop in Python
Display numbers from 0 to 9
In Python, when dealing with integer values in a
for loop, we make use of the range() function
range(n) returns a sequence of numbers of size n
Example:
range (4) --> returns a sequence of 0, 1, 2, 3
The for loop
Example for loop in Python
Display numbers from 0 to 9
So, to solve the problem of displaying numbers from 0
to 9 in Python, we make use of the solution below:
for i in range(10):
print(i)
REMEMBER: ‘i’ does not need to be declared;
parameter in range() is not included in the
sequence
The for loop
More about range():
range(x) : returns a sequence containing 0 to x-1
range(x, y) : returns a sequence containing x to y-1
range(x, y, z) : returns a sequence containing values
between x to y with an increment of z
NOTE: x, y, and z are integers
Other uses of for loop
Iterating through a list
courses = [‘Biology‘,
‘Chemistry‘, ‘Computer
Science‘, ‘Information
Technology‘,
‘Meteorology‘]
for i in courses:
print(i)
Biology
Chemistry
Computer Science
Information Technology
Meteorology
Other uses of for loop
Iterating through a string
course = ‘Computer Science’
for i in course:
print(i)
C
o
m
p
u
t
e
r
S
c
i
e
n
c
e
ADDITIONAL NOTES
Just like in while loop, for loops in Python can be
appended with an else clause which will execute
once, after the for loop terminates
break and continue statements are also available for
use in Python
break exits the loop entirely
continue skips the current iteration and proceeds to
the next one
Library Functions
and their C counterparts
Input/Output:
Python: print(), input()
C: printf(), scanf()
Math functions:
Python: abs(), max(), min(), pow(), round()
C: abs(), fmax(), fmin(), pow(), round()
String Functions:
Python: len(), strcat(), strcmp(), strcpy(), strchr(),
strstr()
C: strlen(), strcat(), strcmp(), strcpy(), strchr()
Array/List Functions:
Python: len(), append(), extend(), pop(), remove()
C: Arrays are typically handled using pointers and
manual memory management, so there are no
built-in functions for these operations.
File I/O Functions:
Python: open(), read(), write(), close()
C: fopen(), fread(), fwrite(), fclose()
Conditional Statements:
Python: if, elif, else
C: if, else if, else
Looping Constructs:
Python: for, while
C: for, while
Memory Management:
Python: handled automatically by the Python
interpreter (using garbage collection).
C: handled manually, using functions like malloc(),
calloc(), realloc(), and free().
Some notable library functions of
Python that are not available in C
help() - this function helps to invoke the built-in Help
System.
hex() - converts an Integer value to Hexadecimal.
hash() - this function returns a hash value of an object
range() - generates a sequence of numbers.
eval(), exec() - evaluate Python expressions or execute
Python code dynamically.
complex() - a Complex Number is created.
Use of Python across Multiple Fields
Reasons why Python is a viable tool across
different fields:
1.
Easy to use
2.
Versatile
3.
AI Integration
4.
True Portability
5. Efficient for Rapid Development
6.
Extensive Libraries and
Frameworks
7. Automatic Memory Allocation
Artificial Intelligence and Robotics
Python is widely used in artificial
intelligence and robotics applications.
Libraries like OpenAI Gym, ROS (Robot
Operating System), facilitate research,
development, and deployment of AIpowered systems and robots.
Game Development
Python offers an array of
libraries and frameworks that
are purpose-built for game
development. Some aspects of
the game server and backend
systems for World of Tanks, a
multiplayer online tank warfare
game, were developed using
Python.
Game Development
Python offers an array of
libraries and frameworks that
are purpose-built for game
development. Some aspects of
the game server and backend
systems for World of Tanks, a
multiplayer online tank warfare
game, were developed using
Python.
Game Development
Python offers an array of
libraries and frameworks that
are purpose-built for game
development. Some aspects of
the game server and backend
systems for World of Tanks, a
multiplayer online tank warfare
game, were developed using
Python.
Healthcare and Bioinformatics
Python is used in healthcare for tasks
such as medical imaging analysis,
patient data management, drug
discovery, and bioinformatics. Libraries
like Biopython and scikit-bio are
commonly used for analyzing
biological data and conducting
genomic research.
Thank you.
Download