SlideShare a Scribd company logo
Python Programming
Workshop
Pramote Kuacharoen
Topics
 Expressions, operators, precedence, control flows, functions
 Input/output
 List
 Classes and Objects
2
The Python Interpreter
 Python is an interpreted language
 Commands are executed through the Python interpreter
 A programmer defines a series of commands in advance and saves those
commands in a text file known as source code or a script.
 For Python, source code is conventionally stored in a file named with the .py
suffix (e.g., demo.py)
3
Writing a Simple Program
 Algorithm for calculating the area of a square
 Obtain the width from the user
 Computer the area by applying the following formula
 𝒂𝒓𝒆𝒂 = 𝒘𝒊𝒅𝒕𝒉 ∗ 𝒘𝒊𝒅𝒕𝒉
 Display the result
4
Reading Input from the Console
 Use the input function to obtain a string
 variable = input(‘Enter width : ’)
 Use the eval function to evaluate expression
 variable = eval(string_variable)
 Combination
 width = eval(input(‘Enter width : ’))
5
Calculating Square Area
width = eval(input('Enter width : '))
area = width * width
print('Area is ', area)
6
Identifiers
 Identifiers in Python are case-sensitive, so temperature and Temperature are
distinct names.
 Identifiers can be composed of almost any combination of letters, numerals,
and underscore characters.
 An identifier cannot begin with a numeral and that there are 33 specially
reserved words that cannot be used as identifiers:
7
Types
 Python is a dynamically typed language, as there is no advance declaration
associating an identifier with a particular data type.
 An identifier can be associated with any type of object, and it can later be
reassigned to another object of the same (or different) type.
 Although an identifier has no declared type, the object to which it refers has
a definite type. In our first example, the characters 98.6 are recognized as a
floating-point literal, and thus the identifier temperature is associated with
an instance of the float class having that value.
8
Numerical Data Types ad Numeric
Operators
 integer: e.g., 3, 4
 float: e.g., 3.0, 4.0
Name Meaning Example Result
+ Addition 34 + 1 35
- Subtraction 34.0 – 0.1 33.9
* Multiplication 300 * 30 9000
/ Float Division 1 / 2 0.5
// Integer Division 1 // 2 0
** Exponentiation 4 ** 0.5 2.0
% Remainder 20 % 3 2
9
Boolean Data Types
 Often in a program you need to compare two values, such as whether i is
greater than j
 There are six comparison operators (also known as relational operators) that
