Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

Module 1 Introduction to Python Programming

Information and Communication Technology

Introduction to Python Programming


IT 331 Application Development and Emerging Technologies I

Module 1
Python Programming
Introduction

Python is an object-oriented programming language created by Guido Rossum in 1989. It is ideally


designed for rapid prototyping of complex applications. It has interfaces to many OS system calls and
libraries and is extensible to C or C++. Many large companies use the Python programming language
include NASA, Google, YouTube, BitTorrent, etc [ CITATION Gur20 13321 1.
Objectives:

Discuss the principles of Python Programming


Explain why Python is a useful scripting language for developers
Familiarize on the Python development interface
Discuss the concept of Python Input Output
Familiarize on Python variables
Create Python program which utilize 0/1 process

I. The Pytton Programming


Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is
designed to be highly readable. It uses English keywords frequently where as other languages use
punctuation, and it has fewer syntactical constructions than other languages [ CITATION Tut20
13321 1 .

Python programming is widely used in Artificial Intelligence, Natural Language Generation, Neural
Networks and other advanced fields of Computer Science. Python had deep focus on code readability
& this class will teach you python from basics [ CITATION Gur20 13321 ].
Python is a MUST for students and working professionals to become a great Software Engineer
especially when they are working in Web Development Domain. Below are some of the key
advantages of learning Python:

 Python is Interpreted — Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
 Python is Interactve — You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.

Introduction to Python Programming


IT 331 Application Development and Emerging Technologies I
 Python is Object-Oriented — Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.

 Python is a Beginner's Language — Python is a great language for the beginner-level


programmers and supports the development of a wide range of applications from simple text
processing to WWW browsers to games.

Python Is used for:


 web development (server-side),
 software development,
 mathematics,
 system scripting.

What can Python do?


 Python can be used on a server to create web applications.
 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software development.

Why Python?
 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon as it is written.
This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a functional way.

Il. Gettng Sbtted With Pytton


Python is a cross-platform programming language, which means that it can run on multiple platforms
like Windows, macOS, Linux, and has even been ported to the Java and .NET virtual machines. It is
free and open-source [ CITATION Pr020 13321 ].
The Easiest Way to Run Pytton
The easiest way to run Python is by using Thonny IDE.
The Thonny IDE comes with the latest version of Python bundled in it. So you don't have to install
Python separately.
Follow the following steps to run Python on your computer.
1. Download Thonny IDE

Introduction to Python Programming


IT 331 Application Development and Emerging Technologies I
2. Run the installer to install Thonny on your computer.
3. Go to: File > New. Then save the file with .py extension. For example, hello.py, example.py,
etc. (You can give any name to the file. However, the file name should end with .py)
4. Write Python code in the file and save it.

Introduction to Python Programming


IT 331 Application Development and Emerging Technologies I
- x
:

5. Then Go to Run > Run current saipt or simply click F5 to run it.

Visit www.thonny.org/ to see the full feature of this IDE.

Ill. Pytton Synex


The syntax of the Python programming language is the set of rules that defines how a Python program
will be written and interpreted (by both the runtime system and by human readers). The Python
language has many similarities to Perl, C, and Java. However, there are some definite differences
between the languages [ CITATION Wik20 13321 ].

Python Synex Rules


1. Python is case sensitive. Hence a variable with name myvariable is not same as
MYVARIABLE
2. For path specification, python uses forward slashes. Hence if you are working with a file, the
default path for the file in case of Windows OS will have backward slashes, which you will
have to convert to forward slashes to make them work in your python script.

For window's path C:\folderA\folderB relative python program path should be


C:/folderA/folderB
3. In python, there is no command terminator, which means no semicolon ; or anything.
So if you want to print something as output, all you have to do is:

Introduction to Python Programming


IT 331 Application Development and Emerging Technologies I
print("something")
4. In one line only a single executable statement should be written and the line change act as
command terminator in python. To write two separate executable statements in a single line,
you should use a semicolon; to separate the commands.
5. In python, you can use single quotes double quotes '"' and even triple quotes to represent string
literals.
6. In python, you can write comments in your program using a # at the start. A comment is
ignored while the python script is executed.
7. Line Continuation: To write a code in multiline without confusing the python interpreter, is by
using a backslash \ at the end of each line to explicitly denote line continuation. Expressions
enclosed in ( ), [ ] or { } brackets don't need a backward slash for line continuation.
8. Blank lines in between a program are ignored by python.
9. Code Indentation: This is the most important rule of python programming. In programming
language like Java, C or C++, generally curly brackets { } are used to define a code block, but
python doesn't use brackets, then how does python knows where a particular code block ends.
Well python used indentation for this. It is recommended to use tab for indentation, although
you can use spaces for indentation as well, just keep in mind that the amount of indentation for
a single code block should be same.
So these are some basic rules that you must know so that it becomes easier for us to learn various
concepts of python programming [ CITATION Stu20 13321 ]

Stop Using Semicolons in Pytton


Coming from a C/C++ background, you are used to seeing a lot of semi-colons ; in code. They are
used to represent statement termination. But, Python does not mandate the use of semi-colons for
delimiting statements [ CITATION Cha20 13321 1.
Semi-colons are used only in uncommon situations in Python.

In many popular programming languages, you need to add a semi-colon at the end of every statement.
For example, in C++:
int c = 10; int a = 5; cout <<"ln C++, semicolon
at the end is must";
In Python, a statement ends at the end of a line (exception for open brackets, quotes or parentheses).
For example:

c = 10

print( I No semicolons in Python')

Staement Separabrs
A semi-colon in Python denotes separation, rather than termination. It allows you to write multiple
statements on the same line [ CITATION Cha20 13321 ].
print(I Statement 1'); printCStatement 2'); print('Statement 3')
Introduction to Python Programming
IT 331 Application Development and Emerging Technologies I
This syntax also makes it legal to put a semicolon at the end of a single statement:
print('New Learnings for Mel );

This statement means print('...') and then do nothing. So, it's actually two statements where the second
one is empty [ CITATION Cha20 13321 1.
Even though the language allows a semi-colon for delimiting statements, most Python programmers
would have never used it in their code[ CITATION Cha20 13321 ]

Display the Output


A built-in function printo serves as an output statement in Python. It echoes the value of any Python
expression on the Python shell.

printCHeIlo World") printCThis is your


first python program"
Multiple values can be displayed by the single print() function separated by comma. print(... ,
print("hello", "world")

The output of the print() function always ends by a newline character. The print() function has
another optional parameter end, whose default value is "\n". This value can be substituted by any
other character such as a single space I ) to display the output of the subsequent print() statement in
the same line [ CITATION Stu20 13321 ].
Ill. I€ywords and Identifier
Python ICywords
Keywords are the reserved words in Python. We cannot use a keyword as a variable name, function
name or any other identifier. They are used to define the syntax and structure of the Python language
[ CITATION Pr020 13321 1.
In Python, keywords are case sensitive. There are 33 keywords in Python 3. All the keywords except
Tue, &lse and None are in lowercase and they must be written as they are. The list of all the keywords
is given below [ CITATION Pr020 13321 ].

False await else import pass

None break except in raise

Tue class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif or yield


Python Identifiers
Introduction to Python Programming
IT 331 Application Development and Emerging Technologies I
An idenåfier is a name given to entities like class, functions, variables, etc. It helps to differentiate one
entity from another [ CITATION Pr020 13321 ]. Variable name is known as identifier.
Rules for writing identifiers
1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0
to 9) or an underscore _. Names like myClass, var_l and print_this_to_screen, all are valid
example.
2. An identifier cannot start with a digit. Ivariable is invalid, but variablel is a valid name.
3. Keywords cannot be used as identifiers.
4. Identifier is case sensitive in Python which means num and NUM are two different variables in
python.
5. We cannot use special symbols like !, @, # , $, % etc. in our identifier
6. An identifier can be of any length.

Python Statemene and ö(pressions


A setement is an instruction that the Python interpreter can execute. For example, a = 1 is an
assignment statement. if statement, for statement, while statement, etc. are other kinds of
statements which will be discussed later.

By default, the Python interpreter treats a piece of text terminated by hard carriage return (new line
character) as one statement. It means each line in a Python script is a statement. (Just as in C/C+
+/C#, a semicolon ; denotes the end of a statement).

An expression is a combination of values, variables, operators and calls to functions. Expressions need
to be evaluated.

sample 1

World"
code—123
name="Steve"

Multi-line statement
In Python, the end of a statement is marked by a newline character. But we can make a statement
extend over multiple lines with the line continuation character (\). For example:
numbers

Introduction to Python Programming


IT 331 Application Development and Emerging Technologies I

7+8+9
This is an explicit line continuation. In Python, line continuation is implied inside parentheses ( ),
brackets [ ], and braces { }. For instance, we can implement the above multi-line statement as:

numbers = (1 + 2 + 3 +

colors - — ['red',
'blue',
'green']

We can also put multiple statements in a single line using semicolons, as follows:

math = 93; english = 92; science = 88

Python Indenbtion
Most of the programming languages like C, C++, and Java use braces { } to define a block of code.
Python, however, uses indentation [ CITATION Pr020 13321 ]. 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, which is rigidly enforced [ CITATION Tut201 13321 ].
if True:
print "True"
else:
print "False"

However, the following block generates an error


— if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"

Introduction to Python Programming


IT 331 Application Development and Emerging Technologies I
Quottion in P)åon
Python string functions are very popular. There are two ways to represent strings in python. String is
enclosed either with single quotes or double quotes. Both the ways (single or double quotes) are correct
depending upon the requirement. Sometimes we have to use quotes (single or double quotes) together
in the same string, in such cases, we use single and double quotes alternatively so that they can be
distinguished [ CITATION Gee19 13321 ].
Sample 1
l
#Gives Error print(
lt's new to me')

Explanation
It gives an invalid syntax error. Because single quote after "it" is considered as the end of the string and
rest part is not the part of a string. It can be corrected as:

new to me")

Sample 2
If you want to print 'WithQuotes' in python, this can't be done with only single (or double) quotes
alone, it requires simultaneous use of both.

# this code prints the output within quotes. #


print WithQuotes within single quotes

print("Hello 'Python'")

# print WithQuotes within single quotes


I
print("'WithQuotes'") print( Hello
"Python'")

Output
'WithQuotes'
Hello 'Python'
"WithQuotes"
Hello "Python"

Conclusion

Introduction to Python Programming


IT 331 Application Development and Emerging Technologies I
The choice between both the types (single quotes and double quotes) depends on the programmer's
choice. Generally, double quotes are used for string representation and single quotes are used for
regular expressions, dict keys or SQL. Hence both single quote and double quotes depict string in
python but it's sometimes our need to use one type over the other [ CITATION Gee19 13321 ].

IV. P}åon Variable


In C++ you have learned that in creating a variable you need to define its datatype. But in Python it
different, Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable [ CITATION Tut20 13321 ]. The equal
sign (=) is used to assign values to variables just like in C++ the only difference is that in Python, you
don't need to define the datatype.
Example

name = "Tony Stark" # string variable declaration number


= 35254 # integer variable declaration pie = 3.14 # float
variable declaration print(name) print(number) print(pie)

In this example, "Tony Stark", 35254 and 3.14 are the values assigned to name, number, and pie
variables, respectively. This produces the following result — Tony Stark
35254
3.14

Assigning multiple values to multiple variables

a, b, c = 5, 3.2, "Hello"
print (a) print (b) print
(c)

If we want to assign the same value to multiple variables at once, we can do this as:
x = y = z = "Python"
print (x) print (y)
print (z)
Wherein x,y and z variables will have the Python as their value.

Getöng the User's Input


The input() function is a part of the core library of standard Python distribution. It reads the key strokes
as a string object which can be referred to by a variable having a suitable name.
name = input("Enter your Name")
print(name)

Introduction to Python Programming


IT 331 Application Development and Emerging Technologies I
In the above example, the input() function takes the user's input from the next line. input() will capture
it and assign it to a name variable. The name variable will display whatever the user has provided as the
input.

The input() function always reads the input as a string, even if comprises of digits. To be able to
convert sting input into integer or float input use int() or float() respectively.

Example numl = input("Enter Number: ")


num2 = input("Another:
ans = numl + num2 print("Total
is: ans)

Output
Enter Number: 5 # if the user entered 5
Another: 3 # if the user entered 3
Total is 53

öQIanation
The input() function always reads the input as a string, since we used a plus sign (+) it just concatenate
or combine the integer input that is why it returns 53 instead of 8. To solve this problem we need to use
int() method. The int() method returns an integer object from any number or string. Place the input()
inside the int() to be able to convert the string to integer.
Example numl = int(input("Enter Number: "))
num2 = int(input("Another:
ans = numl + num2 print("Total
is: ans)
Output
Enter Number : 5 # if the user entered 5
Another : 3 # if the user entered 3
Total is 8

Explanation
In this example, we have utilized the int() method. First we place the input() method inside the int() to
be able to convert the string value into an integer. With this, any integer input will now be treated as
integer instead of string. Since the input are integer operators can perform its rightful functions.

This process can be also used in float() method.

V. Python Datatype
Data types are the classification or categorization of data items. Data types represent a kind of value
which determines what operations can be performed on that data. Numeric, non-numeric and Boolean

Introduction to Python Programming


IT 331 Application Development and Emerging Technologies I
(true/false) data are the most used data types. However, each programming language has its own
classification largely reflecting its programming philosophy [ CITATION Pr020 13321 1.

Built-in Datatype for Python


Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set '1Ypes: set, frozenset

Boolean IYpe: bool


bytes, bytearray,
Binaty Types:
memoryview
Numeric
A numeric value is any representation of data which has a numeric value. Python identifies three types
of numbers [ CITATION Pr020 13321
Integer: Positive or negative whole numbers (without a fractional part)
Float: Any real number with a floating point representation in which a fractional component is
denoted by a decimal symbol or scientific notation
Complex number: A number with a real and imaginary component represented as x+yj.
x and y are floats and j is -I(square root of -1 called an imaginary number)

Boolean
Data with one of two built-in values True or False. Notice that 'T' and 'F' are capital. true and false are
not valid booleans and Python will throw an error for them [ CITATION Pr020 13321 ].

Sequence Wpe
A sequence is an ordered collection of similar or different data types. Python has the following built-in
sequence data types [ CITATION Pr020 13321 ]:
String: A string value is a collection of one or more characters put in single, double or triple
quotes.
List : A list object is an ordered collection of one or more data items, not necessarily of
the same type, put in square brackets.
Tuple: A Tuple object is an ordered collection of one or more data items, not necessarily
of the same type, put in parentheses.

Dictionary
A dictionary object is an unordered collection of data in a key:value pair form. A collection of
such pairs is enclosed in curly brackets [ CITATION Pr020 13321 ]. For example: {1:"Steve",
2: "Tony", 3: "Thor", 4: "Flint"}
Introduction to Python Programming
IT 331 Application Development and Emerging Technologies I
type() Function
Python has an in-built function 9epe() to ascertain the data type of a certain value [ CITATION
Pr020 13321 ]. To be able to get the data type of any object use type() function
Example

print(type(x)
Python Operators
Setting Specific Data Type
greetings = str("Hello World") str
numl = int(20) int
fl_numl = float(20.5) float
x = complex(lj) complex
mylist = list(("apple", "banana", "cherry")) list
mytuple = tuple(("apple", "banana", "cherry")) tuple
myRange = range(6) range
dic_l = dict(name="John", age=36) dict
x set = set(("apple", "banana", "cherry")) set
y_set = frozenset(("apple", "banana", "cherry")) frozenset
myBool = bool(5) bool
xbytes = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
VI. Python Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators

Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common mathematical operations
Operator Name Example
Addition

Subtraction

Introduction to Python Programming


IT 331 Application Development and Emerging Technologies I
Multiplication

Division

Modulus
Exponentiation

Floor division
#the floor division // rounds the result down to the nearest whole number

Python Assignment Operators


Assignment operators are used to assign values to variables:
Operator Sample Same As

x = x//
3
x x

x=x13

x=x
A3
3 x=x
>> 3
x=X
<< 3
Python Comparison Operators
Comparison operators are used to compare two values:
Introduction to Python Programming
IT 331 Application Development and Emerging Technologies I
Operator Name Sample
Equal x =— y
Not equal

Greater than

Less than

Greater than or equal to


Less than or equal to

Equal
Python Logical Operators
Logical operators are used to combine conditional statements:
Opetator Descripdon Sample
Returns True if both statements
and x < 5 and x < 10
are true
Returns True if one of the
or
statements is true
x < 5 or x < 4
Reverse the result, returns False
not not(x < 5 and x < 10)
if the result is true
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location:
Operator Descripton Sample
Returns True if both variables are
the same ob•ect
x is y
Returns True if both variables are
Is not
not the same ob•ect
x is not y
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Operator Descripdon Sample
Returns True if a sequence with
in the specified value is present in x in y
the ob'ect
Returns True if a sequence with
not in the specified value is not present x not in y
in the ob•ect
Python BiW•8ise Operators
Bitwise operators are used to compare (binary) numbers:
Operator Description Sample
AND Sets each bit to 1 if both bits are 1
Introduction to Python Programming
IT 331 Application Development and Emerging Technologies I

OR Sets each bit to 1 if one of two bits is 1

XOR Sets each bit to 1 if only one of two bits is 1

NOT Inverts all the bits


Shift left by pushing zeros in from the right and
Zero fill left shift
let the leftmost bits fall off
Shift right by pushing copies of the leftmost bit in
Signed right shift
from the left, and let the rightmost bits fall off

ActMty

Download and Insell Thonny IDE www.thonny.org/.


Create an account on repl.it https://repl.it/

Watch

Python for Beginners https://www.youtube.com/playlist?


list=PLlrxDOHtieHhS8VzuMCfQD4uJ9yne1mE6

Python TUtoriaI for Beginners https://www.youtube.com/playlist?


list=PLsyeobzWx17poL9JTVyndKe62ieoN-MZ3

Assessment
Create a simple python program that will do the following: Get the name of the user, get a number and
get another number. After getting the name and two numbers it will perform an arithmetic operation
using all the Python Arithmetic Operators. For the output, it will show the entered name, two numbers
and the total for each operation.
Output
What is your name? #inpUt
Enter Number #inpUt
Another #input
Hello "Name" #output
#if the user enter 5 and 4 respectively
5 -4 = 1
#continue until you have used all the arithmetic operators

Introduction to Python Programming


IT 331 Application Development and Emerging Technologies I
[1] Guru99, "Python Tutorials for Beginners," October 16 2020. [Online]. Available:
https://www.guru99.com/. [Accessed 2020 October 2020].

[2] T. Points, "Python Tutorial," 2020. [Online]. Available: https://www.tutorialspoint.com/. [Accessed


21 October 2020].

[3] Programiz, "Python Introduction," 2020. [Online]. Available: https://www.programiz.com/.


[Accessed 21 October 2020].

[4] Wikipedia, "Python syntax and semantics," 2020.


[5] StudyTonight, "Basic Syntax and Hello World! program in Python," [Online]. Available:
https://www.studytonight.com/. [Accessed 29 October 2020].

[6] C. Baweja, "Stop Using Semicolons in Python," 28 May 2020. [Online]. Available:
https://towardsdatascience.com/. [Accessed 28 October 2020].
[7] T. Points, "Python - Basic Syntax," [Online]. Available: https://www.tutorialspoint.com. [Accessed
22 10 2020].

[8] G. f. Geeks, "Single and Double Quotes I Python," 14 July 2019. [Online]. Available:
https://www.geeksforgeeks.org/. [Accessed 28 October 2020].

Introduction to Python Programming

You might also like