SlideShare une entreprise Scribd logo
1  sur  4
Télécharger pour lire hors ligne
Python examples

          Compile Python program:python filename.py

                         First.py

#! /usr/bin/env python
#Above is valid only if you are using the script in linux and you can
understand this is comment :)// /*
import os##include<os.h>
print(50*"-")#will print '-' fifty times
print("file name :%s"%(__file__))#will reveal current file name
printf("%s",__file__)
name=raw_input("What is your name :")#get i/p from user
print ("Name:"+name)#print the name
print(50*"=")



                     list_comp.py
#! /usr/bin/env python
def looping():
     x=[]
     for y in range(20):
           if y%2 == 0:
                x.append(y)
     print x

def list_comp():
      x=[y for y in range(20) if y%2 ==0 ]
      print x

looping()
list_comp()
import dis
dis.dis(looping)
dis.dis(list_comp)
fav_movies.py
#! /usr/bin/env python
"""This file contains few ways how one can read and write content to
file in python"""
count=0
file="fav_movies.txt"
file_="fav_movie_list.txt"
movie_list=[]
def write_to_file():
      '''Writing string to file'''
      global file,count
      fp=open(file,'w')
      print 50*"="
      print("Enter 5 movie names you like ")
      while count < 5 :
            movie=(raw_input("Enter the fav movie:"))+"n"
            movie_list.append(movie)
            fp.write(movie)
            count+=1
      fp.close()
      print 50*"="
def read_a_line():
      global file
      fp=open(file,'r')
      fp.close()
      print ("n Reading one line")
def readlines():
      global file
      fp=open(file,"r")
      print fp.readline()#will read only one line
      fp.close()
      print "="*50
def write_list():
      global file_,movie_list
      print("Writing entire list into a file ")
      f=open(file_,"w")
      f.writelines(movie_list)#write entire list to a file
      f.close()
      print "="*50
def read_using_for():
      global file
print ("reading input using for loop")
     for line in open(file):
           print line
     print "="*50
def one_liner():
     global file
     print ("read entire contents in a single line")
     print(open(file).read())#will read all lines in one stretch
     print 50*'='
write_to_file()
print ("doc for %s:%s "%
(write_to_file.func_name,write_to_file.__doc__))
read_a_line()
readlines()
write_list()
read_using_for()
one_liner()
print ("__doc__",__doc__)

                    get_particular_line.py
#! /usr/bin/env python
file="text.txt"
import linecache
theline=linecache.getline(file,2)
print theline
zip_length.py
#! /usr/bin/env python
import zipfile
z=zipfile.ZipFile("day1.odp.zip","r")
for filename in z.namelist():
      print "File:",filename
      bytes=z.read(filename)
      print 'has',len(bytes),'bytes'

                          details.py
#! /usr/bin/env python
import socket
myname=socket.getfqdn(socket.gethostname())
myaddr=socket.gethostbyname(myname)
print "System name:%s"%(myname),"Ip:",myaddr
password_gen.py
import string,random
chars=string.lowercase+string.uppercase+string.digits
print ''.join([random.choice(chars) for i in range(0,10)])

Contenu connexe

Tendances

جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲Mohammad Reza Kamalifard
 
Logrotate sh
Logrotate shLogrotate sh
Logrotate shBen Pope
 
The Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveThe Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveEleanor McHugh
 
Raspberry pi Part 4
Raspberry pi Part 4Raspberry pi Part 4
Raspberry pi Part 4Techvilla
 
Pop3stat sh
Pop3stat shPop3stat sh
Pop3stat shBen Pope
 
Scripting 101
Scripting 101Scripting 101
Scripting 101ohardebol
 
북스터디 디스커버리 Go 언어
북스터디 디스커버리 Go 언어북스터디 디스커버리 Go 언어
북스터디 디스커버리 Go 언어동규 이
 
Playing 44CON CTF for fun and profit
Playing 44CON CTF for fun and profitPlaying 44CON CTF for fun and profit
Playing 44CON CTF for fun and profit44CON
 
Coding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMCoding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMRaveen Perera
 
File-I/O -- ist doch ganz einfach, oder?
File-I/O -- ist doch ganz einfach, oder?File-I/O -- ist doch ganz einfach, oder?
File-I/O -- ist doch ganz einfach, oder?Christian Kauhaus
 
The Ring programming language version 1.5.1 book - Part 24 of 180
The Ring programming language version 1.5.1 book - Part 24 of 180The Ring programming language version 1.5.1 book - Part 24 of 180
The Ring programming language version 1.5.1 book - Part 24 of 180Mahmoud Samir Fayed
 
Cis 216 – shell scripting
Cis 216 – shell scriptingCis 216 – shell scripting
Cis 216 – shell scriptingDan Morrill
 
The Ring programming language version 1.2 book - Part 15 of 84
The Ring programming language version 1.2 book - Part 15 of 84The Ring programming language version 1.2 book - Part 15 of 84
The Ring programming language version 1.2 book - Part 15 of 84Mahmoud Samir Fayed
 

Tendances (19)

جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
 
gitfs
gitfsgitfs
gitfs
 
I phone
I phoneI phone
I phone
 
Logrotate sh
Logrotate shLogrotate sh
Logrotate sh
 
The Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveThe Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's Perspective
 
Raspberry pi Part 4
Raspberry pi Part 4Raspberry pi Part 4
Raspberry pi Part 4
 