can be used to compare two values
 The result of the comparison is a Boolean value: true or false
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
10
String
 Sequence of characters that is treated as a single item
 Written as a sequence of characters surrounded by either single quotes (') or
double quotes (")
 Position or index of a character in a string
 Identified with one of the numbers 0, 1, 2, 3, . . . .
11
List
12
list1 = list() # Create an empty list
list2 = list([2, 3, 4]) # Create a list with elements 2, 3, 4
list3 = list(["red", "green", "blue"]) # Create a list with strings
list4 = list(range(3, 6)) # Create a list with elements 3, 4, 5
list5 = list("abcd") # Create a list with characters a, b, c
list1 = [] # Same as list()
list2 = [2, 3, 4] # Same as list([2, 3, 4])
list3 = ["red", "green"] # Same as list(["red", "green"])
append(x: object): None
insert(index: int, x: object): None
remove(x: object): None
index(x: object): int
count(x: object): int
sort(): None
reverse(): None
extend(l: list): None
pop([i]): object
List Is a Sequence Type
13
Operation Description
x in s True if element x is in sequence s
x not in s True if element x is not in sequence s
s1 + s2 Concatenates two sequences s1 and s2
s * n, n * s n copies of sequence s concatenated
s[i] ith element in sequence s
s[i : j] Slice of sequence s from index i to j - 1
len(s) Length of sequence s, i.e., the number of elements in s
min(s) Smallest element in sequence s
max(s) Largest element in sequence s
sum(s) Sum of all numbers in sequence s
for loop Traverses elements from left to right in a for loop
<, <=, >, >=, ==, != Compares two sequences
if Statement
14
if width > 0:
area = width * width
if Boolean-expression:
statement(s)
if-else Statement
15
if width > 0:
area = width * width
else:
print(‘width must be positive’)
if Boolean-expression:
statement(s) for the true case
else:
statement(s) for the false case
Multiple Alternative for if Statements
16
if score >= 90.0:
grade = 'A'
elif score >= 80.0:
grade = 'B'
elif score >= 70.0:
grade = 'C'
elif score >= 60.0:
grade = 'D'
else:
grade = 'F'
if score >= 90.0:
grade = 'A'
else:
if score >= 80.0:
grade = 'B'
else:
if score >= 70.0:
grade = 'C'
else:
if score >= 60.0:
grade = 'D'
else:
grade = 'F'
Logical Operators
17
Operator Description
not Logical negation
and Logical conjunction
or Logical disjunction
(year % 4 == 0 and year % 100 != 0) or year % 400 == 0)
A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400.
Conditional Operator
18
y = 1 if x > 0 else -1if x > 0:
y = 1
else:
y = -1
if num % 2 == 0:
print(str(num) + “is even”)
else:
print(str(num) + “is odd”);
print("number is even" if (number % 2 == 0)
else "number is odd")
Operator Precedence
 +, - unary
 **
 not
 *, /, //, %
 +, -
 <, <=, >, >=
 ==, !=
 and
 or
 =, +=, -=, *=, /=, //=, %= (Assignment operator)
19
Loops
20
for i in range(1, 6):
print (i)
num = 1
while num <= 5:
print(num)
num += 1
while conditions:
indented block of statements
for var in sequence:
indented block of statements
Functions
 Functions can be used to define reusable code and organize and simplify code
21
def sum_range(a, b):
result = 0
for i in range(a, b+1):
result += i
return result
def main():
print('Sum from 1 to 10 is ', sum_range(1, 10));
print('Sum from 50 to 100 is ', sum_range(50, 100));
main()
def function_name(list of parameters):
# Function body
Reading Input from Text Files
22
continent = input('Enter the name of a continent : ')
continent = continent.title()
if continent != 'Antarctica':
infile = open('UN.txt', 'r')
for line in infile:
data = line.split(',')
if data[1] == continent:
print(data[0])
else:
print('There are not countries in Antarctica.')
infile = open(‘Filename’, ‘r’)
List Comprehension
23
list1 = [x for x in range(5)]
[0, 1, 2, 3, 4]
line = input('Enter series of numbers : ')
text_numbers = line.split(' ')
numbers = [eval(num) for num in text_numbers]
Objects and Classes
 Object-oriented programming enables you to develop large-scale software
and GUIs effectively.
24
class Rectangle:
def __init__(self, width = 1, height = 2):
self._width = width
self._height = height
def area(self):
return self._width * self._height
def perimeter(self):
return 2 * (self._width * self._height)
def main():
r1 = Rectangle(10, 20)
print('The area of the rectangle is : ', r1.area())
print('The perimeter of the rectangle is : ', r1.perimeter())
main()
class ClassName:
initializer
methods

More Related Content

What's hot (20)

Arrays
ArraysArrays
Arrays
Saranya saran
 
Arrays in C language
Arrays in C languageArrays in C language
Arrays in C language
Shubham Sharma
 
Unit ii ppt
Unit ii pptUnit ii ppt
Unit ii ppt
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
 
Lecture 15 - Array
Lecture 15 - ArrayLecture 15 - Array
Lecture 15 - Array
Md. Imran Hossain Showrov
 
DATA TYPE IN PYTHON
DATA TYPE IN PYTHONDATA TYPE IN PYTHON
DATA TYPE IN PYTHON
vikram mahendra
 
function, storage class and array and strings
 function, storage class and array and strings function, storage class and array and strings
function, storage class and array and strings
Rai University
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
Anurag University Hyderabad
 
Memory management of datatypes
Memory management of datatypesMemory management of datatypes
Memory management of datatypes
Monika Sanghani
 
OPERATOR IN PYTHON-PART1
OPERATOR IN PYTHON-PART1OPERATOR IN PYTHON-PART1
OPERATOR IN PYTHON-PART1
vikram mahendra
 
Unit2 input output
Unit2 input outputUnit2 input output
Unit2 input output
deepak kumbhar
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
Mohd Sajjad
 
FLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHONFLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHON
vikram mahendra
 
Array, string and pointer
Array, string and pointerArray, string and pointer
Array, string and pointer
Nishant Munjal
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programming
nmahi96
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
DhivyaSubramaniyam
 
Unit 2
Unit 2Unit 2
Unit 2
TPLatchoumi
 
C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
HNDE Labuduwa Galle
 
Arrays
ArraysArrays
Arrays
fahadshakeel
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
Saranya saran
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
janani thirupathi
 

Similar to Python programming workshop (20)

UNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineeringUNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineering
SabarigiriVason
 
Python
PythonPython
Python
Sangita Panchal
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdf
simenehanmut
 
Python.pdf
Python.pdfPython.pdf
Python.pdf
Shivakumar B N
 
Keep it Stupidly Simple Introduce Python
Keep it Stupidly Simple Introduce PythonKeep it Stupidly Simple Introduce Python
Keep it Stupidly Simple Introduce Python
SushJalai
 
funadamentals of python programming language (right from scratch)
funadamentals of python programming language (right from scratch)funadamentals of python programming language (right from scratch)
funadamentals of python programming language (right from scratch)
MdFurquan7
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)
ssuser7f90ae
 
