Saturday, 9 March 2019

Working with Lists in Python



Working with Lists in Python – A Complete Beginner’s Guide

If you learn only one data structure in Python, make it a list.

Why? Because almost everything you build in Python—apps, scripts, automation, data analysis—relies on lists.

Lists are:

  • Easy to use

  • Extremely powerful

  • Used everywhere

Let’s master them step by step 👇


What is a List in Python?

A list is a collection of items stored in a single variable.

numbers = [1, 2, 3, 4, 5]

A list can store:

  • Integers

  • Strings

  • Floats

  • Even other lists

data = [10, "Python", 3.14, True]

Accessing List Elements

Each element has an index (starting from 0).

langs = ["Python", "Java", "C++"]
print(langs[0]) # Python
print(langs[2]) # C++

Negative Indexing

print(langs[-1]) # C++

Modifying List Values

Lists are mutable (you can change them).

langs[1] = "JavaScript"
print(langs)

Output:

['Python', 'JavaScript', 'C++']

Common List Operations

1. Adding Elements

lst = [1, 2]
lst.append(3)
lst.insert(0, 99)

2. Removing Elements

lst.remove(99)
lst.pop()
del lst[0]

3. Length of List

len(lst)

Looping Through a List

Basic Loop

for item in lst:
print(item)

With Index

for i in range(len(lst)):
print(i, lst[i])

Slicing Lists

Extract parts of a list:

nums = [10, 20, 30, 40, 50]
print(nums[1:4])

Output:

[20, 30, 40]

Useful List Methods

MethodPurpose
append()Add at end
insert()Add at index
remove()Remove value
pop()Remove last
sort()Sort list
reverse()Reverse
count()Count value
index()Find position

Example:

nums.sort()
nums.reverse()

List Comprehension (Power Feature)

One line instead of loops:

squares = [x*x for x in range(5)]
print(squares)

Output:

[0, 1, 4, 9, 16]

Nested Lists (2D Lists)

matrix = [
[1, 2],
[3, 4]
]

print(matrix[1][0]) # 3

Used in:

  • Tables

  • Matrices

  • Game boards


Common Beginner Mistake

This does NOT modify the list:

arr = [1, 2, 3]
for i in arr:
i = i * 10
print(arr)

Output:

[1, 2, 3]

Correct way:

for i in range(len(arr)):
arr[i] *= 10

Why Lists Are So Important

Lists are used in:

  • Web scraping

  • Data science

  • Machine learning

  • Automation

  • Game development

  • APIs & JSON

If you know lists well, you already know 40% of Python.


Final Thoughts

Mastering lists means:

  • Cleaner code

  • Faster logic

  • Better problem-solving

Before learning:

  • NumPy

  • Pandas

  • Machine Learning

👉 First, become deadly with Python lists.

Because every advanced concept is built on top of them. 🚀

Android Application Development For Dummies

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.

  • 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

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

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 




Sams Teach Yourself Database Programming with Visual C++ 6 in 21 Days

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)


C++ Programming in easy steps, 5th Edition by Mike McGrath

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




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):
text = text
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):
text = text
def innerFunction():
print(text)
return innerFunction # Note we are returning function WITHOUT parenthesis
if __name__ == '__main__':
myFunction = outerFunction('Hey!')
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

# Python program to illustrate
# 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
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)

Output:
6
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))

Output:
The integral value of 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))

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

Tuesday, 5 March 2019

Beginning PHP 5 and MySQL 5: From Novice to Professional (Beginning Series: Open Source) by W. Gilmore (Author)

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.


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:

# 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():
yield 1
yield 2
yield 3

# Driver code to check above generator function
for value in simpleGeneratorFun():
print(value)

Output:
1
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():
i = 1;
# An Infinite loop to generate squares
while True:
yield i*i
i += 1 # Next execution resumes
# from this point
# Driver code to test above generator
# function
for num in nextSquare():
if num > 100:
break
print(num)

Output:
1
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.

# Correct way of writing empty function
# in Python
def fun():
pass

We can use pass in empty while statement also.
# 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) :
pass
else :
print("False")

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (219) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (28) Azure (9) BI (10) Books (262) Bootcamp (1) C (78) C# (12) C++ (83) Course (86) Coursera (300) Cybersecurity (29) data (4) Data Analysis (27) Data Analytics (20) data management (15) Data Science (322) Data Strucures (16) Deep Learning (133) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (19) Finance (10) flask (3) flutter (1) FPL (17) Generative AI (66) Git (10) Google (50) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (262) Meta (24) MICHIGAN (5) microsoft (11) Nvidia (8) Pandas (13) PHP (20) Projects (32) Python (1264) Python Coding Challenge (1074) Python Mistakes (50) Python Quiz (441) Python Tips (5) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (46) Udemy (17) UX Research (1) web application (11) Web development (8) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)