SlideShare a Scribd company logo
CHAPTER-TWO
Python Basic Syntax
By: Mikiale T.
1
Basic Syntax
 Indentation is used in Python to delimit blocks. The number of spaces is
variable, but all statements within the same block must be indented the
same amount.
 The header line for compound statements, such as if, while,
def, and class should be terminated with a colon ( : )
 The semicolon ( ; ) is optional at the end of statement.
 Printing to the Screen:
 Reading Keyboard Input:
 Comments
•Single line:
•Multiple lines:
 Python files have extension
.py
Error
!
2
Variables
 Python is dynamically typed. You do not
need to declare variables!
 The declaration happens automatically
when you assign a value to a variable.
 Variables can change type, simply by
assigning them a new value of a different
type.
 Python allows you to assign a single value
to several variables simultaneously.
 You can also assign multiple objects to
multiple variables.
3
Python Data Types
4
Python has five standard data types-
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
1. Numbers
 Numbers are Immutable objects in Python that cannot change their
values.
 There are three built-in data types for numbers in Python3:
• Integer (int)
• Floating-point numbers (float)
• Complex numbers: <real part> + <imaginary part>j (not used much in Python programming)
 Common Number Functions
Function Description
int(x) to convert x to an integer
float(x) to convert x to a floating-point number
abs(x) The absolute value of x
cmp(x,y) -1 if x < y, 0 if x == y, or 1 if x > y
exp(x) The exponential of x: ex
log(x) The natural logarithm of x, for x> 0
pow(x,y) The value of x**y
sqrt(x) The square root of x for x > 0 5
2. Strings
 Python Strings are Immutable objects that cannot change their values.
 You can update an existing string by (re)assigning a variable to another string.
 Python does not support a character type; these are treated as strings of length
one.
 Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals.
 String indexes starting at 0 in the beginning of the string and working their way
from -1
at the end.
6
Strings …
 String Formatting
 Common String Operators
Assume string variable a holds 'Hello' and variable b holds
'Python’
Operator Description Example
+ Concatenation - Adds values on either side of the operator a + b will give
HelloPython
* Repetition - Creates new strings, concatenating multiple
copies of the same string
a*2 will give HelloHello
[ ] Slice - Gives the character from the given index a[1] will give
e a[-1] will
give o
[ : ] Range Slice - Gives the characters from the given range a[1:4] will give ell
in Membership - Returns true if a character exists in the given
string
‘H’ in a will give True
7
Strings …
 Common String Methods
Method Description
str.count(sub,
beg=
0,end=len(str))
Counts how many times sub occurs in string or in a substring of
string if starting index beg and ending index end are given.
str.isalpha() Returns True if string has at least 1 character and all
characters are alphanumeric and False otherwise.
str.isdigit() Returns True if string contains only digits and False otherwise.
str.lower() Converts all uppercase letters in string to lowercase.
str.upper() Converts lowercase letters in string to uppercase.
str.replace(old, new) Replaces all occurrences of old in string with new.
str.split(str=‘ ’) Splits string according to delimiter str (space if not
provided) and returns list of substrings.
str.strip() Removes all leading and trailing whitespace of string.
str.title() Returns "titlecased" version of string.
 Common String Functions str(x) :to convert x to a string
len(string):gives the total length of the string
8
Strings …
Example:
9
3. Lists
 A list in Python is an ordered group of items or elements, and these list elements don't
have to be of the same type.
 Python Lists are mutable objects that can change their values.
 A list contains items separated by commas and enclosed within square brackets.
 List indexes like strings starting at 0 in the beginning of the list and working their way
from -1 at the end.
 Similar to strings, Lists operations include slicing ([ ] and [:]) , concatenation
(+),repetition (*), and membership (in).
 This example shows how to access, update and delete list elements:
10
Lists
 Lists can have sublists as elements and these sublists may contain other
sublists
as well.
 Common List Functions
