- Walks you through all the steps in developing applications for the Android platform, including the latest Android features like scrollable widgets, enhanced UI tools, social media integration, and new calendar and contact capabilities
- Starts off with downloading the SDK, then explains how to bring your applications to life and submit your work to the Android Market
- Includes real–world advice from expert programmers Donn Felker and Michael Burton, who break every aspect of the development process down into practical, digestible pieces
Saturday 9 March 2019
The Android OS continues to rapidly expand offering app developers access to one of the largest platforms available, and this easy–to–follow guide walks you through the development process step by step. In this new edition of the bestselling Android Application Development For Dummies, Android programming experts Michael Burton and Donn Felker explain how to download the SDK, get Eclipse up and running, code Android applications, and share your finished products with the world.
Buy :
PDF Download :
Featuring two sample programs, this book explores everything from the simple basics to advanced aspects of Android application development.
Whether you′re new to Android development or already on your way, Android Application Development For Dummies, 2nd Edition is the guide you need to dig into the app dev process!
Thursday 7 March 2019
Borland C++ Builder: The Complete Reference by Herbert Schildt
Irawen March 07, 2019 C++ No comments
C++ Builder 5 is an integrated development enviroment for building standalone, client/server, distributed and Internet-enabled Windows applications. This resource provides an introduction to the operation of the Intergrated Development Enviroment (IDE), the various tools, the debugger, the C++ language and libaries. It also gives coverage of the standard template library (STL) and Windows programming.
Buy :-
Borland C++ Builder: The Complete Reference by Herbert Schildt
PDF Download :-
Borland C++ Builder: The Complete Reference
Buy :-
Borland C++ Builder: The Complete Reference by Herbert Schildt
PDF Download :-
Borland C++ Builder: The Complete Reference
Sams Teach Yourself Database Programming with Visual C++ 6 in 21 Days
Irawen March 07, 2019 C++ No comments
In only 21 days, you'll have all the skills you need to get up and running efficiently. With this complete tutorial, you'll master the basics of database programming and then move on to the more advanced features and concepts. Understand the fundamentals of database programming in Visual C++. Master all the new and advanced database features that Visual C++6 offers. Learn how to effectively use the latest tools and features of Visual C++ for database programming by following practical, real-world examples. Get expert tips from a leading authority for programming your databases with Visual C++ 6 in the corporate environment.
Buy :-
Sams Teach Yourself Database Programming with Visual C++ 6 in 21 Days (Sams Teach Yourself in Days)
PDF Download :-
Sams Teach Yourself Database Programming with Visual C++ 6 in 21 Days (Sams Teach Yourself in Days)
Buy :-
Sams Teach Yourself Database Programming with Visual C++ 6 in 21 Days (Sams Teach Yourself in Days)
PDF Download :-
Sams Teach Yourself Database Programming with Visual C++ 6 in 21 Days (Sams Teach Yourself in Days)
C++ Programming in easy steps, 5th Edition by Mike McGrath
Irawen March 07, 2019 C++ No comments
C++ Programming in easy steps, 5th Edition begins by explaining how to install a free C++ compiler so you can quickly begin to create your own executable programs by copying the book’s examples. It demonstrates all the C++ language basics before moving on to provide examples of Object Oriented Programming (OOP).
C++ is not platform-dependent, so programs can be created on any operating system. Most illustrations in this book depict output on the Windows operating system purely because it is the most widely used desktop platform. The examples can also be created on other platforms such as Linux or macOS.
The book concludes by demonstrating how you can use your acquired knowledge to create programs graphically using a modern C++ Integrated Development Environment (IDE), such as Microsoft’s Visual Studio Community Edition.
C++ Programming in easy steps, 5th Edition has an easy-to-follow style that will appeal to:
anyone who wants to begin programming in C++
programmers moving from another programming language
students who are studying C++ Programming at school or college
those seeking a career in computing who need a fundamental understanding of object oriented programming
This book makes no assumption that you have previous knowledge of any programming language so it is suitable for the beginner to programming in C++, whether you know C or not.
Contents:
Getting started
Performing operations
Making statements
Handling strings
Reading and writing files
Pointing to data
Creating classes and objects
Harnessing polymorphism
Processing macros
Programming visually
Buy:-
C++ Programming in easy steps, 5th Edition by Mike McGrath
PDF Download :-
C++ Programming in easy steps, 5th Edition Kindle Edition by Mike McGrath
C++ is not platform-dependent, so programs can be created on any operating system. Most illustrations in this book depict output on the Windows operating system purely because it is the most widely used desktop platform. The examples can also be created on other platforms such as Linux or macOS.
The book concludes by demonstrating how you can use your acquired knowledge to create programs graphically using a modern C++ Integrated Development Environment (IDE), such as Microsoft’s Visual Studio Community Edition.
C++ Programming in easy steps, 5th Edition has an easy-to-follow style that will appeal to:
anyone who wants to begin programming in C++
programmers moving from another programming language
students who are studying C++ Programming at school or college
those seeking a career in computing who need a fundamental understanding of object oriented programming
This book makes no assumption that you have previous knowledge of any programming language so it is suitable for the beginner to programming in C++, whether you know C or not.
Contents:
Getting started
Performing operations
Making statements
Handling strings
Reading and writing files
Pointing to data
Creating classes and objects
Harnessing polymorphism
Processing macros
Programming visually
Buy:-
C++ Programming in easy steps, 5th Edition by Mike McGrath
PDF Download :-
C++ Programming in easy steps, 5th Edition Kindle Edition by Mike McGrath
Wednesday 6 March 2019
Python Closures
Before seeing what a closure is, we have to first understand what are nested functions and non-local variables.
Nested functions in Python
A function which is defined inside another function is known as nested function. Nested functions are able to access variables of the enclosing scope.
In Python, these non-local variables can be accessed only within their scope and not outside their scope. This can be illustrated by following example:
# Python program to illustrate
# nested functions
def outerFunction(text):
# nested functions
def outerFunction(text):
text = text
def innerFunction():
def innerFunction():
print(text)
innerFunction()
if __name__ == '__main__':
outerFunction('Hey!')
As we can see innerFunction() can easily be accessed inside the outerFunction body but not outside of it’s body. Hence, here, innerFunction() is treated as nested Function which uses text as non-local variable.
Python Closures
A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory.
1.It is a record that stores a function together with an environment: a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.
2.A closure—unlike a plain function—allows the function to access those captured variables through the closure’s copies of their values or references, even when the function is invoked outside their scope.
# Python program to illustrate
# closures
def outerFunction(text):
# closures
def outerFunction(text):
text = text
def innerFunction():
def innerFunction():
print(text)
return innerFunction # Note we are returning function WITHOUT parenthesis
if __name__ == '__main__':
myFunction = outerFunction('Hey!')
myFunction()
myFunction()
Output:
Hey!
1.As observed from above code, closures help to invoke function outside their scope.
2.The function innerFunction has its scope only inside the outerFunction. But with the use of closures we can easily extend its scope to invoke a function outside its scope
2.The function innerFunction has its scope only inside the outerFunction. But with the use of closures we can easily extend its scope to invoke a function outside its scope
# Python program to illustrate
# closures
import logging
logging.basicConfig(filename='example.log', level=logging.INFO)
def logger(func):
# closures
import logging
logging.basicConfig(filename='example.log', level=logging.INFO)
def logger(func):
def log_func(*args):
logging.info('Running "{}" with arguments {}'.format(func.__name__, args))
# Necessary for closure to work (returning WITHOUT parenthesis)
return log_func
return log_func
def add(x, y):
return x+y
def sub(x, y):
return x-y
add_logger = logger(add)
sub_logger = logger(sub)
add_logger(3, 3)
add_logger(4, 5)
sub_logger(10, 5)
sub_logger(20, 10)
sub_logger = logger(sub)
add_logger(3, 3)
add_logger(4, 5)
sub_logger(10, 5)
sub_logger(20, 10)
Output:
6
9
5
10
9
5
10
When and why to use Closures:
1.As closures are used as callback functions, they provide some sort of data hiding. This helps us to reduce the use of global variables. 2.When we have few functions in our code, closures prove to be efficient way. But if we need to have many functions, then go for class (OOP).
Precision Handling in Python
Precision Handling in Python
Python in its definition allows to handle precision of floating point numbers in several ways using different functions. Most of them are defined under the “math” module. Some of the most used operations are discussed in this article.
1. trunc() :- This function is used to eliminate all decimal part of the floating point number and return the integer without the decimal part.
2. ceil() :- This function is used to print the least integer greater than the given number.
3. floor() :- This function is used to print the greatest integer smaller than the given integer.
# Python code to demonstrate ceil(), trunc()
# and floor()
# importing "math" for precision function
import math
# initializing value
a = 3.4536
# using trunc() to print integer after truncating
print ("The integral value of number is : ",end="")
print (math.trunc(a))
# using ceil() to print number after ceiling
print ("The smallest integer greater than number is : ",end="")
print (math.ceil(a))
# using floor() to print number after flooring
print ("The greatest integer smaller than number is : ",end="")
print (math.floor(a))
# and floor()
# importing "math" for precision function
import math
# initializing value
a = 3.4536
# using trunc() to print integer after truncating
print ("The integral value of number is : ",end="")
print (math.trunc(a))
# using ceil() to print number after ceiling
print ("The smallest integer greater than number is : ",end="")
print (math.ceil(a))
# using floor() to print number after flooring
print ("The greatest integer smaller than number is : ",end="")
print (math.floor(a))
Output:
The integral value of number is : 3
The smallest integer greater than number is : 4
The greatest integer smaller than number is : 3
The smallest integer greater than number is : 4
The greatest integer smaller than number is : 3
Setting Precision
There are many ways to set precision of floating point value. Some of them is discussed below.
1. Using “%” :- “%” operator is used to format as well as set precision in python. This is similar to “printf” statement in C programming.
2. Using format() :- This is yet another way to format the string for setting precision.
3. Using round(x,n) :- This function takes 2 arguments, number and the number till which we want decimal part rounded.
# Python code to demonstrate precision
# and round()
# initializing value
a = 3.4536
# using "%" to print value till 2 decimal places
print ("The value of number till 2 decimal place(using %) is : ",end=" ")
print ('%.2f'%a)
# using format() to print value till 2 decimal places
print ("The value of number till 2 decimal place(using format()) is : ",end=" ")
print ("{0:.2f}".format(a))
# using round() to print value till 2 decimal places
print ("The value of number till 2 decimal place(using round()) is : ",end=" ")
print (round(a,2))
# and round()
# initializing value
a = 3.4536
# using "%" to print value till 2 decimal places
print ("The value of number till 2 decimal place(using %) is : ",end=" ")
print ('%.2f'%a)
# using format() to print value till 2 decimal places
print ("The value of number till 2 decimal place(using format()) is : ",end=" ")
print ("{0:.2f}".format(a))
# using round() to print value till 2 decimal places
print ("The value of number till 2 decimal place(using round()) is : ",end=" ")
print (round(a,2))
Output:
The value of number till 2 decimal place(using %) is : 3.45
The value of number till 2 decimal place(using format()) is : 3.45
The value of number till 2 decimal place(using round()) is : 3.45
The value of number till 2 decimal place(using format()) is : 3.45
The value of number till 2 decimal place(using round()) is : 3.45
Tuesday 5 March 2019
Beginning PHP 5 and MySQL 5: From Novice to Professional (Beginning Series: Open Source) by W. Gilmore (Author)
Irawen March 05, 2019 PHP No comments
Beginning PHP and MySQL 5: From Novice to Professional, Second Edition offers comprehensive information about two of the most prominent open source technologies on the planet: the PHP scripting language and the MySQL database server. Essentially three books in one, this second edition covers PHP 5, MySQL 5, and how these two popular open source technologies work together to create powerful websites. The book is packed with practical examples and insight into real-world challenges. It is based on the author's 7 years of experience working with these technologies. You will repeatedly refer to this book as a valuable instructional tool and reference guide.
PDF Download
Buy:Beginning PHP 5 and MySQL 5: From Novice to Professional (Beginning Series: Open Source) Paperback – Import, 1 Jan 2006 by W. Gilmore (Author)
Yield Instead of return in Python
When to use yield instead of return in Python?
The yield statement suspends function’s execution and sends a value back to caller, but retains enough state to enable function to resume where it is left off. When resumed, the function continues execution immediately after the last yield run. This allows its code to produce a series of values over time, rather them computing them at once and sending them back like a list.
Let’s see with an example:
Let’s see with an example:
# A Simple Python program to demonstrate working
# of yield
# A generator function that yields 1 for first time,
# 2 second time and 3 third time
def simpleGeneratorFun():
# of yield
# A generator function that yields 1 for first time,
# 2 second time and 3 third time
def simpleGeneratorFun():
yield 1
yield 2
yield 3
yield 2
yield 3
# Driver code to check above generator function
for value in simpleGeneratorFun():
for value in simpleGeneratorFun():
print(value)
Output:
1
2
3
2
3
Return sends a specified value back to its caller whereas Yield can produce a sequence of values. We should use yield when we want to iterate over a sequence, but don’t want to store the entire sequence in memory.
Yield are used in Python generators. A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.
# A Python program to generate squares from 1
# to 100 using yield and therefore generator
# An infinite generator function that prints
# next square number. It starts with 1
def nextSquare():
# to 100 using yield and therefore generator
# An infinite generator function that prints
# next square number. It starts with 1
def nextSquare():
i = 1;
# An Infinite loop to generate squares
while True:
# An Infinite loop to generate squares
while True:
yield i*i
i += 1 # Next execution resumes
# from this point
i += 1 # Next execution resumes
# from this point
# Driver code to test above generator
# function
for num in nextSquare():
# function
for num in nextSquare():
if num > 100:
break
print(num)
Output:
1
4
9
16
25
36
49
64
81
100
4
9
16
25
36
49
64
81
100
Empty Function in Python
In C/C++ and Java, we can write empty function as following
// An empty function in C/C++/Java
void fun() { }
In Python, if we write something like following in Python, it would produce compiler error.
# Incorrect empty function in Python
def fun():
Output:
IndentationError: expected an indented block
In Python, to write empty functions, we use pass statement. pass is a special statement in Python that does nothing. It only works as a dummy statement.
In Python, to write empty functions, we use pass statement. pass is a special statement in Python that does nothing. It only works as a dummy statement.
# Correct way of writing empty function
# in Python
def fun():
# in Python
def fun():
pass
We can use pass in empty while statement also.
# Empty loop in Python
mutex = True
while (mutex == True) :
# Empty loop in Python
mutex = True
while (mutex == True) :
pass
We can use pass in empty if else statements.
# Empty in if/else in Python
mutex = True
if (mutex == True) :
# Empty in if/else in Python
mutex = True
if (mutex == True) :
pass
else :
print("False")
Monday 4 March 2019
Function Decorator in Python
Following are important facts about functions in Python that are useful to understand decorator functions.
1.In Python, we can define a function inside another function.
2.In Python, a function can be passed as parameter to another function (a function can also return another function).
# A Python program to demonstrate that a function
# can be defined inside another function and a
# function can be passed as parameter.
# Adds a welcome message to the string
def messageWithWelcome(str):
# can be defined inside another function and a
# function can be passed as parameter.
# Adds a welcome message to the string
def messageWithWelcome(str):
# Nested function
def addWelcome():
def addWelcome():
return "Welcome to "
# Return concatenation of addWelcome()
# and str.
return addWelcome() + str
# and str.
return addWelcome() + str
# To get site name to which welcome is added
def site(site_name):
def site(site_name):
return site_name
print messageWithWelcome(site("PythonWorld"))
Output:
Welcome to PythonWorld
Function Decorator
A decorator is a function that takes a function as its only parameter and returns a function. This is helpful to “wrap” functionality with the same code over and over again. For example, above code can be re-written as following.
We use @func_name to specify a decorator to be applied on another function.
We use @func_name to specify a decorator to be applied on another function.
# Adds a welcome message to the string
# returned by fun(). Takes fun() as
# parameter and returns welcome().
def decorate_message(fun):
# returned by fun(). Takes fun() as
# parameter and returns welcome().
def decorate_message(fun):
# Nested function def addWelcome(site_name):
return "Welcome to " + fun(site_name)
# Decorator returns a function
return addWelcome
return addWelcome
@decorate_message
def site(site_name):
def site(site_name):
return site_name;
# Driver code # This call is equivalent to call to # decorate_message() with function # site("GeeksforGeeks") as parameter print site("PythonWorld")
Output:
Welcome to PythonWorld
Iterators in Python
Iterator in python is any python type that can be used with a ‘for in loop’. Python lists, tuples, dicts and sets are all examples of inbuilt iterators. These types are iterators because they implement following methods. In fact, any object that wants to be an iterator must implement following methods.
1.__iter__ method that is called on initialization of an iterator. This should return an object that has a next or __next__ (in Python 3) method.
2.next ( __next__ in Python 3) The iterator next method should return the next value for the iterable. When an iterator is used with a ‘for in’ loop, the for loop implicitly calls next() on the iterator object. This method should raise a StopIteration to signal the end of the iteration.
2.next ( __next__ in Python 3) The iterator next method should return the next value for the iterable. When an iterator is used with a ‘for in’ loop, the for loop implicitly calls next() on the iterator object. This method should raise a StopIteration to signal the end of the iteration.
Below is a simple Python program that creates iterator type that iterates from 10 to given limit. For example, if limit is 15, then it prints 10 11 12 13 14 15. And if limit is 5, then it prints nothing.
# A simple Python program to demonstrate
# working of iterators using an example type
# that iterates from 10 to given value
# An iterable user defined type
class Test:
# working of iterators using an example type
# that iterates from 10 to given value
# An iterable user defined type
class Test:
# Cosntructor
def __init__(self, limit):
def __init__(self, limit):
self.limit = limit
# Called when iteration is initialized
def __iter__(self):
def __iter__(self):
self.x = 10
return self
# To move to next element. In Python 3,
# we should replace next with __next__
def next(self):
# we should replace next with __next__
def next(self):
# Store current value of x
x = self.x
# Stop iteration if limit is reached
if x > self.limit:
x = self.x
# Stop iteration if limit is reached
if x > self.limit:
raise StopIteration
# Else increment and return old value
self.x = x + 1;
return x
self.x = x + 1;
return x
# Prints numbers from 10 to 15
for i in Test(15):
for i in Test(15):
print(i)
# Prints nothing
for i in Test(5):
for i in Test(5):
print(i)
Output:
10
11
12
13
14
15
11
12
13
14
15
Accessing Counters in Python
Once initialized, counters are accessed just like dictionaries. Also, it does not raise the Key Value error (if key is not present) instead the value’s count is shown as 0.
Example:
# Python program to demonstrate accessing of
# Counter elements
from collections import Counter
# Create a list
z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
col_count = Counter(z)
print(col_count)
col = ['blue','red','yellow','green']
# Here green is not in col_count
# so count of green will be zero
for color in col:
print (color, col_count[color])
# Counter elements
from collections import Counter
# Create a list
z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
col_count = Counter(z)
print(col_count)
col = ['blue','red','yellow','green']
# Here green is not in col_count
# so count of green will be zero
for color in col:
print (color, col_count[color])
Output:
Counter({'blue': 3, 'red': 2, 'yellow': 1})
blue 3
red 2
yellow 1
green 0
blue 3
red 2
yellow 1
green 0
elements()
The elements() method returns an iterator that produces all of the items known to the Counter. Note : Elements with count <= 0 are not included.
Example:
# Python example to demonstrate elements() on
# Counter (gives back list)
from collections import Counter
coun = Counter(a=1, b=2, c=3)
print(coun)
print(list(coun.elements()))
# Counter (gives back list)
from collections import Counter
coun = Counter(a=1, b=2, c=3)
print(coun)
print(list(coun.elements()))
Output:
Counter({'c': 3, 'b': 2, 'a': 1})
['a', 'b', 'b', 'c', 'c', 'c']
['a', 'b', 'b', 'c', 'c', 'c']
most_common() :
most_common() is used to produce a sequence of the n most frequently encountered input values and their respective counts.
# Python example to demonstrate most_elements() on
# Counter
from collections import Counter
coun = Counter(a=1, b=2, c=3, d=120, e=1, f=219)
# This prints 3 most frequent characters
for letter, count in coun.most_common(3):
print('%s: %d' % (letter, count))
# Counter
from collections import Counter
coun = Counter(a=1, b=2, c=3, d=120, e=1, f=219)
# This prints 3 most frequent characters
for letter, count in coun.most_common(3):
print('%s: %d' % (letter, count))
Output:
f: 219
d: 120
c: 3
d: 120
c: 3
Counter in Python
What is counter?
Counter is a container included in the collections module.
What is container?
Containers are objects that hold objects. They provide a way to access the contained objects and iterate over them. Examples of built in containers are Tuple, list and dictionary. Others are included in Collections module.
A Counter is a subclass of dict. Therefore it is an unordered collection where elements and their respective count are stored as dictionary. This is equivalent to bag or multiset of other languages.
Syntax:
class collections.Counter([iterable-or-mapping])
initialization
The constructor of counter can be called in any one of the following ways :
1.With sequence of items
2.With dictionary containing keys and counts
3.With keyword arguments mapping string names to counts
Example of each type of initialization :
1.With sequence of items
2.With dictionary containing keys and counts
3.With keyword arguments mapping string names to counts
Example of each type of initialization :
# A Python program to show different ways to create
# Counter
from collections import Counter
# With sequence of items
print Counter(['B','B','A','B','C','A','B','B','A','C'])
# with dictionary
print Counter({'A':3, 'B':5, 'C':2})
# with keyword arguments
print Counter(A=3, B=5, C=2)
Output of all the three lines is same :
Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 3, 'C': 2})
Updation:
We can also create an empty counter in the following manner :
coun = collections.Counter()
And can be updated via update() method .Syntax for the same :
coun.update(Data)
# A Python program to demonstrate update()
from collections import Counter
coun = Counter()
coun.update([1, 2, 3, 1, 2, 1, 1, 2])
print(coun)
coun.update([1, 2, 4])
print(coun)
from collections import Counter
coun = Counter()
coun.update([1, 2, 3, 1, 2, 1, 1, 2])
print(coun)
coun.update([1, 2, 4])
print(coun)
Output:
Counter({1: 4, 2: 3, 3: 1})
Counter({1: 5, 2: 4, 3: 1, 4: 1})
Counter({1: 5, 2: 4, 3: 1, 4: 1})
Function use in Python
Function Calls
A callable object is an object that can accept some arguments (also called parameters) and possibly return an object (often a tuple containing multiple objects). A function is the simplest callable object in Python, but there are others, such as classes or certain class instances.
Defining Functions
A function is defined in Python by the following format:
def functionname(arg1, arg2, ...):
statement1
statement2
def functionname(arg1,arg2):
return arg1+arg2
t = functionname(24,24) # Result: 48
If a function takes no arguments, it must still include the parentheses, but without anything in them:
def functionname():
statement1
statement2
The arguments in the function definition bind the arguments passed at function invocation (i.e. when the function is called), which are called actual parameters, to the names given when the function is defined, which are called formal parameters. The interior of the function has no knowledge of the names given to the actual parameters; the names of the actual parameters may not even be accessible (they could be inside another function).
A function can 'return' a value, for example:
def square(x):
return x*x
A function can define variables within the function body, which are considered 'local' to the function. The locals together with the arguments comprise all the variables within the scope of the function. Any names within the function are unbound when the function returns or reaches the end of the function body. You can return multiple values as follows:
def first2items(list1):
return list1[0], list1[1]
a, b = first2items(["Hello", "world", "hi", "universe"])
print a + " " + b
print a + " " + b
Declaring Arguments
When calling a function that takes some values for further processing, we need to send some values as Function Arguments. For example:
def find_max(a,b):
if(a > b):
if(a > b):
print str(a) + " is greater than " + str(b)
elif(b > a):
print str(b) + " is greater than " + str(a)
find_max(30, 45) #Here (30, 45) are the arguments passing for finding max between this two numbers
The ouput will be: 45 is greater than 30
The ouput will be: 45 is greater than 30
Default Argument Values
If any of the formal parameters in the function definition are declared with the format "arg = value," then you will have the option of not specifying a value for those arguments when calling the function. If you do not specify a value, then that parameter will have the default value given when the function executes.
def display_message(message, truncate_after=4):
def display_message(message, truncate_after=4):
print message[:truncate_after]
display_message("message")
mess
display_message("message", 6)
message
mess
display_message("message", 6)
message
Variable-Length Argument Lists
Python allows you to declare two special arguments which allow you to create arbitrary-length argument lists. This means that each time you call the function, you can specify any number of arguments above a certain number.
def function(first,second,*remaining):
statement1
statement2
When calling the above function, you must provide value for each of the first two arguments. However, since the third parameter is marked with an asterisk, any actual parameters after the first two will be packed into a tuple and bound to "remaining."
def print_tail(first,*tail):
print tail
print_tail(1, 5, 2, "omega")
(5, 2, 'omega')
(5, 2, 'omega')
If we declare a formal parameter prefixed with two asterisks, then it will be bound to a dictionary containing any keyword arguments in the actual parameters which do not correspond to any formal parameters. For example, consider the function:
def make_dictionary(max_length=10, **entries):
return dict([(key, entries[key]) for i, key in enumerate(entries.keys()) if i < max_length])
If we call this function with any keyword arguments other than max_length, they will be placed in the dictionary "entries." If we include the keyword argument of max_length, it will be bound to the formal parameter max_length, as usual.
make_dictionary(max_length=2, key1=5, key2=7, key3=9)
{'key3': 9, 'key2': 7}
make_dictionary(max_length=2, key1=5, key2=7, key3=9)
{'key3': 9, 'key2': 7}
By Value and by Reference
Objects passed as arguments to functions are passed by reference; they are not being copied around. Thus, passing a large list as an argument does not involve copying all its members to a new location in memory. Note that even integers are objects. However, the distinction of by value and by reference present in some other programming languages often serves to distinguish whether the passed arguments can be actually changed by the called function and whether the calling function can see the changes.
Passed objects of mutable types such as lists and dictionaries can be changed by the called function and the changes are visible to the calling function. Passed objects of immutable types such as integers and strings cannot be changed by the called function; the calling function can be certain that the called function will not change them. For mutability, see also Data Types chapter.
Passed objects of mutable types such as lists and dictionaries can be changed by the called function and the changes are visible to the calling function. Passed objects of immutable types such as integers and strings cannot be changed by the called function; the calling function can be certain that the called function will not change them. For mutability, see also Data Types chapter.
def appendItem(ilist, item):
ilist.append(item) # Modifies ilist in a way visible to the caller
def replaceItems(ilist, newcontentlist):
del ilist[:] # Modification visible to the caller
ilist.extend(newcontentlist) # Modification visible to the caller ilist = [5, 6] # No outside effect; lets the local ilist point to a new list object, # losing the reference to the list object passed as an argument
ilist.extend(newcontentlist) # Modification visible to the caller ilist = [5, 6] # No outside effect; lets the local ilist point to a new list object, # losing the reference to the list object passed as an argument
def clearSet(iset):
iset.clear()
def tryToTouchAnInteger(iint):
iint += 1 # No outside effect; lets the local iint to point to a new int object,
# losing the reference to the int object passed as an argument
print "iint inside:",iint # 4 if iint was 3 on function entry
# losing the reference to the int object passed as an argument
print "iint inside:",iint # 4 if iint was 3 on function entry
list1 = [1, 2]
appendItem(list1, 3)
print list1 # [1, 2, 3]
replaceItems(list1, [3, 4])
print list1 # [3, 4]
set1 = set([1, 2])
clearSet(set1 )
print set1 # set([])
int1 = 3
tryToTouchAnInteger(int1)
print int1 # 3
appendItem(list1, 3)
print list1 # [1, 2, 3]
replaceItems(list1, [3, 4])
print list1 # [3, 4]
set1 = set([1, 2])
clearSet(set1 )
print set1 # set([])
int1 = 3
tryToTouchAnInteger(int1)
print int1 # 3
Calling Functions
A function can be called by appending the arguments in parentheses to the function name, or an empty matched set of parentheses if the function takes no arguments.
foo()
square(3)
bar(5, x)
A function's return value can be used by assigning it to a variable, like so:
x = foo()
y = bar(5,x)
As shown above, when calling a function you can specify the parameters by name and you can do so in any order
def display_message(message, start=0, end=4):
foo()
square(3)
bar(5, x)
A function's return value can be used by assigning it to a variable, like so:
x = foo()
y = bar(5,x)
As shown above, when calling a function you can specify the parameters by name and you can do so in any order
def display_message(message, start=0, end=4):
print message[start:end]
display_message("message", end=3)
This above is valid and start will have the default value of 0. A restriction placed on this is after the first named argument then all arguments after it must also be named. The following is not valid
display_message(end=5, start=1, "my message")
because the third argument ("my message") is an unnamed argument.
This above is valid and start will have the default value of 0. A restriction placed on this is after the first named argument then all arguments after it must also be named. The following is not valid
display_message(end=5, start=1, "my message")
because the third argument ("my message") is an unnamed argument.
Sunday 3 March 2019
Find the Hash of File in Python
# Python rogram to find the SHA-1 message digest of a file
# import hashlib module
import hashlib
def hash_file(filename):
# import hashlib module
import hashlib
def hash_file(filename):
""""This function returns the SHA-1 hash
of the file passed into it"""
# make a hash objectv h = hashlib.sha1()
# open file for reading in binary mode
with open(filename,'rb') as file:
of the file passed into it"""
# make a hash objectv h = hashlib.sha1()
# open file for reading in binary mode
with open(filename,'rb') as file:
# loop till the end of the file
chunk = 0
while chunk != b'':
chunk = 0
while chunk != b'':
# read only 1024 bytes at a time
chunk = file.read(1024)
h.update(chunk)
chunk = file.read(1024)
h.update(chunk)
# return the hex representation of digest return h.hexdigest()
message = hash_file("track1.mp3") print(message)
Output:
633d7356947eec543c50b76a1852f92427f4dca9
Find the size of Image in Python
def jpeg_res(filename):
""""This function prints the resolution of the jpeg image file passed into it"""
# open image for reading in binary mode
with open(filename,'rb') as img_file:
# open image for reading in binary mode
with open(filename,'rb') as img_file:
# height of image (in 2 bytes) is at 164th position
img_file.seek(163)
# read the 2 bytes
a = img_file.read(2)
# calculate height
height = (a[0] << 8) + a[1]
# next 2 bytes is width
a = img_file.read(2)
# calculate width
width = (a[0] << 8) + a[1]
img_file.seek(163)
# read the 2 bytes
a = img_file.read(2)
# calculate height
height = (a[0] << 8) + a[1]
# next 2 bytes is width
a = img_file.read(2)
# calculate width
width = (a[0] << 8) + a[1]
print("The resolution of the image is",width,"x",height)
jpeg_res("img1.jpg")
Output:
The resolution of the image is 280 x 280
Merge Mails in Python
# Python program to mail merger
# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open("names.txt",'r',encoding = 'utf-8') as names_file:
# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open("names.txt",'r',encoding = 'utf-8') as names_file:
# open body.txt for reading
with open("body.txt",'r',encoding = 'utf-8') as body_file:
with open("body.txt",'r',encoding = 'utf-8') as body_file:
# read entire content of the body
body = body_file.read()
# iterate over names
for name in names_file:
body = body_file.read()
# iterate over names
for name in names_file:
mail = "Hello "+name+body
# write the mails to individual files
with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file:
# write the mails to individual files
with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file:
mail_file.write(mail)
Count the Number of Vowel in Python
# Program to count the number of each vowel in a string
# string of vowels
vowels = 'aeiou'
# change this value for a different result
ip_str = 'Hello, have you tried our turorial section yet?'
# uncomment to take input from the user
#ip_str = input("Enter a string: ")
# make it suitable for caseless comparisions
ip_str = ip_str.casefold()
# make a dictionary with each vowel a key and value 0
count = {}.fromkeys(vowels,0)
# count the vowels
for char in ip_str:
# string of vowels
vowels = 'aeiou'
# change this value for a different result
ip_str = 'Hello, have you tried our turorial section yet?'
# uncomment to take input from the user
#ip_str = input("Enter a string: ")
# make it suitable for caseless comparisions
ip_str = ip_str.casefold()
# make a dictionary with each vowel a key and value 0
count = {}.fromkeys(vowels,0)
# count the vowels
for char in ip_str:
if char in count:
count[char] += 1
print(count)
Output:
{'o': 5, 'i': 3, 'a': 2, 'e': 5, 'u': 3}
Different Set Operations in Python
# Program to perform different set operations like in mathematics
# define three sets
E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};
# set union
print("Union of E and N is",E | N)
# set intersection
print("Intersection of E and N is",E & N)
# set difference
print("Difference of E and N is",E - N)
# set symmetric difference
print("Symmetric difference of E and N is",E ^ N)
# define three sets
E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};
# set union
print("Union of E and N is",E | N)
# set intersection
print("Intersection of E and N is",E & N)
# set difference
print("Difference of E and N is",E - N)
# set symmetric difference
print("Symmetric difference of E and N is",E ^ N)
Output:
Union of E and N is {0, 1, 2, 3, 4, 5, 6, 8}
Intersection of E and N is {2, 4}
Difference of E and N is {8, 0, 6}
Symmetric difference of E and N is {0, 1, 3, 5, 6, 8}
Intersection of E and N is {2, 4}
Difference of E and N is {8, 0, 6}
Symmetric difference of E and N is {0, 1, 3, 5, 6, 8}
Popular Posts
-
What you'll learn Distinguish between front-end, back-end, and full-stack developers. Create and style a webpage with HTML and CSS. Th...
-
What you'll learn Gain an immersive understanding of the practices and processes used by a junior or associate data analyst in their d...
-
Code: import pyfiglet from termcolor import colored import random def get_random_font_style(): # List of available Figlet font styles ...
-
Machine learning is one of the fastest growing areas of computer science, with far-reaching applications. The aim of this textbook is to i...
-
Code: class Tripler(int): def __mul__(self, other): return super().__mul__(other - 2) t = Tripler(6) result = t * 4 print(resu...
-
Code: x = [1, 2, 3, 4, 5] a, *_, b = x print(a, b) Solution and Explanation: Let's break down the Python code step by step: x = [1, 2,...
-
Code: num = [1, 2, 3] *middle, last = num print(middle, last) Solution and Explanation: Let's break down the code step by step: num = ...
-
Code: import gzip import shutil def compress_file(input_file, output_file): with open(input_file, 'rb') as f_in: with ...
-
import statsmodels.api as sm import numpy as np # Generate some sample data x = np.random.rand(100) y = 2 * x + np.random.randn(100) # Fit...
-
What you'll learn Conduct an inferential statistical analysis Discern whether a data visualization is good or bad Enhance a data analy...
Categories
AI
(27)
Android
(24)
AngularJS
(1)
Assembly Language
(2)
aws
(17)
Azure
(7)
BI
(10)
book
(4)
Books
(117)
C
(77)
C#
(12)
C++
(82)
Course
(62)
Coursera
(179)
coursewra
(1)
Cybersecurity
(22)
data management
(11)
Data Science
(95)
Data Strucures
(6)
Deep Learning
(9)
Django
(6)
Downloads
(3)
edx
(2)
Engineering
(14)
Excel
(13)
Factorial
(1)
Finance
(6)
flutter
(1)
FPL
(17)
Google
(19)
Hadoop
(3)
HTML&CSS
(46)
IBM
(25)
IoT
(1)
IS
(25)
Java
(92)
Leet Code
(4)
Machine Learning
(44)
Meta
(18)
MICHIGAN
(5)
microsoft
(3)
Pandas
(3)
PHP
(20)
Projects
(29)
Python
(752)
Python Coding Challenge
(224)
Questions
(2)
R
(70)
React
(6)
Scripting
(1)
security
(3)
Selenium Webdriver
(2)
Software
(17)
SQL
(40)
UX Research
(1)
web application
(8)