SlideShare a Scribd company logo
1 of 17
Learn Python – for beginners
Part-I
Raj Kumar Rampelli
Outline
• Introduction
• Variables
• Strings
• Command line arguments
• if statement
• while loop
• Functions
• File Handling
6/16/2016 Rajkumar Rampelli - Learn Python 2
Python Introduction
• Python is a high level programming language like a C/C++/Java etc..
• Python is processed at runtime by Interpreter
– No need to compile the python program.
• Python source file has an extension of .py
• Python versions: 1.x, 2.x and 3.x
– Both 2.x (Python) and 3.x (Python3) are currently used
• Python console:
– Allow us to run one line of python code, executes it and display the
output on the console, repeat it (Read-Eval-Print-Loop)
– quit() or exit() to close the console
• Python applications including web, scripting, computing and
artificial intelligence etc.
• Python instruction/code doesn’t end with semicolon ; and it
doesn’t use any special symbol for this.
6/16/2016 Rajkumar Rampelli - Learn Python 3
Write Python code – Variables usage
• Variables don’t have any specific data type here like int/float/char etc.
– A variable can be assigned with different type of values in the same program
• Adding comments in program
– # symbol is used to add a single line comment in the program (symbol // in C)
– “”” “”” used for multiple line comment here (/* */ in C)
• Python is case sensitive, i.e. Last and last are two different variables.
• Variable name should have only letters, numbers, underscore and
theyu can’t start with numbers.
• NameError:
– Occur when program tries to access a variable which is not defined in the program.
• del statement used to delete a variable
– Syntax: del variable_name
#Save below code in sample.py and run
A = 100
print(A)
A = “Python”
print(A)
Output:
100
‘Python’
6/16/2016 Rajkumar Rampelli - Learn Python 4
Strings
• String is created by entering text between single quotes or double quotes.
“Python” is a string and ‘Python’ is a string.
String basic operations
Concatenation
str() is a special function that
converts input to string.
"spam"+"eggs" -> output: spameggs
"spam"+","+"eggs" -> output: spam,eggs
"2"+"2" output: 22
1 + "2" -> output: TypeError
str(1) + “2” -> output: 12
Multiplication "spam"*3 -> output: spamspamspam
4 * "3" -> output: 3333
"s" * "r" -> output: TypeError
"s" * 7.0 -> output: TypeError
Replace "hello me".replace("me", "world") -> output: hello world
Startswith "This is car".startswith("This") -> output: True
Endswith "This is car".endswith("This") -> output: False
Upper() "I am a boy".upper() -> output: I AM A BOY
Lower() ”I am a Boy”.lower() -> output: i am a boy
Split() "spam, eggs, ham".split(",") -> output: ['spam', ' eggs', ' ham']6/16/2016 Rajkumar Rampelli - Learn Python 5
Command line arguments
• Python sys module provides a way to access command line arguments
– sys.argv is a list containing all arguments passed via command line arguments
and sys.argv[0] contains the program name
#!/usr/bin/python
import sys
“””len() is a special function that returns the number of characters in a
string or number of strings in a list.”””
#To avoid concatenation error, converted length into string using str().
print('Number of arguments:‘ + str(len(sys.argv)) + 'arguments.‘)
print('Argument List:‘ + str(sys.argv))
Run: sample.py arg1 arg2 arg3
Output:
Number of arguments: 4 arguments
Argument List: [‘sample.py', 'arg1', 'arg2', 'arg3']
Multiline
comment
(“”” text
“””)
Single line
comment
(#)
6/16/2016 Rajkumar Rampelli - Learn Python 6
if statement
• Python uses indentation (white space at the
beginning of a line) to delimit the block of
code. Syntax:
• elif - short form of else if
– Or use standard way
if expression:
statement
else:
if expression:
statement
if condition:
line1
line2
elif condition2:
line4
else:
line5
Print(“hello”)
White
space
or tab
6/16/2016 Rajkumar Rampelli - Learn Python 7
while loop
• Use it when run a code for certain number of times. Syntax:
• infinite loop –
while 1==1:
print("in the loop")
• break - To end a while loop prematurely,
then break statement can be used.
i = 1
while 1==1:
if i > 5:
break
print("in the loop")
i = i + 1
• Continue - Unlike break, continue jumps back to the top of the
loop, rather than stopping it.
• break and continue usage is same across other languages (ex: C)
while condition:
statement1
statement2
It will print “In the
loop” for 4 times.
6/16/2016 Rajkumar Rampelli - Learn Python 8
else with loops
• Using else with for and while loops, the code
within it is called if the loop finished normally
(when a break statement doesn’t cause an exit
from the loop).
i = 50
while i < 100:
if i % 3 == 4:
print(“breaking”)
break
i = i + 1
else:
print(“Unbroken”)
Output:
Unbroken
6/16/2016 Rajkumar Rampelli - Learn Python 9
else with try/except
• The else statement can also be used with
try/except statements. In this case, the code
within it is only executed if no error occurs in
the try statement.
try:
print(1)
except ZeroDivisionError:
print(2)
else:
print(3)
Output:
1
3
6/16/2016 Rajkumar Rampelli - Learn Python 10
User defined functions
• create a function by using the def statement
and must be defined before they are called,
else you would see NameError.
• Functions can be assigned and reassigned to
variables and later referenced by those values
• The code in the function must be indented.
def my_func():
print("I am in function")
my_func()
func2 = my_func()
print(“before func2”)
func2()
Output:
I am in function
before func2
I am in function
6/16/2016 Rajkumar Rampelli - Learn Python 11
Functions with arguments and return
value
def max(x, y):
if x >= y:
return x
else:
return y
z = max(8, 5)
print(z)
Output:
8
6/16/2016 Rajkumar Rampelli - Learn Python 12
File handling
Open file:
myfile = open("filename.txt", mode);
The argument of the open() function is the path to
the file. You can specify the mode used to open a file
by 2nd argument.
r : Open file in read mode, which is the default.
w : Write mode, for re-writing the contents of the file
a : Append mode, for adding new content to the end
of the file
b : Open file in a binary mode, used for non-text files.
Writing Files - write()
write() - writes a string to the file.
"w" mode will create a file if not
exist. If exist, the contents of the
file will be deleted.
write() returns the number of
bytes written to the file, if
successful.
file = open("new.txt", "w")
file.write("Writting to the file")
file.close()  closes file.
Reading file:
1. read() : reads entire file
2. readline() : return a list in which each
element is a line in the file.
Example:
cont = myfile.read()
print(cont) -> print all the contents of the file.
print(“Before readline()”)
cont2 = myfile.readline()
print(cont2)
Input file contains:
Line1
line2
Output:
Line1
line2
Before readline()
[“line1”, “line2”]
6/16/2016 Rajkumar Rampelli - Learn Python 13
C language Vs Python
C language Python language
Special operators (++ and --) works
I.e. a++; --a;
It doesn't support ++ and --. Throws Syntax error.
Each statement in C ends with semicolon ; No use of ; here.
Curly braces are used to delimit blocks of code
If (condition)
{
Statement1;
Statement2;
}
It uses white spaces for this purpose
If condition:
Statement1
Statement2
Compiling the program before execution is mandatory Python program directly executed by using interpreter. No
compiler here.
Boolean operators are && and || and ! Boolean operators are and, or and not
Uses // for one line comment
Uses /* */ for multiple line comment
Uses # for one line comment
Uses """ """ for multi line comments (Docstrings).
Uses #include to import standard library functions
#include<stdio.h>
Uses import keyword to include standard library functions
Import math
Void assert(int expression)
Expression -This can be a variable or any C expression. If
expression evaluates to TRUE, assert() does nothing.
If expression evaluates to FALSE, assert() displays an error
message on stderr(standard error stream to display error
messages and diagnostics) and aborts program execution.
assert expression
Example
assert 1 + 1 == 3
NULL – represents absence of value None - represents absence of value
Don't have automatic memory management. Automatic Garbage collection exist
6/16/2016 Rajkumar Rampelli - Learn Python 14
Next: Part-2 will have followings. Stay Tune..!!
• Data Structures
– Lists
– Sets
– Dictionaries
– Tuples
• Exception Handling
• Python modules
• Regular expressions – tool for string manipulations
• Standard libraries
• Python Programs
6/16/2016 Rajkumar Rampelli - Learn Python 15
References
• Install Learn Python (SoloLearn) from Google
Play :
https://play.google.com/store/apps/details?id
=com.sololearn.python&hl=en
• Learn Python the Harder Way :
http://learnpythonthehardway.org/
6/16/2016 Rajkumar Rampelli - Learn Python 16
Thank you
• Have a look at
• My PPTs:
http://www.slideshare.net/rampalliraj/
• My Blog: http://practicepeople.blogspot.in/
6/16/2016 Rajkumar Rampelli - Learn Python 17

More Related Content

What's hot

Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in pythonSantosh Verma
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Edureka!
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
Python & jupyter notebook installation
Python & jupyter notebook installationPython & jupyter notebook installation
Python & jupyter notebook installationAnamta Sayyed
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners Sujith Kumar
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in JavaRavi_Kant_Sahu
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & ImportMohd Sajjad
 
Variables in python
Variables in pythonVariables in python
Variables in pythonJaya Kumari
 
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]vikram mahendra
 
Threads V4
Threads  V4Threads  V4
Threads V4Sunil OS
 

What's hot (20)

Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Header files in c
Header files in cHeader files in c
Header files in c
 
Python Control structures
Python Control structuresPython Control structures
Python Control structures
 
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Python Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String FormattingPython Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String Formatting
 
Python & jupyter notebook installation
Python & jupyter notebook installationPython & jupyter notebook installation
Python & jupyter notebook installation
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
 
List in Python
List in PythonList in Python
List in Python
 
Database programming
Database programmingDatabase programming
Database programming
 
Basics of python
Basics of pythonBasics of python
Basics of python
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Python
PythonPython
Python
 
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
 
Threads V4
Threads  V4Threads  V4
Threads V4
 

Viewers also liked

System Booting Process overview
System Booting Process overviewSystem Booting Process overview
System Booting Process overviewRajKumar Rampelli
 
Network security and cryptography
Network security and cryptographyNetwork security and cryptography
Network security and cryptographyRajKumar Rampelli
 
Tasklet vs work queues (Deferrable functions in linux)
Tasklet vs work queues (Deferrable functions in linux)Tasklet vs work queues (Deferrable functions in linux)
Tasklet vs work queues (Deferrable functions in linux)RajKumar Rampelli
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2RajKumar Rampelli
 
Introduction to Kernel and Device Drivers
Introduction to Kernel and Device DriversIntroduction to Kernel and Device Drivers
Introduction to Kernel and Device DriversRajKumar Rampelli
 

Viewers also liked (8)

System Booting Process overview
System Booting Process overviewSystem Booting Process overview
System Booting Process overview
 
Linux Kernel I/O Schedulers
Linux Kernel I/O SchedulersLinux Kernel I/O Schedulers
Linux Kernel I/O Schedulers
 
Network security and cryptography
Network security and cryptographyNetwork security and cryptography
Network security and cryptography
 
Tasklet vs work queues (Deferrable functions in linux)
Tasklet vs work queues (Deferrable functions in linux)Tasklet vs work queues (Deferrable functions in linux)
Tasklet vs work queues (Deferrable functions in linux)
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2
 
Linux GIT commands
Linux GIT commandsLinux GIT commands
Linux GIT commands
 
Introduction to Kernel and Device Drivers
Introduction to Kernel and Device DriversIntroduction to Kernel and Device Drivers
Introduction to Kernel and Device Drivers
 
Linux watchdog timer
Linux watchdog timerLinux watchdog timer
Linux watchdog timer
 

Similar to Learn python – for beginners

Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programmingChetan Giridhar
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointJavaTpoint.Com
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdfsamiwaris2
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way PresentationAmira ElSharkawy
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C LanguageMohamed Elsayed
 
Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1Devashish Kumar
 
While-For-loop in python used in college
While-For-loop in python used in collegeWhile-For-loop in python used in college
While-For-loop in python used in collegessuser7a7cd61
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language CourseVivek chan
 

Similar to Learn python – for beginners (20)

Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
Python Tutorial for Beginner
Python Tutorial for BeginnerPython Tutorial for Beginner
Python Tutorial for Beginner
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
 
Open mp intro_01
Open mp intro_01Open mp intro_01
Open mp intro_01
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C Language
 
Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1
 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
 
pyton Notes1
pyton Notes1pyton Notes1
pyton Notes1
 
While-For-loop in python used in college
While-For-loop in python used in collegeWhile-For-loop in python used in college
While-For-loop in python used in college
 
Python Session - 4
Python Session - 4Python Session - 4
Python Session - 4
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language Course
 

More from RajKumar Rampelli

Writing Character driver (loadable module) in linux
Writing Character driver (loadable module) in linuxWriting Character driver (loadable module) in linux
Writing Character driver (loadable module) in linuxRajKumar Rampelli
 
Introduction to Python - Running Notes
Introduction to Python - Running NotesIntroduction to Python - Running Notes
Introduction to Python - Running NotesRajKumar Rampelli
 
Linux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver OverviewLinux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver OverviewRajKumar Rampelli
 

More from RajKumar Rampelli (7)

Writing Character driver (loadable module) in linux
Writing Character driver (loadable module) in linuxWriting Character driver (loadable module) in linux
Writing Character driver (loadable module) in linux
 
Introduction to Python - Running Notes
Introduction to Python - Running NotesIntroduction to Python - Running Notes
Introduction to Python - Running Notes
 
Linux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver OverviewLinux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver Overview
 
Sql injection attack
Sql injection attackSql injection attack
Sql injection attack
 
Turing awards seminar
Turing awards seminarTuring awards seminar
Turing awards seminar
 
Higher education importance
Higher education importanceHigher education importance
Higher education importance
 
C compilation process
C compilation processC compilation process
C compilation process
 

Recently uploaded

Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
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
 
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
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
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
 
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
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
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
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinojohnmickonozaleda
 
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
 

Recently uploaded (20)

Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
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
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.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
 
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
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.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
 
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
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
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
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipino
 
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
 
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
 

Learn python – for beginners

  • 1. Learn Python – for beginners Part-I Raj Kumar Rampelli
  • 2. Outline • Introduction • Variables • Strings • Command line arguments • if statement • while loop • Functions • File Handling 6/16/2016 Rajkumar Rampelli - Learn Python 2
  • 3. Python Introduction • Python is a high level programming language like a C/C++/Java etc.. • Python is processed at runtime by Interpreter – No need to compile the python program. • Python source file has an extension of .py • Python versions: 1.x, 2.x and 3.x – Both 2.x (Python) and 3.x (Python3) are currently used • Python console: – Allow us to run one line of python code, executes it and display the output on the console, repeat it (Read-Eval-Print-Loop) – quit() or exit() to close the console • Python applications including web, scripting, computing and artificial intelligence etc. • Python instruction/code doesn’t end with semicolon ; and it doesn’t use any special symbol for this. 6/16/2016 Rajkumar Rampelli - Learn Python 3
  • 4. Write Python code – Variables usage • Variables don’t have any specific data type here like int/float/char etc. – A variable can be assigned with different type of values in the same program • Adding comments in program – # symbol is used to add a single line comment in the program (symbol // in C) – “”” “”” used for multiple line comment here (/* */ in C) • Python is case sensitive, i.e. Last and last are two different variables. • Variable name should have only letters, numbers, underscore and theyu can’t start with numbers. • NameError: – Occur when program tries to access a variable which is not defined in the program. • del statement used to delete a variable – Syntax: del variable_name #Save below code in sample.py and run A = 100 print(A) A = “Python” print(A) Output: 100 ‘Python’ 6/16/2016 Rajkumar Rampelli - Learn Python 4
  • 5. Strings • String is created by entering text between single quotes or double quotes. “Python” is a string and ‘Python’ is a string. String basic operations Concatenation str() is a special function that converts input to string. "spam"+"eggs" -> output: spameggs "spam"+","+"eggs" -> output: spam,eggs "2"+"2" output: 22 1 + "2" -> output: TypeError str(1) + “2” -> output: 12 Multiplication "spam"*3 -> output: spamspamspam 4 * "3" -> output: 3333 "s" * "r" -> output: TypeError "s" * 7.0 -> output: TypeError Replace "hello me".replace("me", "world") -> output: hello world Startswith "This is car".startswith("This") -> output: True Endswith "This is car".endswith("This") -> output: False Upper() "I am a boy".upper() -> output: I AM A BOY Lower() ”I am a Boy”.lower() -> output: i am a boy Split() "spam, eggs, ham".split(",") -> output: ['spam', ' eggs', ' ham']6/16/2016 Rajkumar Rampelli - Learn Python 5
  • 6. Command line arguments • Python sys module provides a way to access command line arguments – sys.argv is a list containing all arguments passed via command line arguments and sys.argv[0] contains the program name #!/usr/bin/python import sys “””len() is a special function that returns the number of characters in a string or number of strings in a list.””” #To avoid concatenation error, converted length into string using str(). print('Number of arguments:‘ + str(len(sys.argv)) + 'arguments.‘) print('Argument List:‘ + str(sys.argv)) Run: sample.py arg1 arg2 arg3 Output: Number of arguments: 4 arguments Argument List: [‘sample.py', 'arg1', 'arg2', 'arg3'] Multiline comment (“”” text “””) Single line comment (#) 6/16/2016 Rajkumar Rampelli - Learn Python 6
  • 7. if statement • Python uses indentation (white space at the beginning of a line) to delimit the block of code. Syntax: • elif - short form of else if – Or use standard way if expression: statement else: if expression: statement if condition: line1 line2 elif condition2: line4 else: line5 Print(“hello”) White space or tab 6/16/2016 Rajkumar Rampelli - Learn Python 7
  • 8. while loop • Use it when run a code for certain number of times. Syntax: • infinite loop – while 1==1: print("in the loop") • break - To end a while loop prematurely, then break statement can be used. i = 1 while 1==1: if i > 5: break print("in the loop") i = i + 1 • Continue - Unlike break, continue jumps back to the top of the loop, rather than stopping it. • break and continue usage is same across other languages (ex: C) while condition: statement1 statement2 It will print “In the loop” for 4 times. 6/16/2016 Rajkumar Rampelli - Learn Python 8
  • 9. else with loops • Using else with for and while loops, the code within it is called if the loop finished normally (when a break statement doesn’t cause an exit from the loop). i = 50 while i < 100: if i % 3 == 4: print(“breaking”) break i = i + 1 else: print(“Unbroken”) Output: Unbroken 6/16/2016 Rajkumar Rampelli - Learn Python 9
  • 10. else with try/except • The else statement can also be used with try/except statements. In this case, the code within it is only executed if no error occurs in the try statement. try: print(1) except ZeroDivisionError: print(2) else: print(3) Output: 1 3 6/16/2016 Rajkumar Rampelli - Learn Python 10
  • 11. User defined functions • create a function by using the def statement and must be defined before they are called, else you would see NameError. • Functions can be assigned and reassigned to variables and later referenced by those values • The code in the function must be indented. def my_func(): print("I am in function") my_func() func2 = my_func() print(“before func2”) func2() Output: I am in function before func2 I am in function 6/16/2016 Rajkumar Rampelli - Learn Python 11
  • 12. Functions with arguments and return value def max(x, y): if x >= y: return x else: return y z = max(8, 5) print(z) Output: 8 6/16/2016 Rajkumar Rampelli - Learn Python 12
  • 13. File handling Open file: myfile = open("filename.txt", mode); The argument of the open() function is the path to the file. You can specify the mode used to open a file by 2nd argument. r : Open file in read mode, which is the default. w : Write mode, for re-writing the contents of the file a : Append mode, for adding new content to the end of the file b : Open file in a binary mode, used for non-text files. Writing Files - write() write() - writes a string to the file. "w" mode will create a file if not exist. If exist, the contents of the file will be deleted. write() returns the number of bytes written to the file, if successful. file = open("new.txt", "w") file.write("Writting to the file") file.close()  closes file. Reading file: 1. read() : reads entire file 2. readline() : return a list in which each element is a line in the file. Example: cont = myfile.read() print(cont) -> print all the contents of the file. print(“Before readline()”) cont2 = myfile.readline() print(cont2) Input file contains: Line1 line2 Output: Line1 line2 Before readline() [“line1”, “line2”] 6/16/2016 Rajkumar Rampelli - Learn Python 13
  • 14. C language Vs Python C language Python language Special operators (++ and --) works I.e. a++; --a; It doesn't support ++ and --. Throws Syntax error. Each statement in C ends with semicolon ; No use of ; here. Curly braces are used to delimit blocks of code If (condition) { Statement1; Statement2; } It uses white spaces for this purpose If condition: Statement1 Statement2 Compiling the program before execution is mandatory Python program directly executed by using interpreter. No compiler here. Boolean operators are && and || and ! Boolean operators are and, or and not Uses // for one line comment Uses /* */ for multiple line comment Uses # for one line comment Uses """ """ for multi line comments (Docstrings). Uses #include to import standard library functions #include<stdio.h> Uses import keyword to include standard library functions Import math Void assert(int expression) Expression -This can be a variable or any C expression. If expression evaluates to TRUE, assert() does nothing. If expression evaluates to FALSE, assert() displays an error message on stderr(standard error stream to display error messages and diagnostics) and aborts program execution. assert expression Example assert 1 + 1 == 3 NULL – represents absence of value None - represents absence of value Don't have automatic memory management. Automatic Garbage collection exist 6/16/2016 Rajkumar Rampelli - Learn Python 14
  • 15. Next: Part-2 will have followings. Stay Tune..!! • Data Structures – Lists – Sets – Dictionaries – Tuples • Exception Handling • Python modules • Regular expressions – tool for string manipulations • Standard libraries • Python Programs 6/16/2016 Rajkumar Rampelli - Learn Python 15
  • 16. References • Install Learn Python (SoloLearn) from Google Play : https://play.google.com/store/apps/details?id =com.sololearn.python&hl=en • Learn Python the Harder Way : http://learnpythonthehardway.org/ 6/16/2016 Rajkumar Rampelli - Learn Python 16
  • 17. Thank you • Have a look at • My PPTs: http://www.slideshare.net/rampalliraj/ • My Blog: http://practicepeople.blogspot.in/ 6/16/2016 Rajkumar Rampelli - Learn Python 17