Function Description
cmp(list1, list2) Compares elements of both lists.
len(list) Gives the total length of the list.
max(list) Returns item from the list with max value.
min(list) Returns item from the list with min value.
list(tuple) Converts a tuple into list.
11
Lists
 Common List Methods
 List Comprehensions
Each list comprehension consists of an expression followed by a for
clause.
Method Description
list.append(obj) Appends object obj to list
list.insert(index,
obj)
Inserts object obj into list at offset index
list.count(obj) Returns count of how many times obj occurs in
list
list.index(obj) Returns the lowest index in list that obj appears
list.remove(obj) Removes object obj from list
list.reverse() Reverses objects of list in place
list.sort() Sorts objects of list in place
 List comprehension
12
…Lists
Example:
13
Python Reserved Words
 Akeywordisonethat meanssomething to the language.
 Inother words, youcan’tusea reservedword asthe nameof avariable,afunction, aclass,or amodule.
 All the Python keywordscontainlowercaseletters only.
14
4. Tuples
 Python Tuples are Immutableobjects that cannot be changedonce theyhave
been created.
 A tuple contains items separated by commas and enclosed in parentheses instead
of square brackets.
 access
 No update
 You can update an existing tuple by (re)assigning a variable to another tuple.
 Tuples are faster than lists and protect your data against accidental changes to
these data.
 The rules for tuple indices are the same as for lists and they have the same
operations, functions as well.
 To write a tuple containing a single value, you have to include a comma, even though
there is only one value. e.g. t = (3, ) 15
…Tuples
Example:
16
• Hashing is a technique that is used to uniquely identify a specific object
from a group of similar objects.
 Assume that you have an object and you want to
assign a key to it to make searching easy.
 To store the key/value pair, you can use a simple array
like a data structure where keys (integers) can be used
directly as an index to store values.
 However, in cases where the keys are large and
cannot be used directly as an index, you should use
hashing.
Hash Table
17
5. Dictionary
 Python's dictionaries are kind of hash table type which consist of key-value pairs
of unordered elements.
• Keys : must be immutable data types ,usually numbers or strings.
• Values : can be any arbitrary Python object.
 Python Dictionaries are mutable objects that can change their values.
 A dictionary is enclosed by curly braces ({ }), the items are separated by commas, and
each key is separated from its value by a colon (:).
 Dictionary’s values can be assigned and accessed using square braces ([]) with a
key to obtain its value.
18
Dictionary …
Example:
19
Dictionary
 Common Dictionary Functions
• cmp(dict1, dict2) : compares elements of both dict.
• len(dict) : gives the total number of (key, value) pairs in the
dictionary.
 Common Dictionary Methods
Method Description
dict.keys() Returns list of dict's keys
dict.values() Returns list of dict's values
dict.items() Returns a list of dict's (key, value) tuple pairs
dict.get(key,
default=None)
For key, returns value or default if key not in dict
dict.has_key(key) Returns True if key in dict, False otherwise
dict.update(dict2) Adds dict2's key-values pairs to dict
dict.clear() Removes all elements of dict
20
Dictionary
 This example shows how to access, update and delete dictionary elements:
 The output:
21
Exercises
1. Reverse a list in Python
2. Accept any three string from one input()
3. Create a string containing an integer, then convert that string into an actual integer object
using int(). Test that your new object is a number by multiplying it by another number and
displaying the result.
4. Write python program that Count all letters, digits, and special symbols from a given string.
5. Given a list of numbers. write a program to turn every item of a list into its square.
Given:
numbers = [1, 2, 3, 4, 5, 6, 7]
Expected output:
[1, 4, 9, 16, 25, 36, 49]
22

More Related Content

Similar to Chapter - 2.pptx

Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptx
rohithprabhas1
 

Similar to Chapter - 2.pptx (20)

dataStructuresInPython.pptx
dataStructuresInPython.pptxdataStructuresInPython.pptx
dataStructuresInPython.pptx
 
