SlideShare ist ein Scribd-Unternehmen logo
1 von 22
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

Weitere ähnliche Inhalte

Ähnlich wie Python Basic Syntax Guide

Introduction To Programming with Python-3
Introduction To Programming with Python-3Introduction To Programming with Python-3
Introduction To Programming with Python-3Syed Farjad Zia Zaidi
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumarSujith Kumar
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming LanguageTahani Al-Manie
 
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.pptxdeivanayagamramachan
 
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 FundamentalsPraveen M Jigajinni
 
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.pdfTHIRUGAMING1
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptxrohithprabhas1
 
Python data type
Python data typePython data type
Python data typenuripatidar
 
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.pptx0901EO211056SUBHRATT
 
Presentation on python data type
Presentation on python data typePresentation on python data type
Presentation on python data typeswati kushwaha
 
Data types in python
Data types in pythonData types in python
Data types in pythonRaginiJain21
 
Basic data types in python
Basic data types in pythonBasic data types in python
Basic data types in pythonsunilchute1
 
Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning ParrotAI
 

Ähnlich wie Python Basic Syntax Guide (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
 
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
 
Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning
 

Mehr von 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
 

Kürzlich hochgeladen

HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 

Kürzlich hochgeladen (20)

Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 

Python Basic Syntax Guide

  • 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