Module 1 Introduction To Python Programming: Information and Communication Technology
Module 1 Introduction To Python Programming: Information and Communication Technology
Module 1
Python Programming
Introduction
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.
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.
5. Then Go to Run > Run current saipt or simply click F5 to run it.
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
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 ]
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 ].
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
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:
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"
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.
print("Hello 'Python'")
Output
'WithQuotes'
Hello 'Python'
"WithQuotes"
Hello "Python"
Conclusion
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
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.
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.
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.
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
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
Subtraction
Division
Modulus
Exponentiation
Floor division
#the floor division // rounds the result down to the nearest whole number
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
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
ActMty
Watch
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
[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].