01 linux basics
01 linux basics01 linux basics
01 linux basics
 
Pop3stat sh
Pop3stat shPop3stat sh
Pop3stat sh
 
Bash Programming
Bash ProgrammingBash Programming
Bash Programming
 
Shell and perl scripting classes in mumbai
Shell and perl scripting classes in mumbaiShell and perl scripting classes in mumbai
Shell and perl scripting classes in mumbai
 
Scripting 101
Scripting 101Scripting 101
Scripting 101
 
북스터디 디스커버리 Go 언어
북스터디 디스커버리 Go 언어북스터디 디스커버리 Go 언어
북스터디 디스커버리 Go 언어
 
Sender
SenderSender
Sender
 
Playing 44CON CTF for fun and profit
Playing 44CON CTF for fun and profitPlaying 44CON CTF for fun and profit
Playing 44CON CTF for fun and profit
 
Coding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMCoding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBM
 
File-I/O -- ist doch ganz einfach, oder?
File-I/O -- ist doch ganz einfach, oder?File-I/O -- ist doch ganz einfach, oder?
File-I/O -- ist doch ganz einfach, oder?
 
The Ring programming language version 1.5.1 book - Part 24 of 180
The Ring programming language version 1.5.1 book - Part 24 of 180The Ring programming language version 1.5.1 book - Part 24 of 180
The Ring programming language version 1.5.1 book - Part 24 of 180
 
Cis 216 – shell scripting
Cis 216 – shell scriptingCis 216 – shell scripting
Cis 216 – shell scripting
 
The Ring programming language version 1.2 book - Part 15 of 84
The Ring programming language version 1.2 book - Part 15 of 84The Ring programming language version 1.2 book - Part 15 of 84
The Ring programming language version 1.2 book - Part 15 of 84
 

Similaire à Workshop programs

Similaire à Workshop programs (20)

working with files
working with filesworking with files
working with files
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16
 
Fileinc
FileincFileinc
Fileinc
 
Unit5
Unit5Unit5
Unit5
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
Python File functions
Python File functionsPython File functions
Python File functions
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
 
File management
File managementFile management
File management
 
File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Python build your security tools.pdf
Python build your security tools.pdfPython build your security tools.pdf
Python build your security tools.pdf
 
file handling1
file handling1file handling1
file handling1
 
Python 3.x File Object Manipulation Cheatsheet
Python 3.x File Object Manipulation CheatsheetPython 3.x File Object Manipulation Cheatsheet
Python 3.x File Object Manipulation Cheatsheet
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
Satz1
Satz1Satz1
Satz1
 
File handling in c
File  handling in cFile  handling in c
File handling in c
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
 
File handling in c language
File handling in c languageFile handling in c language
File handling in c language
 

Dernier

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Dernier (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

Workshop programs

  • 1. Python examples Compile Python program:python filename.py First.py #! /usr/bin/env python #Above is valid only if you are using the script in linux and you can understand this is comment :)// /* import os##include<os.h> print(50*"-")#will print '-' fifty times print("file name :%s"%(__file__))#will reveal current file name printf("%s",__file__) name=raw_input("What is your name :")#get i/p from user print ("Name:"+name)#print the name print(50*"=") list_comp.py #! /usr/bin/env python def looping(): x=[] for y in range(20): if y%2 == 0: x.append(y) print x def list_comp(): x=[y for y in range(20) if y%2 ==0 ] print x looping() list_comp() import dis dis.dis(looping) dis.dis(list_comp)
  • 2. fav_movies.py #! /usr/bin/env python """This file contains few ways how one can read and write content to file in python""" count=0 file="fav_movies.txt" file_="fav_movie_list.txt" movie_list=[] def write_to_file(): '''Writing string to file''' global file,count fp=open(file,'w') print 50*"=" print("Enter 5 movie names you like ") while count < 5 : movie=(raw_input("Enter the fav movie:"))+"n" movie_list.append(movie) fp.write(movie) count+=1 fp.close() print 50*"=" def read_a_line(): global file fp=open(file,'r') fp.close() print ("n Reading one line") def readlines(): global file fp=open(file,"r") print fp.readline()#will read only one line fp.close() print "="*50 def write_list(): global file_,movie_list print("Writing entire list into a file ") f=open(file_,"w") f.writelines(movie_list)#write entire list to a file f.close() print "="*50 def read_using_for(): global file
  • 3. print ("reading input using for loop") for line in open(file): print line print "="*50 def one_liner(): global file print ("read entire contents in a single line") print(open(file).read())#will read all lines in one stretch print 50*'=' write_to_file() print ("doc for %s:%s "% (write_to_file.func_name,write_to_file.__doc__)) read_a_line() readlines() write_list() read_using_for() one_liner() print ("__doc__",__doc__) get_particular_line.py #! /usr/bin/env python file="text.txt" import linecache theline=linecache.getline(file,2) print theline zip_length.py #! /usr/bin/env python import zipfile z=zipfile.ZipFile("day1.odp.zip","r") for filename in z.namelist(): print "File:",filename bytes=z.read(filename) print 'has',len(bytes),'bytes' details.py #! /usr/bin/env python import socket myname=socket.getfqdn(socket.gethostname()) myaddr=socket.gethostbyname(myname) print "System name:%s"%(myname),"Ip:",myaddr