- Python is a scripting programming language.
- Python is free and easy to learn.
- Python is powerful object oriented programming
- Comparable to Perl, Ruby, Scheme, or Java
- Code can be grouped into modules and packages
- Applications : Web applications, Automation, Scientific modelling, Big data applications and many more.
Python Modules
Many modules are available like math, os, time ,etc . please refer the link : https://docs.python.org/3/py-modindex.html
Python Real time using Applications
The Most Popular Python and Django Websites are listed Below
- YouTube (python + django)
- Dropbox (python +django)
- Google (python +django)
- Quora (python +django)
- Instagram (python +django)
- Spotify (python +django)
- Reddit (python +django)
- Yahoo map (python +django)
- Hibmunk (python +django)
Python interpreter software
Install in windows
Note : tested on windows 10, 64bit with python 3.6.5.
- Download & Install official python software from this link.
- Once Installations done, now going to test the first getting started with hello world print sting example.
Install Android App
Get Start : Hello World Example
- Open a new file with .py extension. Ex : Hello-World.py .
- Then write the Simple code print(“ArunEworld”) , and save that.
- Now right click the file Hello-World.py , you can see Edit with IDLE option. Open your file with that option.
- Now Click the Run –> Run Module in tab or click F5 Button.
- Now another pop will open. that is the output windows the you can see you output or result also can see if any error in your program.
- This example is a simple and just print the ArunEworld word in the output screen using print function.
Python IDE
PyCharm IDE
- This IDE is fulfilled for professional
- Download : https://www.jetbrains.com/pycharm/?fromMenu
Install PIP : Install pip using this below link
Remember This
- In c language like don’t need to put ; Semicolon command every end of the line. Because Python inter predictor run every line by line also paragraph. Ex print(“ArunEworld”) this will execute with out error in python
Skip command
- Single Line Skip : # (Hash). Example : A = 0 #A is int Variable
- Paragraph Skip : “”” (Triple Quat). Example : “”” ArunEworld is a educational organization
Python Keyword
Totally 33 Keywords
- ‘False’,
- ‘None’,
- ‘True’,
- ‘and’,
- ‘as’,
- ‘assert’,
- ‘break’,
- ‘class’,
- ‘continue’,
- ‘def’,
- ‘del’,
- ‘elif’,
- ‘else’,
- ‘except’,
- ‘finally’,
- ‘for’,
- ‘from’,
- ‘global’,
- ‘if’,
- ‘import’,
- ‘in’,
- ‘is’,
- ‘lambda’,
- ‘nonlocal’,
- ‘not’,
- ‘or’,
- ‘pass’,
- ‘raise’,
- ‘return’,
- ‘try’,
- ‘while’,
- ‘with’,
- ‘yield’
#!/usr/bin/env python3
"""
Keywords (from "graminit.c")
This file is automatically generated; please don't muck it up!
To update the symbols in this file, 'cd' to the top directory of the python source tree after building the interpreter and run:
./python Lib/keyword.py
"""
__all__ = ["iskeyword", "kwlist"]
kwlist = [
# --start keywords--
'False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield',
# --end keywords--
]
iskeyword = frozenset(kwlist).__contains__
def main():
import sys
import re
args = sys.argv[1:]
iptfile = args and args[0] or "Python/graminit.c"
if len(args) > 1:
optfile = args[1]
else:
optfile = "Lib/keyword.py"
# load the output skeleton from the target, taking care to preserve its
# newline convention.
with open(optfile, newline='') as fp:
format = fp.readlines()
nl = format[0][len(format[0].strip()):] if format else '\n'
# scan the source file for keywords
with open(iptfile) as fp:
strprog = re.compile('"([^"]+)"')
lines = []
for line in fp:
if '{1, "' in line:
match = strprog.search(line)
if match:
lines.append(" '" + match.group(1) + "'," + nl)
lines.sort()
# insert the lines of keywords into the skeleton
try:
start = format.index("#--start keywords--" + nl) + 1
end = format.index("#--end keywords--" + nl)
format[start:end] = lines
except ValueError:
sys.stderr.write("target does not contain format markers\n")
sys.exit(1)
# write the output file
with open(optfile, 'w', newline='') as fp:
fp.writelines(format)
if __name__ == "__main__":
main()
Python keywords using cooking-related examples.
| Keyword | Cooking Example |
|---|---|
False | The oven is not hot → oven_is_hot = False |
True | Water is boiling → water_is_boiling = True |
None | No ingredient added yet → spice = None |
and | if oven_is_hot and dough_is_ready: → Start baking |
or | if eggs_available or tofu_available: → Make protein dish |
not | if not fridge_door_closed: → Alert to close it |
as | import spicebox as sb → Use sb.pepper later |
assert | assert temperature >= 180 → Ensure oven is hot enough |
break | Stop cooking if something burns → if food_burns: break |
class | Define a recipe structure → class Recipe: |
continue | Skip burnt chapati and go to next → if chapati.is_burnt(): continue |
def | Define a recipe → def make_chapati(): |
del | Remove old ingredient from list → del ingredients[2] |
elif | if temp < 100: ... elif temp == 100: ... → Decide boiling state |
else | if salt: ... else: add_salt() |
except | try: cut_vegetables() except KnifeError: → Handle if knife breaks |
finally | Always clean up after cooking → finally: clean_kitchen() |
for | for egg in egg_carton: → Crack each egg |
from | from kitchen import mixer → Use specific tool |
global | Change total_dishes globally → global total_dishes |
if | if oil_hot: → Start frying |
import | import kitchen_tools |
in | if 'salt' in ingredients: |
is | if spice is None: |
lambda | filter(lambda x: x.is_ripe(), fruits) |
nonlocal | Access outer recipe variable inside nested one |
pass | Placeholder for steps: def step(): pass |
raise | if ingredient_expired: raise ValueError |
return | return finished_dish |
try | try: bake() → Attempt baking |
while | while water_not_boiling: → Keep heating |
with | with open_fridge() as fridge: → Safely access fridge contents |
yield | yield chapati → Produce one item at a time in a generator |
# Built-in constants
is_kitchen_open = True
oven_temperature = None # not set initially
# Define a cooking class
class Kitchen:
def __init__(self):
self.ingredients = ['flour', 'water', 'salt', 'oil']
self.tools = ['pan', 'spoon']
self.ready = False
def prepare(self):
if 'flour' in self.ingredients and 'water' in self.ingredients:
self.ready = True
else:
self.ready = False
# Create a function to cook
def cook_dish(dish_name):
global oven_temperature
oven_temperature = 180 # Set globally
recipe_steps = ['mix', 'knead', 'roll', 'cook']
for step in recipe_steps:
if step == 'cook':
try:
# Simulate cooking
print(f"Cooking {dish_name} at {oven_temperature}°C")
assert oven_temperature >= 150, "Oven too cold!"
except AssertionError as e:
print("Error:", e)
finally:
print("Finished cooking step.")
elif step == 'knead':
continue # Kneading skipped for demo
else:
print(f"{step.capitalize()}ing the dough...")
return f"{dish_name} is ready!"
# Main control
def main():
kitchen = Kitchen()
kitchen.prepare()
if kitchen.ready:
print("Kitchen is ready!")
elif not kitchen.ready:
print("Missing ingredients.")
else:
print("Unreachable state.")
# Using with statement
with open('cook_log.txt', 'w') as log:
log.write("Cooking started.\n")
dish = 'chapati'
result = cook_dish(dish)
log.write(result + '\n')
# Use a lambda to filter optional ingredients
optional_ingredients = ['butter', 'cheese', None]
available = list(filter(lambda x: x is not None, optional_ingredients))
print("Optional ingredients:", available)
# Use yield to simulate serving one at a time
def serve(dishes):
for d in dishes:
yield f"Serving {d}"
for plate in serve([dish]):
print(plate)
break # serve only one for now
# Raise an error if kitchen is not clean
kitchen_clean = False
if not kitchen_clean:
raise Exception("Clean your kitchen!")
# Declare nonlocal example
def outer():
spice = 'none'
def inner():
nonlocal spice
spice = 'masala'
inner()
print("Spice used:", spice)
# Run the script
if __name__ == "__main__":
try:
main()
except Exception as err:
print("Exception occurred:", err)
outer()
Python Functions
Print Function
- Print function returns
- Example 1 : print the strings with format specifier.
mystring = “ArunEworld” print(“String: %s” % mystring)
- Example 2: You don’t need to declare the type of the variable with format spcifier print(“ArunEworld”)
Print the variables and numbers
myint = 7 print(myint) myfloat = 7.0 print(myfloat) myfloat = float(7) print(myfloat)
Print the Strings
mystring = ‘hello’ print(mystring) mystring = “hello” print(mystring) mystring = “Don’t worry about apostrophes” print(mystring) one = 1 two = 2 three = one + two print(three) hello = “hello” world = “world” helloworld = hello + ” ” + world print(helloworld) a, b = 3, 4 print(a,b
Error May Come
Error : Missing operator
# This will not work! one = 1 two = 2 hello = “hello” print(one + two + hello)
Error : for above program Traceback (most recent call last): File “<stdin>”, line 6, in <module> print(one + two + hello) TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’
Error : NameError
- Code : if run like this print(ArunEworld)then the below error will come.
- Error : NameError: name ‘ArunEworld’ is not defined .
Input function
How to make python to wait for a pressed key?
- To use input() function to wait a your python application coed
- Ex : input(“Press Enter to continue…”)
Python Loops
- If Loop
- while loop
if loop
x = 1 if x == 1: # indented four spaces print(“x is 1.”)
While Loop
- Repeat execute the your program based on the while condition if true.
- Syntax while expression: statement(s)
- Expression : True – Any non zero value or false (Any combination condition)
- Statements : Your application code, Its may be single line of code or multiple block of code.
Example
- if the below example print the value 0 to 8 and then exits from while loop
count = 0 while (count < 9): print ‘The count is:’, count count = count + 1 print “Counter reach 9 value. !” print “ArunEworld”
output The count is: 0 The count is: 1 The count is: 2 The count is: 3 The count is: 4 The count is: 5 The count is: 6 The count is: 7 The count is: 8 Counter reach 9 value ArunEworld
Infinite Loop using while
- code : while true : print(“ArunEworld”)
- output : ArunEworld print infinite time, printing speed is based on system frequency.
Python List
- Lists are very similar to arrays.
- They can contain any type of variable, and they can contain as many variables as you wish.
- Lists can also be iterated over in a very simple manner.
- Here is an example of how to build a list.
mylist.append(1) mylist.append(2) mylist.append(3) print(mylist[0]) # prints 1 print(mylist[1]) # prints 2 print(mylist[2]) # prints 3 # prints out 1,2,3 for x in mylist: print(x)
List : Accessing an index which does not exist generates an exception (an error).
mylist = [1,2,3] print(mylist[10])
Python Tuples
- Tuples are listed items, But its can’t edited.
Python Basic Operators
Arithmetic Operators
number = 1 + 2 * 3 / 4.0 print(number)
Modulo Operators
remainder = 11 % 3 print(remainder)
Multiplication Operator
remainder = 11 % 3 print(remainder)
Using Operators with Strings
helloworld = “hello” + ” ” + “world” print(helloworld)
Python also supports multiplying strings to form a string with a repeating sequence:
lotsofhellos = “hello” * 10 print(lotsofhellos)
Using Operators with Lists
even_numbers = [2,4,6,8] odd_numbers = [1,3,5,7] all_numbers = odd_numbers + even_numbers print(all_numbers)
- Another example
print([1,2,3] * 3)
User Defined Functions
Function Declaration:
Syntax : Def FunctionName(parameters) : ‘fucntion_docstring’ function_suite return [expression]
- Def – Keyword (in python fuctions begin with keyword)
- FunctionName – Function call name
- () – Paranthsis
- parameters – Any input perameters (Ardument replaed with this paranthesis
- fucntion_docstring – Documentation fucntion of the string (Optional)
- : – The code start every function
- function_suite – Code Block
- return [expression] – return statement of the function. With no arguments as same on.
Note : parameters, return expression and documentation strings are optional
Examples : A sample function named ‘square’ is defined here.
def square(n) : “Returns square of a given number” return n**2 print(square.__doc__) print(square(3)) print(square(10))
Result Returns square of a given number 9 100 >>>
- def – keyword
- square(n) : – Square is function Name
- “Returns square of a given number” – Function Document contains the doc strings, will store in Special variable called “__doc__ “
- return n**2 – Returns the square value using return statement
- print(square.__doc__) – Doc string will be stored in special variable “__doc__” associative with function, and it can be access by using “.” Dot operator, as shown in the print statement.
- print(square(3)) – By calling the square function with in the 3 argument value, The output will be the square of 9
- print(square(10)) – By calling the square function with in the 100 argument value, The output will be the square of 10 is 100
Note : Any function can be called by passing required arguments inside the parenthesis within after the function name
Function call :
- Function call generally 4 different arguments like Required Arguments, Keyword Arguments, Default Arguments, variable Length Arguments.
Note : Any function can be called by passing required arguments inside the parenthesis within after the function name
Function call type :
A function can be called using the following types of formal arguments
- Required Arguments
- Keyword Arguments
- Default Arguments
- Variable length Arguments
Required Arguments
- Required arguments are the non keyword arguments
Example def showname(name, age) : “This is fucntion displays the arguments passed” print(“Name : “, name) print(“Age : “, age) showname(“ArunEworld”, 21) showname(21, “ArunEworld”)
Results
- In the example “showname” is the function withh two parameters as “name” and “age”.
- This function is called twise with same non keyword arguments passed in different order.
- In each of the calls the arguments which associated with paramete it involved which thier defined.
- Here we observe the different when two calls.
(‘Name : ‘, ‘ArunEworld’) (‘Age : ‘, 21) (‘Name : ‘, 21) (‘Age : ‘, ‘ArunEworld’)
Keyword Arguments
- Keyword arguments is use when function call.
- Keyword arguments are identified by parameter name.
- Keyword arguments can be called any order.
Example def showinfo(name, age) : ”’ This is fucntion displays passed values of a person name and age ”’ print(“Name : “, name) print(“Age : “, age) showinfo(“ArunEworld.com”, 21) showinfo(age = 21, name = “ArunEworld”)
Results (‘Name : ‘, ‘ArunEworld’) (‘Age : ‘, 21) (‘Name : ‘, ‘ArunEworld’) (‘Age : ‘, 21)
Default Arguments
- A default argument is an argument that assumes a default value if a value is not provided in the function call for that arguments.
Example def showinfo_2(name, age=10 ) : ”’ This is fucntion displays passed values of a person name and age ”’ print(“Name : “, name) print(“Age : “, age) showinfo_2(“ArunEworld.com”) showinfo_2(age = 21, name = “ArunEworld”) showinfo_2(“ArunEworld”, age = 2) #showinfo_2(21, name = “ArunEworld”) # when its run get error like invalid function call
Results
- Note : (very Important ) -> python does not allow passing non-keyword arguments after keyword arguments.
(‘Name : ‘, ‘ArunEworld.com’) (‘Age : ‘, 10) (‘Name : ‘, ‘ArunEworld’) (‘Age : ‘, 21) (‘Name : ‘, ‘ArunEworld’) (‘Age : ‘, 25)
Variable length Arguments
Example def showifo(name, *vartuple, ** vardict) : “”” this function displays all passed arguments””” print(“Nmae : “, name) for arg in vartuple: print(“variable non_kwd argument : “, arg”) for key in vardict: print(“variable kwd argument : “, vadict[key]) showinfo(“ArunEworld”) showinfo(“ArunPrakash”, 21, ‘M’, ‘Fb/ArunEworld’) showinfo(“ArunEworld”, 25, city=”bangalore”, sex=”M”
pdf2image 0.1.0
Python Interview Questions
Q : What are the key features of Python
- Python is interpreted language.
- Write your code or make your application with python is very easy and fast but running its very slow compared to compiled c programming.
- Its Dynamically typed : No need to declare variable type. you can do with out error : x=5 , x=”ArunEworld”
- Object Oriented programming like C++, – Allows define classes along with the composition and inheritance.
- functions are first-class objects – This means that they can be assigned to variables, returned from other functions and passed into functions. Classes are also first class objects
- Applications : web applications, automation, scientific modelling, big data applications and many more
Q : What is the difference between list and tuples?
- List : Its listed but can edited.
- tuples : It’s are listed but can’t edited
Python Example
DateTime Module.py
from turtle import *
from datetime import datetime
mode("logo")
DateTime=datetime.today()
print(DateTime)
Year = DateTime.year
Month = DateTime.month
Day = DateTime.day
Hour = DateTime.hour
Minutes = DateTime.minute
Second = DateTime.second
print(Year)
print(Month)
print(Day)
print(Hour)
print(Minutes)
print(Second)
FileRename.py
# Pythono3 code to rename multiple
# files in a directory or folder
# importing os module
import os
os.rename('Prakash','Arun')
# Function to rename multiple files
#def main():
# i = 0
# for filename in os.listdir("Arun"):
# dst ="Prakash" + str(i) + ".jpg"
# src ='Arun'+ filename
# dst ='Arun'+ dst
# rename() function will
# rename all the files
# os.rename(src, dst)
# i += 1
# os.rename('Prakash','Arun')
# Driver Code
#if __name__ == '__main__':
# # Calling main() function
# main()
ping.py
# "Platform_Type" variable hold the platform type
#print the explame code platform type in console
print("ArunEworld: Ping test to host")
#Need for call the os.system() with ping command
import os
import platform
#Need for identify the platform type like windows or others using platform.system().lower()
#set the variable with host name (Enter the host here)
hostname = "www.aruneworld.com"
#This if, else loop will find the platform type
if platform.system().lower() == "windows":
Platform_Type = "ping -n 1 "
else:
Platform_Type = "ping -c 1 "
#print the platform type in console
print("Ping is running in ",platform.system().lower(), " Platform")
# os.system fun will return 0- got response, 1 - not got the response
if os.system(Platform_Type + hostname) == 0:
print(hostname, "is live")
else:
print(hostname, "is not live")
##Output
#ArunEworld: Ping test to host
#Ping is running in windows Platform
#www.aruneworld.com is live
RepeatTimerRunFun.py
import time
starttime = time.time()
while True:
print("tick")
time.sleep(60.0 - ((time.time() - starttime) % 60.0))
timer.py
import time
starttime = time.time()
while True:
print ("tick : ", time.time())
time.sleep(1)
#Output
#tick : 1618632561.4104075
#tick : 1618632562.4975173
tick : 1618632563.5195172
tick : 1618632564.5325844
tick : 1618632565.5645263
tick : 1618632566.5756495
tick : 1618632567.5856884
tick : 1618632568.6081123
tick : 1618632569.6243045
tick : 1618632570.630945
tick : 1618632571.6762278
Reference
- Beginner overview guide : https://wiki.python.org/moin/BeginnersGuide/Overview
- Simple Programs : https://wiki.python.org/moin/SimplePrograms
- Application of python : https://www.python.org/about/apps/
- Interview Questions : https://www.edureka.co/blog/interview-questions/python-interview-questions/
- Course : https://www.edureka.co/python
- Learn python YouTube Channel Check the playlist : https://www.youtube.com/channel/UCqrILQNl5Ed9Dz6CGMyvMTQ/playlists
