Lecture 1 CSM 1205
Lecture 1 CSM 1205
Md Nagrul Islam
Lecturer
Department of Computer Science and Mathematics
Mymensingh Engineering College, Mymensingh, Bangladesh
Contents.
Introduction to Python
What is Python
It is used for:
• web development (server-side),
• software development,
• mathematic
• system scripting.
Python IDE:
PC(Pycharm), spyder,jupyter, Thonny, Netbeans
or Eclipse
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.
Version 2 VS 3
Python Install
python --version
python --version
If you find that you do not have Python installed on your computer, then you can
download it for free from the following website: https://www.python.org/
Python Syntax
Example
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
Try it Yourself
You have to use the same number of spaces in the same block of code,
otherwise Python will give you an error:
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Try it Yourself »
Python Comments
Try it Yourself
Comments can be placed at the end of a line,
and Python will ignore the rest of the line:
Example
print("HellAo, World!") #This is a comment
Try it Yourself »
A comment does not have to be text that
explains the code, it can also be used to
prevent Python from executing code:
Example
#print("Hello, World!")
print("Cheers, Mate!")
Python Variables
Try it Yourself »
Python - Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Try it Yourself »
Python Variables - Assign Multiple
Values
Global Variables
Variables that are created outside of a function (as in all of the
examples above) are known as global variables.
Global variables can be used by everyone, both inside of
functions and outside.
Example
Create a variable outside of a function, and use it inside the
function
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Output:Python is awesome
Python - Global Variables
If you create a variable with the same name inside a function, this variable
will be local, and can only be used inside the function. The global variable
with the same name will remain as it was, global and with the original
value.
Example
Create a variable inside a function, with the same name as the global
variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
Output:
Python is fantastic
Python is awesome
Python Data Types
Example
Integers:
x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'int'>
<class 'int'>
<class 'int'>
Python Numbers
Float
Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
Example
Floats:
x = 1.10 y = 1.0 z = -35.59
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'float'>
<class 'float'>
<class 'float'>
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example
Floats:
x = 35e3 y = 12E4 z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'float'>
<class 'float'>
<class 'float'>
Python Numbers
Float
Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
Example
Floats:
x = 1.10 y = 1.0 z = -35.59
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'float'>
<class 'float'>
<class 'float'>
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example
Floats:
x = 35e3 y = 12E4 z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'float'>
<class 'float'>
<class 'float'>
Python Casting
Example
Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Example
Floats:
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
TrYourself »
Example
Strings:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Try it Yourself »
Python Strings
Example
You can use three double quotes:
Negative Indexing
Use negative indexes to start the slice from the end of the
string:Example
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print(b[-5:-2])
Output:
orl
Python - Modify Strings
Python has a set of built-in methods that you can use on strings.
Upper Case
Example
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
Try it Yourself »
Lower Case
Example
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
Try it Yourself »
Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often
you want to remove this space.
Example
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
Try it Yourself
Python - Modify Strings
Replace String
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
Jello, World!
Split String
The split() method returns a list where the text between the specified
separator becomes the list items.
Example
The split() method splits the string into substrings if it finds instances of the
separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Output
Output:['Hello', ' World!']
String Concatenation
Escape Character
To insert characters that are illegal in a string, use an escape
character.
An escape character is a backslash \ followed by the character you
want to insert.
An example of an illegal character is a double quote inside a string
that is surrounded by double quotes:
Example
You will get an error if you use double quotes inside a string that is
surrounded by double quotes:
txt = "We are the so-called "Vikings" from the north."
Try it Yourself »
To fix this problem, use the escape character \":
Example
The escape character allows you to use double quotes when you
normally would not be allowed:
txt = "We are the so-called \"Vikings\" from the north."
Python - Escape Characters
Escape Characters
Other escape characters used in Python:
Code Result
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value
Python - String Methods
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value
occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the
specified value
expandtabs() Sets the tab size of the string
Python - String Methods
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map( Formats specified values in a string
)
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
Python - String Methods
find() Searches the string for a specified value and returns the position of where it was found
maketrans()
format()
format_map()
Returns a translation table to be used in translations
Formats specified values in a string
partition()
index()
isalnum()
Returns a tuple where the string is parted into three parts
Searches the string for a specified value and returns the position of where it was found
replace()
isalpha() Returns a string where a specified value is replaced with a specified value
Returns True if all characters in the string are in the alphabet
rfind() Searches the string for a specified value and returns the last position of where it was found
isdecimal() Returns True if all characters in the string are decimals
rindex()
isidentifier()
islower()
Searches the string for a specified value and returns the last position of where it was found
Returns True if the string is an identifier
rjust()
isnumeric() Returns a right justified version of the string
Returns True if all characters in the string are numeric
rpartition()
isprintable()
isspace()
Returns a tuple where the string is parted into three parts
Returns True if all characters in the string are printable
rsplit()
istitle() Splits the string at the specified separator, and returns a list
Returns True if the string follows the rules of a title
rstrip()
isupper()
join()
Returns a right trim version of the string
Returns True if all characters in the string are upper case
split()
ljust()
lower()
Splits the string at the specified separator, and returns a list
Returns a left justified version of the string
splitlines()
lstrip()
Splits the string at line breaks and returns a list
Returns a left trim version of the string
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning