SlideShare a Scribd company logo
COMPUTER STUDIES
INTRODUCTION TO PYTHON PROGRAMMING
Python programming is pretty straight forward.
>>> 2 + 3 * 6
20
>>> (2 + 3) * 6
30
>>> 48565878 * 578453
28093077826734
>>> 2 ** 8
256
>>> 23 / 7
3.2857142857142856
>>> 23 // 7
3
>>> 23 % 7
2
>>> 2 + 2
4
>>> (5 - 1) * ((7 + 1) / (3 - 1))
16.0
Order of operation:
B (Brackets) E (Exponent) D (Division) M (Multiplication) A (Addition) S (Subtraction)
Comments:
# this is the first comment
spam = 1 # and this is the second comment
# ... and now a third!
text = "# This is not a comment because it's inside quotes."
Single line comment: # this is a single line comment
Block comments “”” this is a block comments that we must put in a 3 double quote
Like this”””
Basic Arithmetic Operations
Operators:
+: Addition
-: Subtraction
*: Multiplication
/: Division
%: Modulo (remainder). The remainder can be calculated with the % operator
**: Power
//: floor division: if both operands are of type int, floor division is performed and an int is
returned
Variables
Variable = 18
Variable1 = “Hello world!”
Types of variables:
 int: integer 2, 4, 20
 float: the ones with a fractional part or decimal (3.4, 4.9, 3.14,…)
 complex:
 bool: Boolean value (Yes/No; True/False; 0/1)
 str: string this is a strings of characters “I am a string of characters”
Data types: Numbers, Strings, Lists, Tuples, Dictionaries, Lists
Functions
In the context of programming, a function is a named sequence of statements that performs a
desired operation. This operation is specified in a function definition. In Python, the syntax for a
function definition is: print(), input(), round()
Built-in functions
Numbers
Using Python as a Calculator
tax = 12.5 / 100
price = 100.50
bill = price * tax
pay = round(bill, 2)
print(“Your final bil is: “,pay,”$”)
The function round () (like in excel) rounds the result pay into 2 decimal places
Strings
Besides numbers, Python can also manipulate strings, which can be expressed in several ways.
They can be enclosed in single quotes ('...') or double quotes ("...") with the same result [2].  can
be used to escape quotes:
>>> 'spam eggs' # single quotes
'spam eggs'
>>> 'doesn't' # use ' to escape the single quote...
"doesn't"
>>> "doesn't" # ...or use double quotes instead
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> ""Yes," he said."
'"Yes," he said.'
>>> '"Isn't," she said.'
'"Isn't," she said.'
Concatenate strings
Prefix = “Py”
Word = Prefix + “thon”
Lists
Built-in function: len()
Manipulate the element in the list.
Index element in the list
The other way around, if we want to know the index of the element in the list we can use:
This program will return the index of the element “horse” in the list that is 2
Modify, append elements in the list
Let’s modify (replace) “bull” with “parrot”
Bull is replaced by parrot
Extend the list and append elements
If we extend the list the new element is added at the end of the list
How if we move the “bull” at the beginning of the list
Bull is moved at the beginning of the list
Bull is added again in the list
Assignment to slices is also possible, and this can even change the size of the list or clear it
entirely
It is possible to nest lists (create lists containing other lists)
In x= [a, n]
The first element of the list must be a in that case x[0] =”a” and the second element must be
x[1] = n
If we want to show the elements of the list in a it must be written as: x[0][0,1,2]
Instead for the element from n, it is: x[1][0,1,2,3]
Et voilà c’est fait!
The elements of X[0] = [a, b, c]
So from the figure above: X [0] [0] = a; X [0] [1] = b; X [0] [2] = c
The elements of X [1] = [1, 2, 3]
So from the figure above: X [1] [0] = 1; X [1] [1] = 2; X [1] [2] = 3
x [ a , n= ]
First element
X [0]
Second element
X [1]
[0] [1] [2]
[0] [1] [2]
Conditions and Conditional Statements
if, else, elif (Elseif)
<, >, <=, >=, ==, !=
# and, or, not, !=, ==
if 12!=13
print (“YES")
a = 33
t = 22i
if a == 33 and not (t ==22):
print ("TRUE")
else:
print("FALSE")
apples = input("How many apples?")
if apples >= 6:
print ("I have more apples: ")
elif apples < 6:
print ("I have not enough apples: ")
else:
print (" I have nothing: ")
apples = int(input("How many apples?: "))
if apples >= 6:
print ("I have more apples: ",str(apples))
elif apples < 6:
print ("I have not enough apples: ",str(apples))
else:
print (" I have nothing: ",str(apples))
It should say, “I have nothing”
We try to compare string and integer so we need to
convert it into integer using the function int ()
We need to refine the code as follow:
Other way of writing multiple conditions
The use of the operator “and” to combine two
conditions and concatenation
Task1
Write a piece of code to display whether a user inputs 0, 1 or more and display this.
Task2
Write a piece of code to test a mark and achievement by each student.
Mark Grade
91 A*
90 A+
80 A
70 B
60 C
50 D
40 E
30 F
20 Fail
Answer
Task1
Task2
Introduction to python programming
What we have learned so far?
Difference between = and ==
Even though it is a mark the print () function will interpret the value as a string so it is necessary
to convert it using the function str()
All string must be in between “ ” (quotes)
We can concatenate 2 strings using +
While condition
while condition :
indentedBlock
To make things concrete and numerical, suppose the following: The tea starts at 115 degrees
Fahrenheit. You want it at 112 degrees. A chip of ice turns out to lower the temperature one
degree each time. You test the temperature each time, and also print out the temperature before
reducing the temperature. In Python you could write and run the code below, saved in example
program cool.py:
1
2
3
4
5
6
temperature = 115
while temperature > 112: # first while loop code
print(temperature)
temperature = temperature - 1
print('The tea is cool enough.')
I added a final line after the while loop to remind you that execution follows sequentially after a
loop completes.
If you play computer and follow the path of execution, you could generate the following table.
Remember, that each time you reach the end of the indented block after the while heading,
execution returns to the while heading for another test:
Line temperature Comment
1 115
2 115 > 112 is true, do loop
3 prints 115
4 114 115 - 1 is 114, loop back
2 114 > 112 is true, do loop
3 prints 114
4 113 114 - 1 is 113, loop back
2 113 > 112 is true, do loop
3 prints 113
4 112 113 - 1 is 112, loop back
2 112 > 112 is false, skip loop
6 prints that the tea is cool
Each time the end of the indented loop body is reached, execution returns to the while loop
heading for another test. When the test is finally false, execution jumps past the indented body of
the while loop to the next sequential statement.
Test yourself: Following the code. Figure out what is printed. :
i = 4
while i < 9:
print(i)
i = i+2
For Loops
'''The number of repetitions is specified by the user.'''
n = int(input('Enter the number of times to repeat: '))
for i in range(n):
print('This is repetitious!')
Extension
name = input('What is your name? ')
if name.endswith('Gumby'):
print ('Hello, Mr. Gumby')

More Related Content

PPTX
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
PPTX
OPERATOR IN PYTHON-PART2
PDF
c programming
PPTX
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
PDF
The Ring programming language version 1.5.2 book - Part 18 of 181
PDF
The Ring programming language version 1.2 book - Part 12 of 84
PDF
The Ring programming language version 1.2 book - Part 9 of 84
PPTX
Python for Data Science
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
OPERATOR IN PYTHON-PART2
c programming
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
The Ring programming language version 1.5.2 book - Part 18 of 181
The Ring programming language version 1.2 book - Part 12 of 84
The Ring programming language version 1.2 book - Part 9 of 84
Python for Data Science

What's hot (20)

PDF
Block ciphers
PDF
iRODS Rule Language Cheat Sheet
PDF
The Ring programming language version 1.2 book - Part 10 of 84
PDF
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
PPTX
Java Foundations: Lists, ArrayList<T>
PPTX
FLOW OF CONTROL-NESTED IFS IN PYTHON
PPTX
Introduction to matlab lecture 4 of 4
PDF
Python Modules, Packages and Libraries
PDF
Python programming : Standard Input and Output
PDF
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
PPTX
OPERATOR IN PYTHON-PART1
PPTX
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
PDF
Cheat sheet python3
PPTX
Python Modules and Libraries
PDF
The Ring programming language version 1.9 book - Part 25 of 210
DOCX
C interview question answer 2
PPTX
Introduction to python programming 1
PDF
Python3 cheatsheet
PDF
Python 2.5 reference card (2009)
PDF
[1062BPY12001] Data analysis with R / April 26
Block ciphers
iRODS Rule Language Cheat Sheet
The Ring programming language version 1.2 book - Part 10 of 84
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Java Foundations: Lists, ArrayList<T>
FLOW OF CONTROL-NESTED IFS IN PYTHON
Introduction to matlab lecture 4 of 4
Python Modules, Packages and Libraries
Python programming : Standard Input and Output
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
OPERATOR IN PYTHON-PART1
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
Cheat sheet python3
Python Modules and Libraries
The Ring programming language version 1.9 book - Part 25 of 210
C interview question answer 2
Introduction to python programming 1
Python3 cheatsheet
Python 2.5 reference card (2009)
[1062BPY12001] Data analysis with R / April 26
Ad

Similar to Introduction to python programming (20)

PPTX
unit1.pptx for python programming CSE department
PDF
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
PDF
Python+Syntax+Cheat+Sheet+Booklet.pdf
PDF
python notes.pdf
PDF
pythonQuick.pdf
PDF
python 34💭.pdf
PDF
Introduction To Programming with Python
PPT
python fundamental for beginner course .ppt
PPTX
Programming with python
PPTX
made it easy: python quick reference for beginners
PPTX
Bikalpa_Thapa_Python_Programming_(Basics).pptx
PPTX
Python programing
PPTX
python_computer engineering_semester_computer_language.pptx
PPTX
lecture 2.pptx
PPTX
Dr.C S Prasanth-Physics ppt.pptx computer
PPTX
Python Traning presentation
PPTX
Python.pptx
PDF
Python for Beginners - Simply understand programming concepts
PPT
Python tutorialfeb152012
unit1.pptx for python programming CSE department
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
Python+Syntax+Cheat+Sheet+Booklet.pdf
python notes.pdf
pythonQuick.pdf
python 34💭.pdf
Introduction To Programming with Python
python fundamental for beginner course .ppt
Programming with python
made it easy: python quick reference for beginners
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Python programing
python_computer engineering_semester_computer_language.pptx
lecture 2.pptx
Dr.C S Prasanth-Physics ppt.pptx computer
Python Traning presentation
Python.pptx
Python for Beginners - Simply understand programming concepts
Python tutorialfeb152012
Ad

More from Rakotoarison Louis Frederick (10)

DOCX
Uses of databases
DOCX
Orang tua perlu pahami makna pendidikan anak oleh
PDF
Programming basics
PDF
Kata Kerja Operasional
PDF
Jiwa seni di cendekia leadership school
PDF
Webdesign(tutorial)
PDF
Fitur fitur yang ada di audacity
PDF
Moustaffa audacity-1
Uses of databases
Orang tua perlu pahami makna pendidikan anak oleh
Programming basics
Kata Kerja Operasional
Jiwa seni di cendekia leadership school
Webdesign(tutorial)
Fitur fitur yang ada di audacity
Moustaffa audacity-1

Recently uploaded (20)

PPTX
Big Data Technologies - Introduction.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
PDF
Chapter 2 Digital Image Fundamentals.pdf
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
cuic standard and advanced reporting.pdf
Big Data Technologies - Introduction.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Understanding_Digital_Forensics_Presentation.pptx
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
Chapter 2 Digital Image Fundamentals.pdf
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
madgavkar20181017ppt McKinsey Presentation.pdf
20250228 LYD VKU AI Blended-Learning.pptx
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Chapter 3 Spatial Domain Image Processing.pdf
Empathic Computing: Creating Shared Understanding
cuic standard and advanced reporting.pdf

Introduction to python programming

  • 1. COMPUTER STUDIES INTRODUCTION TO PYTHON PROGRAMMING Python programming is pretty straight forward. >>> 2 + 3 * 6 20 >>> (2 + 3) * 6 30 >>> 48565878 * 578453 28093077826734 >>> 2 ** 8 256 >>> 23 / 7 3.2857142857142856 >>> 23 // 7 3 >>> 23 % 7 2 >>> 2 + 2 4 >>> (5 - 1) * ((7 + 1) / (3 - 1)) 16.0 Order of operation: B (Brackets) E (Exponent) D (Division) M (Multiplication) A (Addition) S (Subtraction) Comments: # this is the first comment spam = 1 # and this is the second comment # ... and now a third! text = "# This is not a comment because it's inside quotes." Single line comment: # this is a single line comment Block comments “”” this is a block comments that we must put in a 3 double quote Like this”””
  • 2. Basic Arithmetic Operations Operators: +: Addition -: Subtraction *: Multiplication /: Division %: Modulo (remainder). The remainder can be calculated with the % operator **: Power //: floor division: if both operands are of type int, floor division is performed and an int is returned Variables Variable = 18 Variable1 = “Hello world!” Types of variables:  int: integer 2, 4, 20  float: the ones with a fractional part or decimal (3.4, 4.9, 3.14,…)  complex:  bool: Boolean value (Yes/No; True/False; 0/1)  str: string this is a strings of characters “I am a string of characters” Data types: Numbers, Strings, Lists, Tuples, Dictionaries, Lists Functions In the context of programming, a function is a named sequence of statements that performs a desired operation. This operation is specified in a function definition. In Python, the syntax for a function definition is: print(), input(), round()
  • 3. Built-in functions Numbers Using Python as a Calculator tax = 12.5 / 100 price = 100.50 bill = price * tax pay = round(bill, 2) print(“Your final bil is: “,pay,”$”) The function round () (like in excel) rounds the result pay into 2 decimal places
  • 4. Strings Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes ('...') or double quotes ("...") with the same result [2]. can be used to escape quotes: >>> 'spam eggs' # single quotes 'spam eggs' >>> 'doesn't' # use ' to escape the single quote... "doesn't" >>> "doesn't" # ...or use double quotes instead "doesn't" >>> '"Yes," he said.' '"Yes," he said.' >>> ""Yes," he said." '"Yes," he said.' >>> '"Isn't," she said.' '"Isn't," she said.' Concatenate strings Prefix = “Py” Word = Prefix + “thon” Lists Built-in function: len()
  • 5. Manipulate the element in the list. Index element in the list The other way around, if we want to know the index of the element in the list we can use: This program will return the index of the element “horse” in the list that is 2 Modify, append elements in the list Let’s modify (replace) “bull” with “parrot” Bull is replaced by parrot
  • 6. Extend the list and append elements If we extend the list the new element is added at the end of the list How if we move the “bull” at the beginning of the list Bull is moved at the beginning of the list Bull is added again in the list
  • 7. Assignment to slices is also possible, and this can even change the size of the list or clear it entirely It is possible to nest lists (create lists containing other lists)
  • 8. In x= [a, n] The first element of the list must be a in that case x[0] =”a” and the second element must be x[1] = n If we want to show the elements of the list in a it must be written as: x[0][0,1,2] Instead for the element from n, it is: x[1][0,1,2,3] Et voilà c’est fait!
  • 9. The elements of X[0] = [a, b, c] So from the figure above: X [0] [0] = a; X [0] [1] = b; X [0] [2] = c The elements of X [1] = [1, 2, 3] So from the figure above: X [1] [0] = 1; X [1] [1] = 2; X [1] [2] = 3 x [ a , n= ] First element X [0] Second element X [1] [0] [1] [2] [0] [1] [2]
  • 10. Conditions and Conditional Statements if, else, elif (Elseif) <, >, <=, >=, ==, != # and, or, not, !=, == if 12!=13 print (“YES") a = 33 t = 22i if a == 33 and not (t ==22): print ("TRUE") else: print("FALSE") apples = input("How many apples?") if apples >= 6: print ("I have more apples: ") elif apples < 6: print ("I have not enough apples: ") else: print (" I have nothing: ") apples = int(input("How many apples?: ")) if apples >= 6: print ("I have more apples: ",str(apples)) elif apples < 6: print ("I have not enough apples: ",str(apples)) else: print (" I have nothing: ",str(apples)) It should say, “I have nothing” We try to compare string and integer so we need to convert it into integer using the function int ()
  • 11. We need to refine the code as follow: Other way of writing multiple conditions The use of the operator “and” to combine two conditions and concatenation
  • 12. Task1 Write a piece of code to display whether a user inputs 0, 1 or more and display this. Task2 Write a piece of code to test a mark and achievement by each student. Mark Grade 91 A* 90 A+ 80 A 70 B 60 C 50 D 40 E 30 F 20 Fail
  • 15. What we have learned so far? Difference between = and == Even though it is a mark the print () function will interpret the value as a string so it is necessary to convert it using the function str() All string must be in between “ ” (quotes) We can concatenate 2 strings using + While condition while condition : indentedBlock To make things concrete and numerical, suppose the following: The tea starts at 115 degrees Fahrenheit. You want it at 112 degrees. A chip of ice turns out to lower the temperature one degree each time. You test the temperature each time, and also print out the temperature before reducing the temperature. In Python you could write and run the code below, saved in example program cool.py: 1 2 3 4 5 6 temperature = 115 while temperature > 112: # first while loop code print(temperature) temperature = temperature - 1 print('The tea is cool enough.') I added a final line after the while loop to remind you that execution follows sequentially after a loop completes. If you play computer and follow the path of execution, you could generate the following table. Remember, that each time you reach the end of the indented block after the while heading, execution returns to the while heading for another test:
  • 16. Line temperature Comment 1 115 2 115 > 112 is true, do loop 3 prints 115 4 114 115 - 1 is 114, loop back 2 114 > 112 is true, do loop 3 prints 114 4 113 114 - 1 is 113, loop back 2 113 > 112 is true, do loop 3 prints 113 4 112 113 - 1 is 112, loop back 2 112 > 112 is false, skip loop 6 prints that the tea is cool Each time the end of the indented loop body is reached, execution returns to the while loop heading for another test. When the test is finally false, execution jumps past the indented body of the while loop to the next sequential statement. Test yourself: Following the code. Figure out what is printed. : i = 4 while i < 9: print(i) i = i+2 For Loops '''The number of repetitions is specified by the user.''' n = int(input('Enter the number of times to repeat: ')) for i in range(n): print('This is repetitious!')
  • 17. Extension name = input('What is your name? ') if name.endswith('Gumby'): print ('Hello, Mr. Gumby')