0% found this document useful (0 votes)
3 views50 pages

Introduction To Programming

Uploaded by

nahomeyasu36
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views50 pages

Introduction To Programming

Uploaded by

nahomeyasu36
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

What is python?

 Python is a simple, general purpose, high level, and object-


oriented programming language.
 Guido Van Rossum is the founder of Python programming.
 Python is an interpreted language, which means
 Code is executed line-by-line and does not need to be compiled
before running.
 This makes it easy to write, test, and debug code.
 Python is also cross-platform means
 It can run on a variety of operating systems, including Windows,
macOS, and Linux.

3
Cont’d
 Python is an easy-to-learn yet powerful and versatile language, which
makes it attractive for Application Development.
 Python makes development and debugging fast because no
compilation step is included, and edit-test-debug cycle is very fast.
 In Python, code readability and maintainability are important.
 As a result, even if the code was developed by someone else, it is
easy to understand and adapt by some other developer.

4
Why learn python ?
 Python provides many useful features to the programmer. These
features make it the most popular and widely used language.
 Easy to use and Learn: Python has a simple and easy-to-understand syntax,
unlike traditional languages like C, C++, Java, etc., making it easy for
beginners to learn.
 Object-Oriented Language: It supports object-oriented
programming, making writing reusable and modular code easy.
 Learn Standard Library: Python's standard library contains many
modules and functions that can be used for various tasks, such as
string manipulation, web programming, and more.

5
Cont’d
 Open Source Language: Python is open source and free to use, distribute
and modify.

 GUI Programming Support: Python provides several GUI


frameworks, such as Tkinter and PyQt, allowing developers to create
desktop applications easily.

 Integrated: Python can easily integrate with other languages and


technologies, such as C/C++, Java, and . NET.

6
Where is Python used?
 Data Science: Data Science is a vast field, and Python is an
important language for this field because of its simplicity, ease of use,
and availability of powerful data analysis and visualization libraries
like NumPy, Pandas, and Matplotlib.
 Artificial Intelligence: AI is an emerging Technology, and Python is a
perfect language for artificial intelligence and machine learning
because of the availability of powerful libraries such as TensorFlow,
Keras, and PyTorch.
 Machine Learning: Python is widely used for machine learning due to
its simplicity, ease of use, and availability of powerful machine
learning libraries.
7
Cont’d
 Computer Vision or Image Processing Applications: Python can be used for
computer vision and image processing applications through powerful libraries
such as OpenCV and Scikit-image.
 Education: Python's easy-to-learn syntax and availability of many resources
make it an ideal language for teaching programming to beginners.
 Software Development: Python is considered one of the best software-making
languages. Python is easily compatible with both from Small Scale to Large
Scale software.

8
Python Popular Frameworks and Libraries
 Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.

 Web development (Server-side) - Django Flask, Pyramid, CherryPy

 Requests: a library for making HTTP requests

 Pygame: a library for game development

 Pytest: a testing framework for Python

 NLTK: a library for natural language processing

9
Basic Syntax
 There is no use of braces or semicolon in Python. It is English-like
language.
 But Python uses indentation to define a block of code.
 Indentation is nothing but adding whitespace before the statement
when it is needed. For example -
def func():
statement 1
statement 2
…………………
…………………
statement N

10
Cont’d
 statements that are same level to the right belong to the function.
Generally, we can use four whitespaces to define indentation.

 Instead of Semicolon, Python ends its statements with NewLine


character.

 Python is a case-sensitive language, which means that uppercase and


lowercase letters are treated differently.

 For example, 'name' and 'Name' are two different variables in Python.

11
Python Comment
 comment is programmer-readable explanation in Python source code.

 They are added with the purpose of making the source code easier for
humans to understand, and are ignored by Python interpreter.

 This trick is useful for adding notes to the code or temporarily


disabling a code block.

 Python supports single-line (or end-of-line) and multi-line (block)


comments.

12
Cont’d
 In Python, comments can be added using the '#' symbol. Any text written after
