0% found this document useful (0 votes)
4 views40 pages

Lecture 1 CSM 1205

The document provides an introduction to Python programming, covering its history, uses, and advantages such as its simple syntax and cross-platform compatibility. It details Python's features, including variable assignment, data types, and the importance of indentation and comments in code. Additionally, it compares Python 2 and 3, discusses installation, and explains how to execute Python syntax and manage variables.

Uploaded by

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

Lecture 1 CSM 1205

The document provides an introduction to Python programming, covering its history, uses, and advantages such as its simple syntax and cross-platform compatibility. It details Python's features, including variable assignment, data types, and the importance of indentation and comments in code. Additionally, it compares Python 2 and 3, discusses installation, and explains how to execute Python syntax and manage variables.

Uploaded by

jonson233233
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Python Programming

Md Nagrul Islam
Lecturer
Department of Computer Science and Mathematics
Mymensingh Engineering College, Mymensingh, Bangladesh
Contents.

Introduction to Python
What is Python

Python is a popular programming language. It was created by


Guido van Rossum, and released in 1991.

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

In Python 2, print is In Python 3, print is


“Print” Keyword considered to be a statement considered to be a function
and not a function. and not a statement.

In Python 3, strings are


In Python 2, strings are
Storage of Strings stored as UNICODE by
stored as ASCII by default.
default.

On the division of two On the division of two


integers, we get an integral integers, we get a floating-
Division of Integers value in Python 2. For point value in Python 3. For
instance, 7/2 yields 3 in instance, 7/2 yields 3.5 in
Python 2. Python 3.
Python Getting Started

Python Install

Many PCs and Macs will have python already installed.


To check if you have python installed on a Windows PC, search in the start bar for
Python or run the following on the Command Line (cmd.exe):

C:\Users\Your Name>python --version


C:\Users\Your Name>python --version
To check if you have python installed on a Linux or Mac, then on linux open the
command line or on Mac open the Terminal and type:

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

Execute Python Syntax

As we learned in the previous page, Python syntax can be


executed by writing directly in the Command Line:

>>> print("Hello, World!")


Hello, World!
Or by creating a python file on the server, using the .py file
extension, and running it in the Command Line:

C:\Users\Your Name>python myfile.py


Python Indentation

Indentation refers to the spaces at the beginning of a code line.


Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.
Example:
if 5 > 2:
print("Five is greater than two!")
Output:Five is greater than two!

Python will give you an error if you skip the indentation:


Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
The number of spaces is up to you as a programmer, the most common
use is four, but it has to be at least one.
Python Indentation

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

Comments can be used to explain Python code.


Comments can be used to make the code more
readable.
Comments can be used to prevent execution
when testing code.
Creating a Comment:

Comments starts with a #, and Python will


ignore them:
Example
#This is a comment
print("Hello, World!")
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

Variables are containers for storing data values.


Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example
x = 5
y = "John"
print(x)
print(y)
Try it Yourself »
Variables do not need to be declared with any particular type, and can even change type after
they have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Try it Yourself »
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0

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).

Rules for Python variables:

.A variable name must start with a letter or the underscore character


• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _
)
• Variable names are case-sensitive (age, Age and AGE are three different variables)
Example
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Try it Yourself »
Example
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"

Try it Yourself »
Python Variables - Assign Multiple
Values

Python allows you to assign values to multiple variables in one line:


Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Try it Yourself »
Note: Make sure the number of variables matches the number of values, or else you will get
an error.
One Value to Multiple Variables
And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Try it Yourself »
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values
into variables. This is called unpacking.
Example
Unpack a list:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Python - Output Variables

The Python print() function is often used to output variables.


