zueducator

Online education for all on health, science, technology, business and management...

ad3

Sunday, July 3, 2022

20 Python Programs for Beginners

 20 Python Programs for Beginners

Introduction

In this article, you will be able to know and learn about some basic concepts and features of the python language. Python is an object-oriented, high-level programming language and has efficient high-level data structures. It uses simple English keywords frequently and is easy to learn. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting, interactive, and rapid application development in many areas on most platforms. This article will prove to be excellent and suitable for beginners who have little knowledge of Python and other programming languages. So, let us start with Python with its origin.


A brief history of Python

·       Python was developed and created by Guido van Rossum at the National Research Institute for Mathematics and computer science in the Netherlands.

·       Python 1.0 was released in Nov 1994. In 2000, Python 2.0 was released. Python 3.0 was released in 2008.

·       Python 3.5.1 and 3.7.0 are considered the latest version of Python 3.

·       Python is included with most distributions of Linux.

Definition

Python

·       Python refers to a high-level, interpreted, interactive, and object-oriented scripting language.

·       Python uses simple English keywords frequently and focuses less on punctuations.

·       Python is interpreted. Python is processed at runtime by the interpreter. You do not need to compile your program before executing it.

·       Python is interactive. A user can interact with the interpreter directly to write the programs using the Python prompt.

·       Python is an incredibly powerful object-oriented language. The language can be extended by adding new modules, even if they have been compiled in C and C++.

Benefits of learning Python

·       Python is straightforward to learn.

·       Python is easy to read. There is no need to be a skilled programmer.

·       Python makes use of an elegant syntax.

·       Python can be used to develop prototypes because it is easy to work with and read.

·       Most automation, data mining, and big data platforms rely on Python. This is because it is the ideal language to work with for general-purpose tasks.

·       Python powers Django, a complete and open source web application framework. Frameworks –like Ruby on Rails- can be used to simplify the development process.

·       Python is widely used by a number of big companies like Google, Pinterest, Instagram, Disney, Yahoo, Nokia, and IBM.

Main features of Python

·       Python has built-in-high level data types: strings, lists, dictionaries, etc.

·       Python has the usual control structures: if, if-else, if-else if, while, for, etc.

·       Multiple levels of organizational structure: functions, classes, modules, and packages. For instance, Python standard library.

·       In Python, source code is compiled to byte code without a separate compile step.

·       Python provides a consistent way to use objects.

·       Python is good for both small and large tasks.

·       Python uses indentation to show block structure.

·       Python is a scripting language suitable for embedding and writing small unstructured scripts.

·       Python comes with the standard Python library, offering integrated support for a variety of common programming tasks like syncing with web servers, searching through text, and modifying files.

·       Python can be embedded into an application, which will provide a programmable interface for users of that app.

·       Python can be extended by adding new modules, even if they have been compiled in C or C++. Extension modules and extension types can be written by hand. There are also tools that help with this. For instance, SWIG, Sip and Pyrex.

·       Cython enables us to generate C code from Python and do “easily” create wrappers for C/C++ functions.

·       Jython is a version of Python that “plays” well with JAVA.

·       Python is compatible with OS‘s like Windows, Linux, Mac OS, and many brands of Unix, OS/2. Also, Python uses a similar interface on each one of those platforms, which means you can jump between them easily if necessary.

·       Python is used for software development at companies and organizations such as Google, Yahoo, CERN Industrial Light, Magic, and NASA.

Minimum hardware requirement for the installation of Python3.7.0

·       Python comes pre-installed on Mac OS.

·       Python is included with most distributions of Linux.

·       Python requires windows 7 or windows 10 with SP1.

·       Python’s recent version can be downloaded from the www.python.org

Where to write Python programs and run the program?

·       Notepad can be used as a text editor.

·       Save the file as filename.py

·       DOS can be used to run the program.

·       Run the saved file on DOS as filename.py

                               OR

Python IDLE shell installed on your computer can be used as an editor.

Some essential terminologies frequently used in Python are as under:

IDE (Integrated Development Environment)

·       An IDE includes an editor, debuggers, interpreter and other programming aids in one comprehensive program.