Algoritmos e Estruturas de Dados - Pointers
Algoritmos e Estruturas de Dados - PointersAlgoritmos e Estruturas de Dados - Pointers
Algoritmos e Estruturas de Dados - Pointers
martijnkuipersandebo
 
C tutorial
C tutorialC tutorial
C tutorial
Anurag Sukhija
 
COM1407: Arrays
COM1407: ArraysCOM1407: Arrays
COM1407: Arrays
Hemantha Kulathilake
 
Array assignment
Array assignmentArray assignment
Array assignment
Ahmad Kamal
 
The Ring programming language version 1.8 book - Part 94 of 202
The Ring programming language version 1.8 book - Part 94 of 202The Ring programming language version 1.8 book - Part 94 of 202
The Ring programming language version 1.8 book - Part 94 of 202
Mahmoud Samir Fayed
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptx
SahajShrimal1
 
made it easy: python quick reference for beginners
made it easy: python quick reference for beginnersmade it easy: python quick reference for beginners
made it easy: python quick reference for beginners
SumanMadan4
 
Computer programming 2 Lesson 10
Computer programming 2  Lesson 10Computer programming 2  Lesson 10
Computer programming 2 Lesson 10
MLG College of Learning, Inc
 
Array
ArrayArray
Array
Vivian Chia En Chiang
 
vb.net.pdf
vb.net.pdfvb.net.pdf
vb.net.pdf
VimalSangar1
 
Introduction to learn and Python Interpreter
Introduction to learn and Python InterpreterIntroduction to learn and Python Interpreter
Introduction to learn and Python Interpreter
Alamelu
 
Introduction to r
Introduction to rIntroduction to r
Introduction to r
Golden Julie Jesus
 
UNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineeringUNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineering
SabarigiriVason
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdf
simenehanmut
 
Keep it Stupidly Simple Introduce Python
Keep it Stupidly Simple Introduce PythonKeep it Stupidly Simple Introduce Python
Keep it Stupidly Simple Introduce Python
SushJalai
 
funadamentals of python programming language (right from scratch)
funadamentals of python programming language (right from scratch)funadamentals of python programming language (right from scratch)
funadamentals of python programming language (right from scratch)
MdFurquan7
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)
ssuser7f90ae
 
Algoritmos e Estruturas de Dados - Pointers
Algoritmos e Estruturas de Dados - PointersAlgoritmos e Estruturas de Dados - Pointers
Algoritmos e Estruturas de Dados - Pointers
martijnkuipersandebo
 
Array assignment
Array assignmentArray assignment
Array assignment
Ahmad Kamal
 
The Ring programming language version 1.8 book - Part 94 of 202
The Ring programming language version 1.8 book - Part 94 of 202The Ring programming language version 1.8 book - Part 94 of 202
The Ring programming language version 1.8 book - Part 94 of 202
Mahmoud Samir Fayed
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptx
SahajShrimal1
 
made it easy: python quick reference for beginners
made it easy: python quick reference for beginnersmade it easy: python quick reference for beginners
made it easy: python quick reference for beginners
SumanMadan4
 
Introduction to learn and Python Interpreter
Introduction to learn and Python InterpreterIntroduction to learn and Python Interpreter
Introduction to learn and Python Interpreter
Alamelu
 
Ad

More from BAINIDA (20)

ดนตรีของพระเจ้าแผ่นดิน อานนท์ ศักดิ์วรวิชญ์ สุรพงษ์ บ้านไกรทอง หอประชุมวปอ 7...
ดนตรีของพระเจ้าแผ่นดิน อานนท์ ศักดิ์วรวิชญ์  สุรพงษ์ บ้านไกรทอง หอประชุมวปอ 7...ดนตรีของพระเจ้าแผ่นดิน อานนท์ ศักดิ์วรวิชญ์  สุรพงษ์ บ้านไกรทอง หอประชุมวปอ 7...
ดนตรีของพระเจ้าแผ่นดิน อานนท์ ศักดิ์วรวิชญ์ สุรพงษ์ บ้านไกรทอง หอประชุมวปอ 7...
BAINIDA
 
Mixed methods in social and behavioral sciences
Mixed methods in social and behavioral sciencesMixed methods in social and behavioral sciences
Mixed methods in social and behavioral sciences
BAINIDA
 