Example
x = "Python is awesome"
print(x)
In the print() function, you output multiple variables, separated by a comma:
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
You can also use the + operator to output multiple variables:
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Notice the space character after "Python " and "is ", without them the result would be
"Pythonisawesome".
For numbers, the + character works as a mathematical operator
x = 5
y = 10
print(x + y)
In the print() function, when you try to combine a string and a number with the + operator, Python will
give you an error:
Example
x = 5
y = "John"
print(x + y)
The best way to output multiple variables in the print() function is to separate them with commas,
which even support different data types:
x = 5
y = "John"
Python - Global Variables

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

Getting the Data Type


You can get the data type of any object by using
the type() function:
Example
Print the data type of the variable x:
x = 5
print(type(x))
Output:
<class 'int'>

Setting the Data Type


In Python, the data type is set when you assign a value to a variable:
Python Data Types

Example Data Type


x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", list
"cherry"]
x = ("apple", "banana", tuple
"cherry")
x = range(6) range
x = {"name" : "John", "age" : dict
36}
x = {"apple", "banana", set
"cherry"}
x = frozenset({"apple", frozenset
"banana", "cherry"})
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
Python Data Types
□ If you want to specify the data type, you can use
the following constructor functions:

Example Data Type


x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", list
"cherry"))
x = tuple(("apple", "banana", tuple
"cherry"))
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", set
"cherry"))
x = frozenset(("apple", frozenset
"banana", "cherry"))
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
Python Numbers

There are three numeric types in Python:


Int float complex
Variables of numeric types are created when you assign a value to them:
Example
x=1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

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

Specify a Variable Type


There may be times when you want to specify a type on to a variable. This
can be done with casting. Python is an object-orientated language, and as
such it uses classes to define data types, including its primitive types.
Casting in python is therefore done using constructor functions:

• int() - constructs an integer number from an integer literal, a float literal


(by removing all decimals), or a string literal (providing the string
represents a whole number)

• float() - constructs a float number from an integer literal, a float literal or


a string literal (providing the string represents a float or an integer)

• str() - constructs a string from a wide variety of data types, including


strings, integer literals and float literals
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

Strings in python are surrounded by either single quotation marks, or


double quotation marks.
'hello' is the same as "hello".

You can display a string literal with the print() function:


print("Hello") print('Hello')
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by
an equal sign and the string:
Example
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using (Single or
Double)three quotes:

Example
You can use three double quotes:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
Python - Slicing Strings

You can return a range of characters by using the slice syntax.


Specify the start index and the end index, separated by a colon, to return a
part of the string.
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Output:
llo
Note: The first character has index 0.
slice From the Start
By leaving out the start index, the range will start at the first character:
Example
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
Output:Hello
Python - Slicing Strings

Slice To the End


By leaving out the end index, the range will go to the end:
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Output:
llo, World!

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

To concatenate, or combine, two strings you can use the + operator.


Example
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c = a + b
print(c)
Try it Yourself »
Example
To add a space between them, add a " ":
a = "Hello"
b = "World"
c = a + " " + b
print(c)
Python - Format - Strings

As we learned in the Python Variables chapter, we cannot combine strings


and numbers like this:
Example
age = 36
txt = "My name is John, I am " + age
print(txt)
Try it Yourse
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and places
them in the string where the placeholders {} are:
Example
Use the format() method to insert numbers into strings:
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
Try it Yourself
Python - Format - Strings

The format() method takes unlimited number of arguments, and


are placed into the respective placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
Try it Yourself »
You can use index numbers {0} to be sure the arguments are
placed in the correct placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item
{1}."
print(myorder.format(quantity, itemno, price))
Python - Escape Characters

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

Python has a set of built-in methods that you can use on


strings.
Note: All string methods return new values. They do not
change the original string

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

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

Returns True if all characters in the string are alphanumeric

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

isdigit() Returns True if all characters in the string are digits

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

Returns True if all characters in the string are lower case

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

Returns True if all characters in the string are whitespaces

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

Joins the elements of an iterable to the end of the string

split()
ljust()

lower()
Splits the string at the specified separator, and returns a list
Returns a left justified version of the string

Converts a string into lower case

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

You might also like