·       Some commercial IDE include Microsoft Visual Studio 2010, the Eclipse Foundation’s Eclipse IDE, Apple’s Xcode, and IDLE is a very simple IDE for Python.

IDLE

IDLE is a very simple Python IDE available for Windows, Linux, and Mac OS.

Interpreter

An interpreter translates the source code into the target machine language.

Compiler

A compiler translates the source code to the target code.

Debuggers

A debugger allows the programmer to simultaneously run a program and see which source code line is currently being executed. Debuggers are valuable for locating errors (also called bugs) and repairing programs that contain errors.

Profilers

A profiler is used to evaluate a program’s performance. A profiler indicates how many times a portion of a program is executed during a particular run and how long that portion takes to execute.

Dynamic

·       Types are bound to values, not to variables.

·       Python values are inspectable.

·       Strongly typed at runtime, not compile-time objects (values) have a type, but variables do not.

·       Function and method look-up is done at run time.

·       There is an interactive interpreter.

Editor

An editor allows the programmer to enter the program source code and save it to files.

Source code

Source code refers to any higher-level language code.

Target code

Target code refers to the interpreted machine language code.

Statement

A statement is a command that the interpreter executes.

Datatypes

·       Datatypes are the classification or categorization of data items.

·       Datatypes represent a kind of value that determines what operations can be performed on that data.

Some Python built-in datatypes used in this book are:

·       Text type                  str

·       Numeric types             int, float, complex

·       Sequence types          list, tuple, range

·       Set types                  set

·       Datatypes in Python also include classes and variables.

·       Every value in Python has a datatype.

Python numbers

·       Integers, floating-point numbers, and complex numbers fall under Python numbers.

·       Python numbers are defined as int, float, and complex numbers.

Python strings

Python strings refer to a sequence of Unicode characters. We can use single quotes or double quotes to represent strings. Multiline strings can be denoted using triple quotes, ‘  ’ ’ or “  ”  ”.

Python string literals

·       String literals in Python are surrounded by either single quotation marks or double quotation marks. For example, print(“welcome”) or  print(‘welcome’).

·       Strings in Python are arrays of bytes representing Unicode characters.

·       A single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.

Python list

·       Python list refers to an ordered sequence of items.

·       Python list is one of the most used data type in Python and is very flexible.

·       All the items in a Python list do not need to be of the same type.

Declaring Python list

·       Items separated by commas are enclosed within brackets [ ]. For example, a=[1, 2.2, ‘Python’]. We can use the slicing operator [ ] to extract an item or a range of items from a list.

·       Index starts from 0 in Python.    

·       Python lists are mutable, meaning, the value of elements of a list can be altered.

Python tuple

·       Python tuple refers to an ordered sequence of items whose elements are immutable. Python tuples once created cannot be modified.

·       Python tuples are used to write-protect data and are usually faster than lists as they cannot change dynamically.

·       Python tuples are defined within parenthesis () where items are separated by commas.

Python set

·       Python set refers to an unordered collection of unique items.

·       Python set is defined by values separated by a comma inside braces { }. Items in a set are not ordered.

·       Python set has unique values.

·       A Python set eliminates duplicates.

·       In the case of Python set, indexing has no meaning.

Iteration

Iteration repeats the execution of a sequence of code.

Python loop

Python supports only two primitive loops while loop and for a loop.

While loop

Using a while loop, we can execute a set of statements as long as a condition is true.

For loop

·       A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

·       With the for loop, we can execute a set of statements, once for each item in a list, tuple, set, etc.

Basic syntax is

for <variable-name> in <array-name>:

print(<variable-name>)

Python array

Python array refers to a special variable, which can hold more than one value at a time of the same datatype. For example,  fruit =[“Apple”,” Banana”,” Orange”]

Python class

·       A class can define specific sets of characteristics that are shared by all objects of that class.

·       Classes describe objects.

·       In Python, all classes have a function called –init-(), which is always executed when the class is being initiated.

·       We use the –init-() function to assign values to object properties or other operations that are necessary to do when the object is being created.

Syntax to declare a class in Python

class <class-name>:

pass

variable-name=value

           or

class MyFirstclass:

pass

·       A programmer should use four spaces for indentation.