'#' symbol is considered a comment and is ignored by the interpreter.

 A hash sign (#) that is not inside a string literal begins a comment.

 All characters after the # and up to end of the physical line are part of
comment and Python interpreter ignores them.

### Multi Line Comment


### single Line Comment
# This is a comment.
# First comment
# This is a comment, too.
print ("Hello, World!") # Second
# This is a comment, too.
comment
# I said that already.

13
Identifier
 Is a name used to identify a variable, function, class, module or other
object.

 An identifier starts with a letter A to Z or a to z or an underscore (_)


followed by zero or more letters, underscores and digits (0 to 9).

 Python does not allow punctuation characters such as @, $, and %


within identifiers.

 Python is a case sensitive programming language. Thus, Manpower


and manpower are two different identifiers in Python.

14
Cont’d
Here are naming conventions for Python identifiers −
 Python Class names start with an uppercase letter. All other identifiers start with a lowercase
letter. Example: Class Car.
 Starting an identifier with a single leading underscore indicates that the identifier is private
identifier. Example def _get_birth_year(self):
 Starting an identifier with two leading underscores indicates a strongly private identifier.
 Example _ _age, _Person_ _age
 If the identifier also ends with two trailing underscores, the identifier is a language-defined
special name. Example _ _str_ _

15
Reserved Words
 The following list shows the Python keywords.

 These are reserved words and you cannot use them as constant or
variable or any other identifier names.

 All the Python keywords contain lowercase letters only.


 You can not use reserved words as variable names / identifiers
and del for is raise
assert elif from lambda return
break else global not try
class except if or while
continue exec import pass yield
def finally in print

16
Lines and Indentation
 Python provides no braces to indicate blocks of code for class and
function definitions or flow control.
 Blocks of code are denoted by line indentation
 The number of spaces in the indentation is variable, but all
statements within the block must be indented the same amount.
 For example −
if True:
print ("True")
else:
print ("False")

17
Multi-Line Statements
 Statements in Python typically end with a new line.
 Python does, however, allow the use of the line continuation character (\) to denote
that the line should continue.
 For example −
total = item_one + \
item_two + \
item_three
 Statements contained within the [], {}, or () brackets do not need to use the line
continuation character. For example following statement works well in Python −
days = ['Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday']

18
Quotations
 Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string.
 The triple quotes are used to span the string across multiple lines.
 word = 'word "
 sentence = "This is a sentence. "
 paragraph = """This is a paragraph. It is made up of multiple lines and
sentences.""“
Multiple Statements on a Single Line
 The semicolon ( ; ) allows multiple statements on the single line given that neither
statement starts a new code block. Here is a sample snip using the semicolon −
 import sys; x = 'foo’; [Link] (x + '\n’)

19
Variables
 Are reserved memory locations used to store values in Program.

 When you create a variable you reserve some space in the memory.

 Python variable is created automatically when you assign a value to it.


 The equal sign (=) is used to assign values to variables.

 The operand to the left of the = operator is the name of the variable
and the operand to the right of the = operator is the value stored in
counter = 100 # Creates an integer variable
the variable. For example − miles = 1000.0 # Creates a floating point
variable name = "Zara Ali" # Creates a string
variable

20
Printing Variables
 Once we create a Python variable and assign a value to it, we can print it using
print() function.

 Following is the extension of previous example and shows how to print different
variables in Python:  A variable is a name that refers to a value which is used to
refer to the value later
x=3
counter = 100 # integer message = ‘hello’
variable  Programmers get to choose the names of the variables
miles = 1000.0 # floating point  You can change the contents of a variable in a later statement
name = "Zara Ali" # string  Rules
print (counter)  Must start with a letter or underscore _
print (miles)  Must consist of letters and numbers and underscores
print (name)  Case Sensitive
Good: spam eggs spam23 _speed
Bad: 23spam #sign var.12
21
Different: spam Spam SPAM
Multiple Assignment
 Python allows you to assign a single value to several variables
a = b = c = 100
print (a)
print (b)
print (c)

 Here, an integer object is created with the value 1, and all three
variables are assigned to the same memory location. You can also
assign multiple objects to multiple variables.
a = b = c = 100
print (a)
print (b)
print (c)

22
Variable Names
There are rules which should be taken care while naming variable:
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number or any special character like
$, (, * % etc.
 A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
 Python variable names are case-sensitive which means Name and NAME
are two different variables in Python.
 Python reserved keywords cannot be used naming the variable.

23
Cont’d
Local Variable
 Defined inside a [Link] can not access variable outside function.
 A Python functions is a piece of reusable code: Example
def sum(x,y): x=5
sum = x + y y = 10
return sum def sum():
print(sum(5, 10)) sum = x + y
return sum
print(sum())
Global Variable

 Any variable created outside a function can be accessed within any


function and so they have global scope.

24
Named Constants
 They are similar to variables: a memory location that’s been given a
name.

 Unlike variables their contents shouldn’t change.

 >>> PI = 3.14

Literals
 Literal/unnamed constant/magic number: not given a name, the
value that you see is literally the value that you have.

 >>> afterTax = 100000 – (100000 * 0.2)


25
Expressions
 An expression is a combination of values, variables, and operator

17

x +17

Sentences or Lines

26
Assignment statement
 An assignment statement assigns a value to a variable

 We can not access variable outside function.

Basic Form
 <variable> = <expr>
 We assign a value to a variable using the assignment statement (=)
 An assignment statement consists of an expression on the right hand side and a
variable to store the result

27
Numeric Expressions
 Because of the lack of mathematical symbols on

computer keyboards - we use “computer-speak”

to express the classic math operations

 Asterisk is multiplication

 Exponentiation (raise to a power) looks different from in math.

28
Cont’d

>>> xx = 2
>>> >>> print xx >>> jj = 23
4 >>> kk = jj % 5
>>> yy = 440 * 12 >>> print(kk)
>>> print(yy) 3
5280 >>>print(4 ** 3)
>>> zz = yy / 1000 64
>>> print(zz)
xx = xx + 2
5

29
Order of Evaluation
 When we string operators together - Python must know
which one to do first

 This is called “operator precedence”

 Which operator “takes precedence” over the others

x = 1 + 2 * 3 - 4 / 5 ** 6

30
Operator Precedence Rules
 Highest precedence rule to lowest precedence rule
 Parenthesis are always respected

 Exponentiation (raise to a power) Parenthesis


Power
 Multiplication, Division, and Remainder
Multiplication
 Addition and Subtraction Addition
Left to Right
 Left to right
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print(x)
11
>>>
31
Operator Precedence

 When writing code - use parenthesis

 When writing code - keep mathematical Parenthesis


Power
expressions simple enough that they are Multiplication
Addition
easy to understand
Left to Right
 Break long series of mathematical
operations up to make them more clear

32
What does “Type” Mean?
 In CS and programming, data type(simply type) is a classification of
data which tells the compiler or interpreter how the programmer
intends to use the data.
 Example: Boolean(true or false), string(“hello”,”ABC”), int(1,2,5)
 Python Data Types are used to define the type of a variable.
 It defines what type of data we are going to store in a variable.
 The data stored in memory can be of many types.
 Number objects are created when you assign value. For example:
var1 = 1
var2 = 10
var3 = 10.023
33
Cont’d

34
Types in Python

 In Python variables, literals, and

constants have a “type” >>> ddd = 1 + 4


>>> print(ddd)
 Python knows the difference between
5
>>> eee = 'hello ' + 'there'
an integer number and a string >>> print(eee)
hello there
 For example “+” means “addition” if

something is a number and


“concatenate” if something is a string

35
String Data Type
 Strings are contiguous set of characters represented in quotation marks.
 Python allows for either pairs of single or double quotes.
 The plus (+) sign is string concatenation operator and asterisk (*) is
repetition operator in Python.
 str = 'Hello World!’

 print (str) # Prints complete string

 print (str[0]) # Prints first character of the string

 print (str[2:5]) # Prints characters starting from 3rd to 5th

 print (str[2:]) # Prints string starting from 3rd character

 print (str * 2) # Prints string two times

 print (str + "TEST") # Prints concatenated string

36
Python Boolean Data Types
 Python Boolean type is one of built-in data types which represents one of the two
values either True or False.

 Python bool() function allows you to evaluate the value of any expression and returns
either True or False based on the expression.

 Examples
This produce the following result
a = True # display the value of a true
<class 'bool'>
print(a) # display the data type of a
print(type(a))

37
Several Types of Numbers
 Numbers have two main types
 Integers are whole numbers: -14, -2, 0, 1,
100, 401233 >>> xx = 1
>>> type (xx)
 Floating Point Numbers have decimal parts: <type 'int'>
-2.5 , 0.0, 98.6, 14.0 >>> temp = 98.6
>>> type(temp)
 There are other number types - they <type 'float'>

are variations on float and integer

38
Mixing Integer and Floating

 When you perform an operation


>>> print(99 // 100)
where one operand is an integer 0
>>> print(99 / 100.0)
and the other operand is a
0.99
floating point the result is a >>> print(99.0 // 100)
0.0
floating point
>>> print(1 + 2 * 3 // 4.0 - 5)
 The integer is converted to a -3.0
>>>
floating point before the operation

39
Type Matters

>>> eee = 'hello ' + 'there'


 Python knows what “type” everything is >>> eee = eee + 1
Traceback (most recent call last):
 Some operations are prohibited File "<stdin>", line 1, in
<module>
 You cannot “add 1” to a string TypeError: cannot concatenate 'str'
and 'int' objects
 We can ask Python what type something
>>> type(eee)
is by using the type() function. <type 'str'>
>>> type('hello')
<type 'str'>

40
Python Data Type Conversion
 To convert data between different Python data types, you simply use
the type name as a function.

Conversion to int

 Following is an example to convert number, float and string into


integer data type: a = int(1) # a will be 1
b = int(2.2) # b will be 2
c = int("3") # c will be 3
print (a)
print (b)
print (c)
41
Cont’d
 Conversion to float
a = float(1) # a will be 1.0
b = float(2.2) # b will be 2.2
c = float("3.3") # c will be 3.3
print (a)
print (b)
print (c)
 Conversion to string
a = str(1) # a will be "1"
b = str(2.2) # b will be "2.2"
c = str("3.3") # c will be "3.3"

print (a)
print (b)
print (c)
42
List Data Type
 Lists are the most versatile compound data types.

 Contains items separated by commas and enclosed within square brackets [].

 Values stored in a Python list can be accessed using slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1.
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john’]
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists

43
Python Tuple Data Type
 Tuple is another sequence data type that is similar to a list.
 Tuple consists of a number of values separated by commas.

 Unlike lists, however, tuples are enclosed within parentheses.

 The main differences between lists and tuples are:


 Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed
Tuples are enclosed in parentheses ( ( ) ) and cannot be updated.

 Tuples can be thought of as read-only lists.

44
Cont’d
 Example
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john’)
print (tuple) # Prints the complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd
print (tuple[2:]) # Prints elements of the tuple starting from 3rd element
print (tinytuple * 2) # Prints the contents of the tuple twice
print (tuple + tinytuple) # Prints concatenated tuples

45
Python Ranges
 Python range() is an in-built function in Python which returns a sequence of numbers
starting from 0 and increments to 1 until it reaches a specified number.
 We use range() function with for and while loop to generate a sequence of numbers.
Following is the syntax of the function:
range(start, stop, step)
 Here is the description of the parameters used:
 start: Integer number to specify starting position, (Its optional, Default: 0)
 stop: Integer number to specify starting position (It's mandatory)
 step: Integer number to specify increment, (Its optional, Default: 1)

46
Python Ranges
 Examples

 Following is a program which uses for loop to print number from 0 to 4 −


for i in range(5): # output 0-4
print(i)

for i in range(1, 5): # output 1-4


print(i)

for i in range(1, 5, 2): # output 1,3


print(i)

47
Boolean Expressions
<class 'bool'>

 True

 False

48
Boolean Expressions
 Boolean expressions are expressions that evaluate to one of two Boolean values: True or
False. >>> 2 <3
 Some languages use 0 or 1 True
>>> 3 <2
 Others have a data type
False
 Python has literals True and False >>> 5 -1>2+1
>>> 3 <= 4 True
True >>> 3 == 3
>>> 3 >= 4 True
False >>> 3 + 5 == 4 + 4
>>> 3 != 4 True
True >>> 3 == 5 - 3
49 False
Comparison operators
 True

 False

50
Logical Operators
 Boolean expressions can be combined together using Boolean
operators and, or, and not to form larger Boolean expressions.

 Boolean Expressions
>>> 2 < 3 and 4 > 5

False

>>> 2 < 3 and True

True

51
Operator Precedence
 a and b or c

 (a and b) or c

 Not

 a and (b or c)

52

You might also like