Advanced quantitative research methods in political science and pa
Advanced quantitative  research methods in political science and paAdvanced quantitative  research methods in political science and pa
Advanced quantitative research methods in political science and pa
BAINIDA
 
Latest thailand election2019report
Latest thailand election2019reportLatest thailand election2019report
Latest thailand election2019report
BAINIDA
 
Data science in medicine
Data science in medicineData science in medicine
Data science in medicine
BAINIDA
 
Nursing data science
Nursing data scienceNursing data science
Nursing data science
BAINIDA
 
Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...
Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...
Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...
BAINIDA
 
Statistics and big data for justice and fairness
Statistics and big data for justice and fairnessStatistics and big data for justice and fairness
Statistics and big data for justice and fairness
BAINIDA
 
Data science and big data for business and industrial application
Data science and big data  for business and industrial applicationData science and big data  for business and industrial application
Data science and big data for business and industrial application
BAINIDA
 
Update trend: Free digital marketing metrics for start-up
Update trend: Free digital marketing metrics for start-upUpdate trend: Free digital marketing metrics for start-up
Update trend: Free digital marketing metrics for start-up
BAINIDA
 
Advent of ds and stat adjustment
Advent of ds and stat adjustmentAdvent of ds and stat adjustment
Advent of ds and stat adjustment
BAINIDA
 
เมื่อ Data Science เข้ามา สถิติศาสตร์จะปรับตัวอย่างไร
เมื่อ Data Science เข้ามา สถิติศาสตร์จะปรับตัวอย่างไร เมื่อ Data Science เข้ามา สถิติศาสตร์จะปรับตัวอย่างไร
เมื่อ Data Science เข้ามา สถิติศาสตร์จะปรับตัวอย่างไร
BAINIDA
 
Data visualization. map
Data visualization. map Data visualization. map
Data visualization. map
BAINIDA
 
Dark data by Worapol Alex Pongpech
Dark data by Worapol Alex PongpechDark data by Worapol Alex Pongpech
Dark data by Worapol Alex Pongpech
BAINIDA
 
Deepcut Thai word Segmentation @ NIDA
Deepcut Thai word Segmentation @ NIDADeepcut Thai word Segmentation @ NIDA
Deepcut Thai word Segmentation @ NIDA
BAINIDA
 
Professionals and wanna be in Business Analytics and Data Science
Professionals and wanna be in Business Analytics and Data ScienceProfessionals and wanna be in Business Analytics and Data Science
Professionals and wanna be in Business Analytics and Data Science
BAINIDA
 
Deep learning and image analytics using Python by Dr Sanparit
Deep learning and image analytics using Python by Dr SanparitDeep learning and image analytics using Python by Dr Sanparit
Deep learning and image analytics using Python by Dr Sanparit
BAINIDA
 
Visualizing for impact final
Visualizing for impact finalVisualizing for impact final
Visualizing for impact final
BAINIDA
 
Second prize business plan @ the First NIDA business analytics and data scien...
Second prize business plan @ the First NIDA business analytics and data scien...Second prize business plan @ the First NIDA business analytics and data scien...
Second prize business plan @ the First NIDA business analytics and data scien...
BAINIDA
 
Second prize data analysis @ the First NIDA business analytics and data scie...
Second prize data analysis @ the First NIDA  business analytics and data scie...Second prize data analysis @ the First NIDA  business analytics and data scie...
Second prize data analysis @ the First NIDA business analytics and data scie...
BAINIDA
 
ดนตรีของพระเจ้าแผ่นดิน อานนท์ ศักดิ์วรวิชญ์ สุรพงษ์ บ้านไกรทอง หอประชุมวปอ 7...
ดนตรีของพระเจ้าแผ่นดิน อานนท์ ศักดิ์วรวิชญ์  สุรพงษ์ บ้านไกรทอง หอประชุมวปอ 7...ดนตรีของพระเจ้าแผ่นดิน อานนท์ ศักดิ์วรวิชญ์  สุรพงษ์ บ้านไกรทอง หอประชุมวปอ 7...
ดนตรีของพระเจ้าแผ่นดิน อานนท์ ศักดิ์วรวิชญ์ สุรพงษ์ บ้านไกรทอง หอประชุมวปอ 7...
BAINIDA
 
Mixed methods in social and behavioral sciences
Mixed methods in social and behavioral sciencesMixed methods in social and behavioral sciences
Mixed methods in social and behavioral sciences
BAINIDA
 
Advanced quantitative research methods in political science and pa
Advanced quantitative  research methods in political science and paAdvanced quantitative  research methods in political science and pa
Advanced quantitative research methods in political science and pa
BAINIDA
 