·       Python constructs, indentation is used to delimit the classes, rather than braces or brackets.

·       The class definition starts with the “class” keyword. This is followed by a name (user-defined or of your choice) identifying the class and is terminated with a colon.  

·       The “pass” keyword is used on the second line to indicate that no further action needs to be taken.       

Python object

·       An object is a collection of data with associated behaviors.

·       Objects are instances of classes that can be associated with each other.

·       An object instance is a specific object with its own set of data and behaviors.

·       Almost everything in Python is an object, with its properties and methods.

Syntax to declare an object

Object-name=class-name()

print(object-name.variable-name)

Python function

·       Python function is a group of related statements that perform a specific task.

·       Python functions help to break our program into smaller and modular chunks.

·       A Python function avoids repetition and makes code reusable.

·       The simplest function accepts no parameters and returns no value to the caller. The def keyword introduces a function definition.

Syntax to declare a function is:

def function-name(parameters):

“”” doctring”””

Statement(s)

 

Syntax to call a function in Python

function-name (‘value’)

To call a function we simply type the function name with appropriate parameters.

Python method

·       Python methods refer to the behaviors that can be performed on a specific class of objects.

·       A method in Python is formatted identically to a function. It starts with the keyword “def” followed by a space and the name of the method. This is followed by a set of parenthesis containing the parameter list and terminated with a colon.

·       Python methods can also accept parameters and return values.

·       All methods have one required argument. This argument is conventionally named “self”. The “self” argument to a method is simply a reference to the object that the method is being invoked on.

Parameters

Parameters to a method are a list of objects that need to be passed into the method that is being called (the objects that are passed in from the calling object are usually referred to as arguments).

Module

A module is a collection of Python code that can be used in other programs.

from math import sqrt

from math import sqrt makes the sqrt function available for use in the program. The math module has many other mathematical functions. These include trigonometric, logarithmic, hyperbolic, and other mathematical functions.

from math import *

The * symbol represents “everything”. This statement makes all the code in the math module available to the program. If a program needs to use many different functions from the math module, some programmers use this approach.

Python functions

·       Python functions include print(), input(), eval(), int(),float(), range() and type().

sqrt ( )

·       Python has a function in its standard library named sqrt(). The square root function accepts one numeric (integer or floating-point) value and produces a floating-point result.

·       The sqrt() function is part of a separate module.

print ( )

·       The print ( ) function prints the specified message (string or any other object) to the screen or other standard output device.

·       The print() function displays text in the console window. It does not compute and return a value to the client.

·       Empty print () function prints an empty line. It will leave a blank line in the output.

Python casting

·       Python casting is done to specify a type on to a variable.

·       Casting in Python is done using the constructor function.

int() constructor function

int() constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number) literal.

float() constructor function

float() constructs a float number from an integer literal, a float literal.

 str()constructor function

str() constructs a string from a wide variety of data types, including strings, integer literals, and float literals.

type() function

·       type() function is used to get the datatype of any object.

·       type() function is used to know which class a variable or a value belongs to.

instance()

instance() function is used to check if an object belongs to a particular class.

The range ( ) function

·       The range ( ) function is used to loop through a set of code a specified number of times.

·       The range ( ) function defaults to 0 as a starting value.

·       The range ( ) function defaults to increment the sequence by 1. However, it is possible to specify the increment value by adding a third parameter range (2, 30, 3).

·       It is possible to specify the starting value by adding parameter range (2, 6) which means values from 2 to 6 but not including 6.

len() method

The len() method is used to return the length of an array( the number of elements in an array). For example, p=len(array-name)

append( ) method

append( ) method is used to add an element to an array. Basic syntax is array-name. append(“<element-names>”)

pop() method

pop()method is used to remove an element from an array. Basic syntax is array-name.pop(index). For example, fruit.pop(1). This deletes the second element of the fruit array.

 remove() method

·       remove()method is used to remove an element from an array. Basic syntax is array-name.remove(“<element-name>”). For example, fruit.remove(“apple”)

·       The remove() method only removes the first occurrence of the specified value.

insert () method

insert()method is used to add an element at the specified position. Basic syntax is inert(<position index>, <”element-name”> ). For example, insert (2,”apple”).