Python 3.x quick syntax guide
Python 3.x quick syntax guidePython 3.x quick syntax guide
Python 3.x quick syntax guide
 
Introduction To Programming with Python-3
Introduction To Programming with Python-3Introduction To Programming with Python-3
Introduction To Programming with Python-3
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
13- Data and Its Types presentation kafss
13- Data and Its Types presentation kafss13- Data and Its Types presentation kafss
13- Data and Its Types presentation kafss
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
Python slide.1
Python slide.1Python slide.1
Python slide.1
 
Data Types In Python.pptx
Data Types In Python.pptxData Types In Python.pptx
Data Types In Python.pptx
 
Python ppt_118.pptx
Python ppt_118.pptxPython ppt_118.pptx
Python ppt_118.pptx
 
2. Values and Data types in Python.pptx
2. Values and Data types in Python.pptx2. Values and Data types in Python.pptx
2. Values and Data types in Python.pptx
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
 
C# String
C# StringC# String
C# String
 
11 Unit 1 Chapter 02 Python Fundamentals
11  Unit 1 Chapter 02 Python Fundamentals11  Unit 1 Chapter 02 Python Fundamentals
11 Unit 1 Chapter 02 Python Fundamentals
 
Tuple Operation and Tuple Assignment in Python.pdf
Tuple Operation and Tuple Assignment in Python.pdfTuple Operation and Tuple Assignment in Python.pdf
Tuple Operation and Tuple Assignment in Python.pdf
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptx
 
Python data type
Python data typePython data type
Python data type
 
NEC PPT ET IN CS BY SUBHRAT TRIPATHI.pptx
NEC PPT ET IN CS BY SUBHRAT TRIPATHI.pptxNEC PPT ET IN CS BY SUBHRAT TRIPATHI.pptx
NEC PPT ET IN CS BY SUBHRAT TRIPATHI.pptx
 
Presentation on python data type
Presentation on python data typePresentation on python data type
Presentation on python data type
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Basic data types in python
Basic data types in pythonBasic data types in python
Basic data types in python
 

More from MikialeTesfamariam (11)

traditional cliphers 7-11-12.ppt
traditional cliphers 7-11-12.ppttraditional cliphers 7-11-12.ppt
traditional cliphers 7-11-12.ppt
 
6 KBS_ES.ppt
6 KBS_ES.ppt6 KBS_ES.ppt
6 KBS_ES.ppt
 
Chapter - 4.pptx
Chapter - 4.pptxChapter - 4.pptx
Chapter - 4.pptx
 
Chapter - 6.pptx
Chapter - 6.pptxChapter - 6.pptx
Chapter - 6.pptx
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
 
Chapter - 3.pptx
Chapter - 3.pptxChapter - 3.pptx
Chapter - 3.pptx
 
Chapter - 1.pptx
Chapter - 1.pptxChapter - 1.pptx
Chapter - 1.pptx
 
Chapter -7.pptx
Chapter -7.pptxChapter -7.pptx
Chapter -7.pptx
 
Python_Functions.pdf
Python_Functions.pdfPython_Functions.pdf
Python_Functions.pdf
 
functions-.pdf
functions-.pdffunctions-.pdf
functions-.pdf
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
 

Recently uploaded

Recently uploaded (20)

PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Morse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptxMorse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptx
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
Research Methods in Psychology | Cambridge AS Level | Cambridge Assessment In...
Research Methods in Psychology | Cambridge AS Level | Cambridge Assessment In...Research Methods in Psychology | Cambridge AS Level | Cambridge Assessment In...
Research Methods in Psychology | Cambridge AS Level | Cambridge Assessment In...
 
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Open Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPointOpen Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPoint
 
The impact of social media on mental health and well-being has been a topic o...
The impact of social media on mental health and well-being has been a topic o...The impact of social media on mental health and well-being has been a topic o...
The impact of social media on mental health and well-being has been a topic o...
 
The Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. HenryThe Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. Henry
 
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxJose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
 
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
Operations Management - Book1.p  - Dr. Abdulfatah A. SalemOperations Management - Book1.p  - Dr. Abdulfatah A. Salem
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
 
size separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticssize separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceutics
 
The Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational ResourcesThe Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational Resources
 
Benefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational ResourcesBenefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational Resources
 
How to Manage Notification Preferences in the Odoo 17
How to Manage Notification Preferences in the Odoo 17How to Manage Notification Preferences in the Odoo 17
How to Manage Notification Preferences in the Odoo 17
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 

Chapter - 2.pptx

  • 2. Basic Syntax  Indentation is used in Python to delimit blocks. The number of spaces is variable, but all statements within the same block must be indented the same amount.  The header line for compound statements, such as if, while, def, and class should be terminated with a colon ( : )  The semicolon ( ; ) is optional at the end of statement.  Printing to the Screen:  Reading Keyboard Input:  Comments •Single line: •Multiple lines:  Python files have extension .py Error ! 2
  • 3. Variables  Python is dynamically typed. You do not need to declare variables!  The declaration happens automatically when you assign a value to a variable.  Variables can change type, simply by assigning them a new value of a different type.  Python allows you to assign a single value to several variables simultaneously.  You can also assign multiple objects to multiple variables. 3
  • 4. Python Data Types 4 Python has five standard data types- 1. Numbers 2. String 3. List 4. Tuple 5. Dictionary
  • 5. 1. Numbers  Numbers are Immutable objects in Python that cannot change their values.  There are three built-in data types for numbers in Python3: • Integer (int) • Floating-point numbers (float) • Complex numbers: <real part> + <imaginary part>j (not used much in Python programming)  Common Number Functions Function Description int(x) to convert x to an integer float(x) to convert x to a floating-point number abs(x) The absolute value of x cmp(x,y) -1 if x < y, 0 if x == y, or 1 if x > y exp(x) The exponential of x: ex log(x) The natural logarithm of x, for x> 0 pow(x,y) The value of x**y sqrt(x) The square root of x for x > 0 5
  • 6. 2. Strings  Python Strings are Immutable objects that cannot change their values.  You can update an existing string by (re)assigning a variable to another string.  Python does not support a character type; these are treated as strings of length one.  Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals.  String indexes starting at 0 in the beginning of the string and working their way from -1 at the end. 6
  • 7. Strings …  String Formatting  Common String Operators Assume string variable a holds 'Hello' and variable b holds 'Python’ Operator Description Example + Concatenation - Adds values on either side of the operator a + b will give HelloPython * Repetition - Creates new strings, concatenating multiple copies of the same string a*2 will give HelloHello [ ] Slice - Gives the character from the given index a[1] will give e a[-1] will give o [ : ] Range Slice - Gives the characters from the given range a[1:4] will give ell in Membership - Returns true if a character exists in the given string ‘H’ in a will give True 7
  • 8. Strings …  Common String Methods Method Description str.count(sub, beg= 0,end=len(str)) Counts how many times sub occurs in string or in a substring of string if starting index beg and ending index end are given. str.isalpha() Returns True if string has at least 1 character and all characters are alphanumeric and False otherwise. str.isdigit() Returns True if string contains only digits and False otherwise. str.lower() Converts all uppercase letters in string to lowercase. str.upper() Converts lowercase letters in string to uppercase. str.replace(old, new) Replaces all occurrences of old in string with new. str.split(str=‘ ’) Splits string according to delimiter str (space if not provided) and returns list of substrings. str.strip() Removes all leading and trailing whitespace of string. str.title() Returns "titlecased" version of string.  Common String Functions str(x) :to convert x to a string len(string):gives the total length of the string 8
  • 10. 3. Lists  A list in Python is an ordered group of items or elements, and these list elements don't have to be of the same type.  Python Lists are mutable objects that can change their values.  A list contains items separated by commas and enclosed within square brackets.  List indexes like strings starting at 0 in the beginning of the list and working their way from -1 at the end.  Similar to strings, Lists operations include slicing ([ ] and [:]) , concatenation (+),repetition (*), and membership (in).  This example shows how to access, update and delete list elements: 10
  • 11. Lists  Lists can have sublists as elements and these sublists may contain other sublists as well.  Common List Functions Function Description cmp(list1, list2) Compares elements of both lists. len(list) Gives the total length of the list. max(list) Returns item from the list with max value. min(list) Returns item from the list with min value. list(tuple) Converts a tuple into list. 11
  • 12. Lists  Common List Methods  List Comprehensions Each list comprehension consists of an expression followed by a for clause. Method Description list.append(obj) Appends object obj to list list.insert(index, obj) Inserts object obj into list at offset index list.count(obj) Returns count of how many times obj occurs in list list.index(obj) Returns the lowest index in list that obj appears list.remove(obj) Removes object obj from list list.reverse() Reverses objects of list in place list.sort() Sorts objects of list in place  List comprehension 12
  • 14. Python Reserved Words  Akeywordisonethat meanssomething to the language.  Inother words, youcan’tusea reservedword asthe nameof avariable,afunction, aclass,or amodule.  All the Python keywordscontainlowercaseletters only. 14
  • 15. 4. Tuples  Python Tuples are Immutableobjects that cannot be changedonce theyhave been created.  A tuple contains items separated by commas and enclosed in parentheses instead of square brackets.  access  No update  You can update an existing tuple by (re)assigning a variable to another tuple.  Tuples are faster than lists and protect your data against accidental changes to these data.  The rules for tuple indices are the same as for lists and they have the same operations, functions as well.  To write a tuple containing a single value, you have to include a comma, even though there is only one value. e.g. t = (3, ) 15
  • 17. • Hashing is a technique that is used to uniquely identify a specific object from a group of similar objects.  Assume that you have an object and you want to assign a key to it to make searching easy.  To store the key/value pair, you can use a simple array like a data structure where keys (integers) can be used directly as an index to store values.  However, in cases where the keys are large and cannot be used directly as an index, you should use hashing. Hash Table 17
  • 18. 5. Dictionary  Python's dictionaries are kind of hash table type which consist of key-value pairs of unordered elements. • Keys : must be immutable data types ,usually numbers or strings. • Values : can be any arbitrary Python object.  Python Dictionaries are mutable objects that can change their values.  A dictionary is enclosed by curly braces ({ }), the items are separated by commas, and each key is separated from its value by a colon (:).  Dictionary’s values can be assigned and accessed using square braces ([]) with a key to obtain its value. 18
  • 20. Dictionary  Common Dictionary Functions • cmp(dict1, dict2) : compares elements of both dict. • len(dict) : gives the total number of (key, value) pairs in the dictionary.  Common Dictionary Methods Method Description dict.keys() Returns list of dict's keys dict.values() Returns list of dict's values dict.items() Returns a list of dict's (key, value) tuple pairs dict.get(key, default=None) For key, returns value or default if key not in dict dict.has_key(key) Returns True if key in dict, False otherwise dict.update(dict2) Adds dict2's key-values pairs to dict dict.clear() Removes all elements of dict 20
  • 21. Dictionary  This example shows how to access, update and delete dictionary elements:  The output: 21
  • 22. Exercises 1. Reverse a list in Python 2. Accept any three string from one input() 3. Create a string containing an integer, then convert that string into an actual integer object using int(). Test that your new object is a number by multiplying it by another number and displaying the result. 4. Write python program that Count all letters, digits, and special symbols from a given string. 5. Given a list of numbers. write a program to turn every item of a list into its square. Given: numbers = [1, 2, 3, 4, 5, 6, 7] Expected output: [1, 4, 9, 16, 25, 36, 49] 22