Latest thailand election2019report
Latest thailand election2019reportLatest thailand election2019report
Latest thailand election2019report
BAINIDA
 
Data science in medicine
Data science in medicineData science in medicine
Data science in medicine
BAINIDA
 
Nursing data science
Nursing data scienceNursing data science
Nursing data science
BAINIDA
 
Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...
Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...
Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...
BAINIDA
 
Statistics and big data for justice and fairness
Statistics and big data for justice and fairnessStatistics and big data for justice and fairness
Statistics and big data for justice and fairness
BAINIDA
 
Data science and big data for business and industrial application
Data science and big data  for business and industrial applicationData science and big data  for business and industrial application
Data science and big data for business and industrial application
BAINIDA
 
Update trend: Free digital marketing metrics for start-up
Update trend: Free digital marketing metrics for start-upUpdate trend: Free digital marketing metrics for start-up
Update trend: Free digital marketing metrics for start-up
BAINIDA
 
Advent of ds and stat adjustment
Advent of ds and stat adjustmentAdvent of ds and stat adjustment
Advent of ds and stat adjustment
BAINIDA
 
เมื่อ Data Science เข้ามา สถิติศาสตร์จะปรับตัวอย่างไร
เมื่อ Data Science เข้ามา สถิติศาสตร์จะปรับตัวอย่างไร เมื่อ Data Science เข้ามา สถิติศาสตร์จะปรับตัวอย่างไร
เมื่อ Data Science เข้ามา สถิติศาสตร์จะปรับตัวอย่างไร
BAINIDA
 
Data visualization. map
Data visualization. map Data visualization. map
Data visualization. map
BAINIDA
 
Dark data by Worapol Alex Pongpech
Dark data by Worapol Alex PongpechDark data by Worapol Alex Pongpech
Dark data by Worapol Alex Pongpech
BAINIDA
 
Deepcut Thai word Segmentation @ NIDA
Deepcut Thai word Segmentation @ NIDADeepcut Thai word Segmentation @ NIDA
Deepcut Thai word Segmentation @ NIDA
BAINIDA
 
Professionals and wanna be in Business Analytics and Data Science
Professionals and wanna be in Business Analytics and Data ScienceProfessionals and wanna be in Business Analytics and Data Science
Professionals and wanna be in Business Analytics and Data Science
BAINIDA
 
Deep learning and image analytics using Python by Dr Sanparit
Deep learning and image analytics using Python by Dr SanparitDeep learning and image analytics using Python by Dr Sanparit
Deep learning and image analytics using Python by Dr Sanparit
BAINIDA
 
Visualizing for impact final
Visualizing for impact finalVisualizing for impact final
Visualizing for impact final
BAINIDA
 
Second prize business plan @ the First NIDA business analytics and data scien...
Second prize business plan @ the First NIDA business analytics and data scien...Second prize business plan @ the First NIDA business analytics and data scien...
Second prize business plan @ the First NIDA business analytics and data scien...
BAINIDA
 
Second prize data analysis @ the First NIDA business analytics and data scie...
Second prize data analysis @ the First NIDA  business analytics and data scie...Second prize data analysis @ the First NIDA  business analytics and data scie...
Second prize data analysis @ the First NIDA business analytics and data scie...
BAINIDA
 
Ad

Recently uploaded (20)

Swachata Quiz - Prelims - 01.10.24 - Quiz Club IIT Patna
Swachata Quiz - Prelims - 01.10.24 - Quiz Club IIT PatnaSwachata Quiz - Prelims - 01.10.24 - Quiz Club IIT Patna
Swachata Quiz - Prelims - 01.10.24 - Quiz Club IIT Patna
Quiz Club, Indian Institute of Technology, Patna
 
প্রত্যুৎপন্নমতিত্ব - Prottutponnomotittwa 2025.pdf
প্রত্যুৎপন্নমতিত্ব - Prottutponnomotittwa 2025.pdfপ্রত্যুৎপন্নমতিত্ব - Prottutponnomotittwa 2025.pdf
প্রত্যুৎপন্নমতিত্ব - Prottutponnomotittwa 2025.pdf
Pragya - UEM Kolkata Quiz Club
 
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
RVSPSOA
 
LDMMIA Free Reiki Yoga S7 Weekly Workshops
LDMMIA Free Reiki Yoga S7 Weekly WorkshopsLDMMIA Free Reiki Yoga S7 Weekly Workshops
LDMMIA Free Reiki Yoga S7 Weekly Workshops
LDM & Mia eStudios
 
STUDENT LOAN TRUST FUND DEFAULTERS GHANA
STUDENT LOAN TRUST FUND DEFAULTERS GHANASTUDENT LOAN TRUST FUND DEFAULTERS GHANA
STUDENT LOAN TRUST FUND DEFAULTERS GHANA
Kweku Zurek
 