reverse() method

reverse() method is used to reverse the order of the list.

sort() method

sort()method is used to sort the list.


Simple Python programs

Programs based on Python string

1.  Program to display a character constant.

Print(‘a’)           #output statement

Output:

a


2. Program to display a string constant.

print(“Apple”)      #output statement

Output:

Apple


3. Program to display more than one string in a single line without using variable.

Print(“Apple”,”Orange”,”Papaya”)

Output:

Apple   orange   papaya


4. Program to display different types of string using variables.

A=’A’          #Initialization statement

print(a)              #output statement

b=”Apple”

print(b)

c=”Welcome to python”

print(c)            #output statement

Output:

A

Apple

Welcome to Python


5. Program to display different data belonging to different datatypes.

print("welcome to python")

print("This is 2018")

print(5+10)

a=5          #Initialization statement

b=10

print("Sum=",a+b)

c=10.55         #Initialization statement

e=3.5          

d=int(c)         #type casting

print("d=",d)

print(c+e)        #output statement

Output:

Welcome to python

This is 2018

15

Sum=15

d=10

14.05


6. Program to display more than one string using variables.

S1=”apple”        #Initialization statement

s2= “orange”

print(s1, s2)

print(“Strings are:”, s1, “,”,s2)

Output:

apple   orange

Strings are: apple, orange


7. Program to display strings using curly braces{}.

print("I love {0} and {1}".format('ab','bc'))

print("I love {1} and {0}".format('ab','bc'))

Output:

I love ab and  bc      

I love bc  and  ab


8. Program to display a string using input() built -in-function.

a=input("Enter your name:")

print("Name:",a)

Output:

Enter your name: Apple

Apple


9. Program to input any name and display it.

a=input("Enter first name:")

b=input("Enter last name:")

print("Name:",a,b)

Output:

Enter first name: Tom

Enter last name: Paddy

Name: Tom paddy


10. Program to display a string using function with argument.

def f1(a):     #function declaration

 print (a)

f1(a="Apple")       #calling function

Output:

Apple


Programs based on Python numbers

1.  Program to display an integer, a floating number and a double number.

print(5)

print(10.55)    #output statement

print(166.775)

Output:

5

10.55

166.775


2. Program to display an integer and a floating number using variables.

a=5            #Initialization statement

print(a)

b=10.55       #Initialization statement

print(b)                    #output statement

Output:

5

10.55


3. Program to find sum of numbers using variables.

a=5          #Initialization statement

b=10

print(a+b)       #output statement

Output:

15


4. Program to find sum and average of 3 numbers without using variables.

print(5+10+15)

print((5+10+15)/3)       #output statement

Output:

30

10.0


5. Program to find sum and average of 3 numbers using variables and assignment operation.

a=5

b=10           #Initialization statement

c=15   

s=a+b+c          #assignment statement

avg= float(s/3)

print("Sum=", s)

print("Average=",avg)   #output statement

Output:

Sum=30

Average=10.0


6. Program to perform arithmetic operation using variables.

a=10           #Initialization statement

b=3

print("Sum=",a+b)

print("Difference=",a-b)

print("Product=",a*b)

print("Quotient=",a/b)

print("Remainder=",a%b)

Output:

Sum=13

Difference=7

Product=30

Quotient=3.33333

Remainder=1


7. Program to display a number using multiple assignment.

a=b=c=20         #multiple assignment

print(a,"-",b,"-",c)

print(a)

print(b)             #output statement

print(c)

Output:

20 -20-20

20

20

20


8. Program to display numbers using assigning multiple values to multiple variables.

a,b,c=10,20,30

print(a,b,c)            #output statement

Output:

10   20   30


9. Program to find simple interest and amount using assignment operation.

p=1000

r=6             #Initialization statement

t=2

si=float(p*r*t/100)

amt=float(si+p)

print("Si=",si)       #output statement

print("Amount=",amt)

Output:

Si=120.0

Amount=1120.0


10. Program to swap two numbers using assigning values to variables.

a,b=10,20       #multiple initialization

a,b=b,a         #swapping

print(a,b)

Output:

20 10


 


No comments:

Post a Comment