Learn python – for beginners

RajKumar Rampelli
RajKumar RampelliSenior System Software Engineer at NVIDIA
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
1 de 17

Recomendados

Python made easy por
Python made easy Python made easy
Python made easy Abhishek kumar
4.6K visualizações225 slides
C++ ppt por
C++ pptC++ ppt
C++ pptparpan34
45.7K visualizações214 slides
C language por
C languageC language
C languagemarar hina
497 visualizações17 slides
Beginning Python Programming por
Beginning Python ProgrammingBeginning Python Programming
Beginning Python ProgrammingSt. Petersburg College
2.1K visualizações34 slides
Programming in c por
Programming in cProgramming in c
Programming in cvineet4523
830 visualizações35 slides
Algoritmo - tipos de dados por
Algoritmo - tipos de dadosAlgoritmo - tipos de dados
Algoritmo - tipos de dadosProfessor Samuel Ribeiro
7.7K visualizações30 slides

Mais conteúdo relacionado

Mais procurados

Aula 02 - Principios da Orientação a Objetos (POO) por
Aula 02 - Principios da Orientação a Objetos (POO)Aula 02 - Principios da Orientação a Objetos (POO)
Aula 02 - Principios da Orientação a Objetos (POO)Daniel Brandão
2K visualizações44 slides
Steps for c program execution por
Steps for c program executionSteps for c program execution
Steps for c program executionRumman Ansari
13.1K visualizações13 slides
Apostila de Fundamentos Java por
Apostila de Fundamentos JavaApostila de Fundamentos Java
Apostila de Fundamentos JavaMarcio Marinho
11.7K visualizações309 slides
Python PPT por
Python PPTPython PPT
Python PPTEdureka!
38.9K visualizações20 slides
Input and output in C++ por
Input and output in C++Input and output in C++
Input and output in C++Nilesh Dalvi
7.3K visualizações57 slides
Operator & Expression in c++ por
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++bajiajugal
10.7K visualizações34 slides

Mais procurados(20)