PHYSIOLOGY & SPORTS INJURY by Diwakar Sir
PHYSIOLOGY & SPORTS INJURY by Diwakar SirPHYSIOLOGY & SPORTS INJURY by Diwakar Sir
PHYSIOLOGY & SPORTS INJURY by Diwakar Sir
Diwakar Kashyap
 
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdfForestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
ChalaKelbessa
 
How to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time OffHow to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time Off
Celine George
 
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.05.28.pdf
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.05.28.pdfTechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.05.28.pdf
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.05.28.pdf
TechSoup
 
CBSE - Grade 11 - Mathematics - Ch 2 - Relations And Functions - Notes (PDF F...
CBSE - Grade 11 - Mathematics - Ch 2 - Relations And Functions - Notes (PDF F...CBSE - Grade 11 - Mathematics - Ch 2 - Relations And Functions - Notes (PDF F...
CBSE - Grade 11 - Mathematics - Ch 2 - Relations And Functions - Notes (PDF F...
Sritoma Majumder
 
How to Manage Orders in Odoo 18 Lunch - Odoo Slides
How to Manage Orders in Odoo 18 Lunch - Odoo SlidesHow to Manage Orders in Odoo 18 Lunch - Odoo Slides
How to Manage Orders in Odoo 18 Lunch - Odoo Slides
Celine George
 
Introduction to Online CME for Nurse Practitioners.pdf
Introduction to Online CME for Nurse Practitioners.pdfIntroduction to Online CME for Nurse Practitioners.pdf
Introduction to Online CME for Nurse Practitioners.pdf
CME4Life
 
THE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATION
THE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATIONTHE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATION
THE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATION
PROF. PAUL ALLIEU KAMARA
 
LDMMIA Bonus GUEST GRAD Student Check-in
LDMMIA Bonus GUEST GRAD Student Check-inLDMMIA Bonus GUEST GRAD Student Check-in
LDMMIA Bonus GUEST GRAD Student Check-in
LDM & Mia eStudios
 
Writing Research Papers: Guidance for Research Community
Writing Research Papers: Guidance for Research CommunityWriting Research Papers: Guidance for Research Community
Writing Research Papers: Guidance for Research Community
Rishi Bankim Chandra Evening College, Naihati, North 24 Parganas, West Bengal, India
 
Uterine Prolapse, causes type and classification,its managment
Uterine Prolapse, causes type and classification,its managmentUterine Prolapse, causes type and classification,its managment
Uterine Prolapse, causes type and classification,its managment
Ritu480198
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
Types of Actions in Odoo 18 - Odoo Slides
Types of Actions in Odoo 18 - Odoo SlidesTypes of Actions in Odoo 18 - Odoo Slides
Types of Actions in Odoo 18 - Odoo Slides
Celine George
 
Order Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptxOrder Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptx
Arshad Shaikh
 
Pragya Champion's Chalice 2025 Set , General Quiz
Pragya Champion's Chalice 2025 Set , General QuizPragya Champion's Chalice 2025 Set , General Quiz
Pragya Champion's Chalice 2025 Set , General Quiz
Pragya - UEM Kolkata Quiz Club
 
প্রত্যুৎপন্নমতিত্ব - Prottutponnomotittwa 2025.pdf
প্রত্যুৎপন্নমতিত্ব - Prottutponnomotittwa 2025.pdfপ্রত্যুৎপন্নমতিত্ব - Prottutponnomotittwa 2025.pdf
প্রত্যুৎপন্নমতিত্ব - Prottutponnomotittwa 2025.pdf
Pragya - UEM Kolkata Quiz Club
 
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
RVSPSOA
 
LDMMIA Free Reiki Yoga S7 Weekly Workshops
LDMMIA Free Reiki Yoga S7 Weekly WorkshopsLDMMIA Free Reiki Yoga S7 Weekly Workshops
LDMMIA Free Reiki Yoga S7 Weekly Workshops
LDM & Mia eStudios
 
STUDENT LOAN TRUST FUND DEFAULTERS GHANA
STUDENT LOAN TRUST FUND DEFAULTERS GHANASTUDENT LOAN TRUST FUND DEFAULTERS GHANA
STUDENT LOAN TRUST FUND DEFAULTERS GHANA
Kweku Zurek
 
PHYSIOLOGY & SPORTS INJURY by Diwakar Sir
PHYSIOLOGY & SPORTS INJURY by Diwakar SirPHYSIOLOGY & SPORTS INJURY by Diwakar Sir
PHYSIOLOGY & SPORTS INJURY by Diwakar Sir
Diwakar Kashyap
 
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdfForestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
ChalaKelbessa
 
How to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time OffHow to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time Off
Celine George
 
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.05.28.pdf
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.05.28.pdfTechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.05.28.pdf
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.05.28.pdf
TechSoup
 
CBSE - Grade 11 - Mathematics - Ch 2 - Relations And Functions - Notes (PDF F...
CBSE - Grade 11 - Mathematics - Ch 2 - Relations And Functions - Notes (PDF F...CBSE - Grade 11 - Mathematics - Ch 2 - Relations And Functions - Notes (PDF F...
CBSE - Grade 11 - Mathematics - Ch 2 - Relations And Functions - Notes (PDF F...
Sritoma Majumder
 
How to Manage Orders in Odoo 18 Lunch - Odoo Slides
How to Manage Orders in Odoo 18 Lunch - Odoo SlidesHow to Manage Orders in Odoo 18 Lunch - Odoo Slides
How to Manage Orders in Odoo 18 Lunch - Odoo Slides
Celine George
 
Introduction to Online CME for Nurse Practitioners.pdf
Introduction to Online CME for Nurse Practitioners.pdfIntroduction to Online CME for Nurse Practitioners.pdf
Introduction to Online CME for Nurse Practitioners.pdf
CME4Life
 
THE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATION
THE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATIONTHE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATION
THE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATION
PROF. PAUL ALLIEU KAMARA
 
LDMMIA Bonus GUEST GRAD Student Check-in
LDMMIA Bonus GUEST GRAD Student Check-inLDMMIA Bonus GUEST GRAD Student Check-in
LDMMIA Bonus GUEST GRAD Student Check-in
LDM & Mia eStudios
 
Uterine Prolapse, causes type and classification,its managment
Uterine Prolapse, causes type and classification,its managmentUterine Prolapse, causes type and classification,its managment
Uterine Prolapse, causes type and classification,its managment
Ritu480198
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
Types of Actions in Odoo 18 - Odoo Slides
Types of Actions in Odoo 18 - Odoo SlidesTypes of Actions in Odoo 18 - Odoo Slides
Types of Actions in Odoo 18 - Odoo Slides
Celine George
 
Order Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptxOrder Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptx
Arshad Shaikh
 

Python programming workshop

  • 2. Topics  Expressions, operators, precedence, control flows, functions  Input/output  List  Classes and Objects 2
  • 3. The Python Interpreter  Python is an interpreted language  Commands are executed through the Python interpreter  A programmer defines a series of commands in advance and saves those commands in a text file known as source code or a script.  For Python, source code is conventionally stored in a file named with the .py suffix (e.g., demo.py) 3
  • 4. Writing a Simple Program  Algorithm for calculating the area of a square  Obtain the width from the user  Computer the area by applying the following formula  𝒂𝒓𝒆𝒂 = 𝒘𝒊𝒅𝒕𝒉 ∗ 𝒘𝒊𝒅𝒕𝒉  Display the result 4
  • 5. Reading Input from the Console  Use the input function to obtain a string  variable = input(‘Enter width : ’)  Use the eval function to evaluate expression  variable = eval(string_variable)  Combination  width = eval(input(‘Enter width : ’)) 5
  • 6. Calculating Square Area width = eval(input('Enter width : ')) area = width * width print('Area is ', area) 6
  • 7. Identifiers  Identifiers in Python are case-sensitive, so temperature and Temperature are distinct names.  Identifiers can be composed of almost any combination of letters, numerals, and underscore characters.  An identifier cannot begin with a numeral and that there are 33 specially reserved words that cannot be used as identifiers: 7
  • 8. Types  Python is a dynamically typed language, as there is no advance declaration associating an identifier with a particular data type.  An identifier can be associated with any type of object, and it can later be reassigned to another object of the same (or different) type.  Although an identifier has no declared type, the object to which it refers has a definite type. In our first example, the characters 98.6 are recognized as a floating-point literal, and thus the identifier temperature is associated with an instance of the float class having that value. 8
  • 9. Numerical Data Types ad Numeric Operators  integer: e.g., 3, 4  float: e.g., 3.0, 4.0 Name Meaning Example Result + Addition 34 + 1 35 - Subtraction 34.0 – 0.1 33.9 * Multiplication 300 * 30 9000 / Float Division 1 / 2 0.5 // Integer Division 1 // 2 0 ** Exponentiation 4 ** 0.5 2.0 % Remainder 20 % 3 2 9
  • 10. Boolean Data Types  Often in a program you need to compare two values, such as whether i is greater than j  There are six comparison operators (also known as relational operators) that can be used to compare two values  The result of the comparison is a Boolean value: true or false Operator Name < less than <= less than or equal to > greater than >= greater than or equal to == equal to != not equal to 10
  • 11. String  Sequence of characters that is treated as a single item  Written as a sequence of characters surrounded by either single quotes (') or double quotes (")  Position or index of a character in a string  Identified with one of the numbers 0, 1, 2, 3, . . . . 11
  • 12. List 12 list1 = list() # Create an empty list list2 = list([2, 3, 4]) # Create a list with elements 2, 3, 4 list3 = list(["red", "green", "blue"]) # Create a list with strings list4 = list(range(3, 6)) # Create a list with elements 3, 4, 5 list5 = list("abcd") # Create a list with characters a, b, c list1 = [] # Same as list() list2 = [2, 3, 4] # Same as list([2, 3, 4]) list3 = ["red", "green"] # Same as list(["red", "green"]) append(x: object): None insert(index: int, x: object): None remove(x: object): None index(x: object): int count(x: object): int sort(): None reverse(): None extend(l: list): None pop([i]): object
  • 13. List Is a Sequence Type 13 Operation Description x in s True if element x is in sequence s x not in s True if element x is not in sequence s s1 + s2 Concatenates two sequences s1 and s2 s * n, n * s n copies of sequence s concatenated s[i] ith element in sequence s s[i : j] Slice of sequence s from index i to j - 1 len(s) Length of sequence s, i.e., the number of elements in s min(s) Smallest element in sequence s max(s) Largest element in sequence s sum(s) Sum of all numbers in sequence s for loop Traverses elements from left to right in a for loop <, <=, >, >=, ==, != Compares two sequences
  • 14. if Statement 14 if width > 0: area = width * width if Boolean-expression: statement(s)
  • 15. if-else Statement 15 if width > 0: area = width * width else: print(‘width must be positive’) if Boolean-expression: statement(s) for the true case else: statement(s) for the false case
  • 16. Multiple Alternative for if Statements 16 if score >= 90.0: grade = 'A' elif score >= 80.0: grade = 'B' elif score >= 70.0: grade = 'C' elif score >= 60.0: grade = 'D' else: grade = 'F' if score >= 90.0: grade = 'A' else: if score >= 80.0: grade = 'B' else: if score >= 70.0: grade = 'C' else: if score >= 60.0: grade = 'D' else: grade = 'F'
  • 17. Logical Operators 17 Operator Description not Logical negation and Logical conjunction or Logical disjunction (year % 4 == 0 and year % 100 != 0) or year % 400 == 0) A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400.
  • 18. Conditional Operator 18 y = 1 if x > 0 else -1if x > 0: y = 1 else: y = -1 if num % 2 == 0: print(str(num) + “is even”) else: print(str(num) + “is odd”); print("number is even" if (number % 2 == 0) else "number is odd")
  • 19. Operator Precedence  +, - unary  **  not  *, /, //, %  +, -  <, <=, >, >=  ==, !=  and  or  =, +=, -=, *=, /=, //=, %= (Assignment operator) 19
  • 20. Loops 20 for i in range(1, 6): print (i) num = 1 while num <= 5: print(num) num += 1 while conditions: indented block of statements for var in sequence: indented block of statements
  • 21. Functions  Functions can be used to define reusable code and organize and simplify code 21 def sum_range(a, b): result = 0 for i in range(a, b+1): result += i return result def main(): print('Sum from 1 to 10 is ', sum_range(1, 10)); print('Sum from 50 to 100 is ', sum_range(50, 100)); main() def function_name(list of parameters): # Function body
  • 22. Reading Input from Text Files 22 continent = input('Enter the name of a continent : ') continent = continent.title() if continent != 'Antarctica': infile = open('UN.txt', 'r') for line in infile: data = line.split(',') if data[1] == continent: print(data[0]) else: print('There are not countries in Antarctica.') infile = open(‘Filename’, ‘r’)
  • 23. List Comprehension 23 list1 = [x for x in range(5)] [0, 1, 2, 3, 4] line = input('Enter series of numbers : ') text_numbers = line.split(' ') numbers = [eval(num) for num in text_numbers]
  • 24. Objects and Classes  Object-oriented programming enables you to develop large-scale software and GUIs effectively. 24 class Rectangle: def __init__(self, width = 1, height = 2): self._width = width self._height = height def area(self): return self._width * self._height def perimeter(self): return 2 * (self._width * self._height) def main(): r1 = Rectangle(10, 20) print('The area of the rectangle is : ', r1.area()) print('The perimeter of the rectangle is : ', r1.perimeter()) main() class ClassName: initializer methods