Aula 02 - Principios da Orientação a Objetos (POO) por Daniel Brandão
Aula 02 - Principios da Orientação a Objetos (POO)Aula 02 - Principios da Orientação a Objetos (POO)
Aula 02 - Principios da Orientação a Objetos (POO)
Daniel Brandão2K visualizações
Steps for c program execution por Rumman Ansari
Steps for c program executionSteps for c program execution
Steps for c program execution
Rumman Ansari13.1K visualizações
Apostila de Fundamentos Java por Marcio Marinho
Apostila de Fundamentos JavaApostila de Fundamentos Java
Apostila de Fundamentos Java
Marcio Marinho11.7K visualizações
Python PPT por Edureka!
Python PPTPython PPT
Python PPT
Edureka!38.9K visualizações
Input and output in C++ por Nilesh Dalvi
Input and output in C++Input and output in C++
Input and output in C++
Nilesh Dalvi7.3K visualizações
Operator & Expression in c++ por bajiajugal
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
bajiajugal10.7K visualizações
Python 101: Python for Absolute Beginners (PyTexas 2014) por Paige Bailey
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey29.8K visualizações
Estrutura de dados - Aula de Revisão (Linguagem C/C++, Função, Vetor, Matriz,... por Leinylson Fontinele
Estrutura de dados - Aula de Revisão (Linguagem C/C++, Função, Vetor, Matriz,...Estrutura de dados - Aula de Revisão (Linguagem C/C++, Função, Vetor, Matriz,...
Estrutura de dados - Aula de Revisão (Linguagem C/C++, Função, Vetor, Matriz,...
Leinylson Fontinele1.8K visualizações
Aula 1 - Introdução a POO por Daniel Brandão
Aula 1 -  Introdução a POOAula 1 -  Introdução a POO
Aula 1 - Introdução a POO
Daniel Brandão3.6K visualizações
Aula 02 - Introdução ao PHP por Daniel Brandão
Aula 02 - Introdução ao PHPAula 02 - Introdução ao PHP
Aula 02 - Introdução ao PHP
Daniel Brandão3.5K visualizações
C basics por thirumalaikumar3
C   basicsC   basics
C basics
thirumalaikumar31.7K visualizações
Files and streams por Pranali Chaudhari
Files and streamsFiles and streams
Files and streams
Pranali Chaudhari6.4K visualizações
aula 04 - Logica de programacao por Aislan Rafael
aula 04 - Logica de programacaoaula 04 - Logica de programacao
aula 04 - Logica de programacao
Aislan Rafael4.9K visualizações
Python basics por Jyoti shukla
Python basicsPython basics
Python basics
Jyoti shukla470 visualizações
Python Style Guide por Jiayun Zhou
Python Style GuidePython Style Guide
Python Style Guide
Jiayun Zhou356 visualizações
Introduction to python por Yi-Fan Chu
Introduction to pythonIntroduction to python
Introduction to python
Yi-Fan Chu515 visualizações
Python tutorial por Vijay Chaitanya
Python tutorialPython tutorial
Python tutorial
Vijay Chaitanya6.8K visualizações
C fundamental por Selvam Edwin
C fundamentalC fundamental
C fundamental
Selvam Edwin3.1K visualizações

Destaque

System Booting Process overview por
System Booting Process overviewSystem Booting Process overview
System Booting Process overviewRajKumar Rampelli
10.9K visualizações11 slides
Linux Kernel I/O Schedulers por
Linux Kernel I/O SchedulersLinux Kernel I/O Schedulers
Linux Kernel I/O SchedulersRajKumar Rampelli
3.9K visualizações13 slides
Network security and cryptography por
Network security and cryptographyNetwork security and cryptography
Network security and cryptographyRajKumar Rampelli
2.4K visualizações18 slides
Tasklet vs work queues (Deferrable functions in linux) por
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
8.9K visualizações13 slides
Learn python - for beginners - part-2 por
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2RajKumar Rampelli
5.1K visualizações24 slides
Linux GIT commands por
Linux GIT commandsLinux GIT commands
Linux GIT commandsRajKumar Rampelli
2.7K visualizações8 slides

Destaque(8)

System Booting Process overview por RajKumar Rampelli
System Booting Process overviewSystem Booting Process overview
System Booting Process overview
RajKumar Rampelli10.9K visualizações
Linux Kernel I/O Schedulers por RajKumar Rampelli
Linux Kernel I/O SchedulersLinux Kernel I/O Schedulers
Linux Kernel I/O Schedulers
RajKumar Rampelli3.9K visualizações
Network security and cryptography por RajKumar Rampelli
Network security and cryptographyNetwork security and cryptography
Network security and cryptography
RajKumar Rampelli2.4K visualizações
Tasklet vs work queues (Deferrable functions in linux) por RajKumar 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)
RajKumar Rampelli8.9K visualizações
Learn python - for beginners - part-2 por RajKumar Rampelli
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2
RajKumar Rampelli5.1K visualizações
Linux GIT commands por RajKumar Rampelli
Linux GIT commandsLinux GIT commands
Linux GIT commands
RajKumar Rampelli2.7K visualizações
Introduction to Kernel and Device Drivers por RajKumar Rampelli
Introduction to Kernel and Device DriversIntroduction to Kernel and Device Drivers
Introduction to Kernel and Device Drivers
RajKumar Rampelli4.8K visualizações
Linux watchdog timer por RajKumar Rampelli
Linux watchdog timerLinux watchdog timer
Linux watchdog timer
RajKumar Rampelli3K visualizações

Similar a Learn python – for beginners

Tutorial on-python-programming por
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programmingChetan Giridhar
1.4K visualizações62 slides
Python Tutorial for Beginner por
Python Tutorial for BeginnerPython Tutorial for Beginner
Python Tutorial for Beginnerrajkamaltibacademy
331 visualizações62 slides
C Programming Language Tutorial for beginners - JavaTpoint por
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointJavaTpoint.Com
22.8K visualizações39 slides
Python (3).pdf por
Python (3).pdfPython (3).pdf
Python (3).pdfsamiwaris2
23 visualizações30 slides
Learn Python The Hard Way Presentation por
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way PresentationAmira ElSharkawy
912 visualizações33 slides
Open mp intro_01 por
Open mp intro_01Open mp intro_01
Open mp intro_01Oleg Nazarevych
886 visualizações30 slides

Similar a Learn python – for beginners(20)

Tutorial on-python-programming por Chetan Giridhar
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
Chetan Giridhar1.4K visualizações
Python Tutorial for Beginner por rajkamaltibacademy
Python Tutorial for BeginnerPython Tutorial for Beginner
Python Tutorial for Beginner
rajkamaltibacademy331 visualizações
C Programming Language Tutorial for beginners - JavaTpoint por JavaTpoint.Com
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
JavaTpoint.Com22.8K visualizações
Python (3).pdf por samiwaris2
Python (3).pdfPython (3).pdf
Python (3).pdf
samiwaris223 visualizações
Learn Python The Hard Way Presentation por Amira ElSharkawy
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
Amira ElSharkawy912 visualizações
Open mp intro_01 por Oleg Nazarevych
Open mp intro_01Open mp intro_01
Open mp intro_01
Oleg Nazarevych886 visualizações
A brief introduction to C Language por Mohamed Elsayed
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C Language
Mohamed Elsayed517 visualizações
Introduction to Python Part-1 por Devashish Kumar
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1
Devashish Kumar632 visualizações
Python fundamentals por natnaelmamuye
Python fundamentalsPython fundamentals
Python fundamentals
natnaelmamuye92 visualizações
This project includes several but all of your changes.docx por write5
This project includes several but all of your changes.docxThis project includes several but all of your changes.docx
This project includes several but all of your changes.docx
write55 visualizações
pyton Notes1 por Amba Research
pyton Notes1pyton Notes1
pyton Notes1
Amba Research437 visualizações
Python Session - 4 por AnirudhaGaikwad4
Python Session - 4Python Session - 4
Python Session - 4
AnirudhaGaikwad4377 visualizações
Python basics por Hoang Nguyen
Python basicsPython basics
Python basics
Hoang Nguyen2K visualizações
Python basics por Luis Goldster
Python basicsPython basics
Python basics
Luis Goldster110 visualizações
Python basics por Harry Potter
Python basicsPython basics
Python basics
Harry Potter610 visualizações
Python basics por Tony Nguyen
Python basicsPython basics
Python basics
Tony Nguyen89 visualizações
Python basics por James Wong
Python basicsPython basics
Python basics
James Wong50 visualizações
Python basics por Young Alista
Python basicsPython basics
Python basics
Young Alista187 visualizações
Python basics por Fraboni Ec
Python basicsPython basics
Python basics
Fraboni Ec59 visualizações
Complete C++ programming Language Course por Vivek chan
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language Course
Vivek chan5.1K visualizações

Mais de RajKumar Rampelli

Writing Character driver (loadable module) in linux por
Writing Character driver (loadable module) in linuxWriting Character driver (loadable module) in linux
Writing Character driver (loadable module) in linuxRajKumar Rampelli
2K visualizações11 slides
Introduction to Python - Running Notes por
Introduction to Python - Running NotesIntroduction to Python - Running Notes
Introduction to Python - Running NotesRajKumar Rampelli
1.3K visualizações47 slides
Linux Kernel MMC Storage driver Overview por
Linux Kernel MMC Storage driver OverviewLinux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver OverviewRajKumar Rampelli
17.6K visualizações26 slides
Sql injection attack por
Sql injection attackSql injection attack
Sql injection attackRajKumar Rampelli
6K visualizações17 slides
Turing awards seminar por
Turing awards seminarTuring awards seminar
Turing awards seminarRajKumar Rampelli
693 visualizações13 slides
Higher education importance por
Higher education importanceHigher education importance
Higher education importanceRajKumar Rampelli
3.1K visualizações10 slides

Mais de RajKumar Rampelli(7)

Writing Character driver (loadable module) in linux por RajKumar Rampelli
Writing Character driver (loadable module) in linuxWriting Character driver (loadable module) in linux
Writing Character driver (loadable module) in linux
RajKumar Rampelli2K visualizações
Introduction to Python - Running Notes por RajKumar Rampelli
Introduction to Python - Running NotesIntroduction to Python - Running Notes
Introduction to Python - Running Notes
RajKumar Rampelli1.3K visualizações
Linux Kernel MMC Storage driver Overview por RajKumar Rampelli
Linux Kernel MMC Storage driver OverviewLinux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver Overview
RajKumar Rampelli17.6K visualizações
Sql injection attack por RajKumar Rampelli
Sql injection attackSql injection attack
Sql injection attack
RajKumar Rampelli6K visualizações
Turing awards seminar por RajKumar Rampelli
Turing awards seminarTuring awards seminar
Turing awards seminar
RajKumar Rampelli693 visualizações
Higher education importance por RajKumar Rampelli
Higher education importanceHigher education importance
Higher education importance
RajKumar Rampelli3.1K visualizações
C compilation process por RajKumar Rampelli
C compilation processC compilation process
C compilation process
RajKumar Rampelli9.7K visualizações

Último

Class 10 English notes 23-24.pptx por
Class 10 English notes 23-24.pptxClass 10 English notes 23-24.pptx
Class 10 English notes 23-24.pptxTARIQ KHAN
125 visualizações53 slides
AUDIENCE - BANDURA.pptx por
AUDIENCE - BANDURA.pptxAUDIENCE - BANDURA.pptx
AUDIENCE - BANDURA.pptxiammrhaywood
77 visualizações44 slides
discussion post.pdf por
discussion post.pdfdiscussion post.pdf
discussion post.pdfjessemercerail
130 visualizações1 slide
ISO/IEC 27001 and ISO/IEC 27005: Managing AI Risks Effectively por
ISO/IEC 27001 and ISO/IEC 27005: Managing AI Risks EffectivelyISO/IEC 27001 and ISO/IEC 27005: Managing AI Risks Effectively
ISO/IEC 27001 and ISO/IEC 27005: Managing AI Risks EffectivelyPECB
574 visualizações18 slides
231112 (WR) v1 ChatGPT OEB 2023.pdf por
231112 (WR) v1  ChatGPT OEB 2023.pdf231112 (WR) v1  ChatGPT OEB 2023.pdf
231112 (WR) v1 ChatGPT OEB 2023.pdfWilfredRubens.com
151 visualizações21 slides
Drama KS5 Breakdown por
Drama KS5 BreakdownDrama KS5 Breakdown
Drama KS5 BreakdownWestHatch
73 visualizações2 slides

Último(20)

Class 10 English notes 23-24.pptx por TARIQ KHAN
Class 10 English notes 23-24.pptxClass 10 English notes 23-24.pptx
Class 10 English notes 23-24.pptx
TARIQ KHAN125 visualizações
AUDIENCE - BANDURA.pptx por iammrhaywood
AUDIENCE - BANDURA.pptxAUDIENCE - BANDURA.pptx
AUDIENCE - BANDURA.pptx
iammrhaywood77 visualizações
discussion post.pdf por jessemercerail
discussion post.pdfdiscussion post.pdf
discussion post.pdf
jessemercerail130 visualizações
ISO/IEC 27001 and ISO/IEC 27005: Managing AI Risks Effectively por PECB
ISO/IEC 27001 and ISO/IEC 27005: Managing AI Risks EffectivelyISO/IEC 27001 and ISO/IEC 27005: Managing AI Risks Effectively
ISO/IEC 27001 and ISO/IEC 27005: Managing AI Risks Effectively
PECB 574 visualizações
231112 (WR) v1 ChatGPT OEB 2023.pdf por WilfredRubens.com
231112 (WR) v1  ChatGPT OEB 2023.pdf231112 (WR) v1  ChatGPT OEB 2023.pdf
231112 (WR) v1 ChatGPT OEB 2023.pdf
WilfredRubens.com151 visualizações
Drama KS5 Breakdown por WestHatch
Drama KS5 BreakdownDrama KS5 Breakdown
Drama KS5 Breakdown
WestHatch73 visualizações
Psychology KS5 por WestHatch
Psychology KS5Psychology KS5
Psychology KS5
WestHatch81 visualizações
Google solution challenge..pptx por ChitreshGyanani1
Google solution challenge..pptxGoogle solution challenge..pptx
Google solution challenge..pptx
ChitreshGyanani1117 visualizações
AI Tools for Business and Startups por Svetlin Nakov
AI Tools for Business and StartupsAI Tools for Business and Startups
AI Tools for Business and Startups
Svetlin Nakov105 visualizações
OEB 2023 Co-learning To Speed Up AI Implementation in Courses.pptx por Inge de Waard
OEB 2023 Co-learning To Speed Up AI Implementation in Courses.pptxOEB 2023 Co-learning To Speed Up AI Implementation in Courses.pptx
OEB 2023 Co-learning To Speed Up AI Implementation in Courses.pptx
Inge de Waard169 visualizações
Psychology KS4 por WestHatch
Psychology KS4Psychology KS4
Psychology KS4
WestHatch76 visualizações
ANATOMY AND PHYSIOLOGY UNIT 1 { PART-1} por DR .PALLAVI PATHANIA
ANATOMY AND PHYSIOLOGY UNIT 1 { PART-1}ANATOMY AND PHYSIOLOGY UNIT 1 { PART-1}
ANATOMY AND PHYSIOLOGY UNIT 1 { PART-1}
DR .PALLAVI PATHANIA244 visualizações
11.28.23 Social Capital and Social Exclusion.pptx por mary850239
11.28.23 Social Capital and Social Exclusion.pptx11.28.23 Social Capital and Social Exclusion.pptx
11.28.23 Social Capital and Social Exclusion.pptx
mary850239291 visualizações
Community-led Open Access Publishing webinar.pptx por Jisc
Community-led Open Access Publishing webinar.pptxCommunity-led Open Access Publishing webinar.pptx
Community-led Open Access Publishing webinar.pptx
Jisc91 visualizações
UWP OA Week Presentation (1).pptx por Jisc
UWP OA Week Presentation (1).pptxUWP OA Week Presentation (1).pptx
UWP OA Week Presentation (1).pptx
Jisc87 visualizações
Scope of Biochemistry.pptx por shoba shoba
Scope of Biochemistry.pptxScope of Biochemistry.pptx
Scope of Biochemistry.pptx
shoba shoba126 visualizações
Class 10 English lesson plans por TARIQ KHAN
Class 10 English  lesson plansClass 10 English  lesson plans
Class 10 English lesson plans
TARIQ KHAN280 visualizações
Ch. 7 Political Participation and Elections.pptx por Rommel Regala
Ch. 7 Political Participation and Elections.pptxCh. 7 Political Participation and Elections.pptx
Ch. 7 Political Participation and Elections.pptx
Rommel Regala90 visualizações

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