Beruflich Dokumente
Kultur Dokumente
C PYTHON
An object-oriented
programming model is basically
followed by Python.( Object-
An Imperative programming model oriented programming is a
is basically followed by C. programming paradigm based
(imperative programming is on the concept of "objects",
a programming paradigm that uses which can contain data, in the
statements that change form of fields, and code, in the
a program's state) form of procedures.)
Variables are declared in C. Python has no declaration.
Python has OOP which is a
C doesn’t have native OOP. part of language.
Pointers are available in C No pointers functionality is
language. available in Python.
Python is an interpreted
C is a compiled language. language.
There is a limited number of built-in There is a large library of built-
functions available in C. in functions in Python.
Implementation of data structures It is easy to implement data
requires its functions to be explicitly structures in Python with built-in
implemented. insert, append functions.
Python is firstly compiled to a
C is compiled direct to machine byte-code and then it is
code which is executed directly by interpreted by a large C
the CPU program.
Declaring of variable type in C is There is no need to declare a
necessary condition. type of variable in Python.
C does not have complex data Python has some complex data
structures. structures.
C is statically typed. Python is dynamically typed.
Syntax of C is harder than python
because of which programmers It is easy to learn, write and
prefer to use python instead of C read Python programs than C.
C programs are saved with .c Python programs are saved
extension. by .py extension.
Assignment gives an error in
line. For example, a=5 gives an
An assignment is allowed in a line. error in python.
In C language testing and In Python, testing and
debugging is harder. debugging is not harder than C.
C is complex than Python. Python is much easier than C.
The basic if statement in c is
represented as: The basic if statement in
if () Python is represented as:
if:
The basic if-else statement in The basic if-else statement is
Python is represented as: represented as:
if ( ) if :
else else:
Compiled Languages
Compiled languages are converted directly into machine code that
the processor can execute.
As a result, they tend to be faster and more efficient to execute than
interpreted languages.
They also give the developer more control over hardware aspects,
like memory management and CPU usage.
Compiled languages need a “build” step - they need to be manually
compiled first.
You need to “rebuild” the program every time you need to make a
change.
In our hummus example, the entire translation is written before it
gets to you. If the original author decided he wanted to use a
different kind of olive oil, the entire recipe would need to be
translated again and then sent to you.
Examples of pure compiled languages are C, C++, Erlang, Haskell,
Rust, and Go.
Interpreted Languages
Interpreters will run through a program line by line and execute each
command.
Now, if the author decided he wanted to use a different kind of olive
oil, he could scratch the old one out and add the new one.
Your translator friend can then convey that change to you as it
happens.
Interpreted languages were once known to be significantly slower
than compiled languages. But, with the development of just-in-time
compilation, that gap is shrinking.
Examples of common interpreted languages are PHP, Ruby, Python,
and JavaScript.
Advantages and Disadvantages
Advantages of Compiled Languages
Programs compiled into native code at compile time usually tend to be
faster than those translated at run time, due to the overhead of the
translation process.
Disadvantages of Compiled Languages
The most notable disadvantages are :-
Additional time needed to complete the entire compilation step
before testing, and
Platform dependence of the generated binary code.
Advantages of Interpreted Languages
An Interpreted language gives implementations some additional flexibility
over compiled implementations. Because interpreters execute the source
program code themselves, the code itself is platform independent (Java’s
byte code, for example). Other features include dynamic typing, and
smaller executable program size.
Disadvantages of Interpreted Languages
The most notable disadvantage is typical execution speed compared to
compiled languages.
Ex 1:Python program to add two numbers:
a=10
b=10
c=a+b
print(c)
ex2: Adding two number provided by user input
number1 = input("First number: ")
number2 = input("\nSecond number: ")
What is Computation?
Computation is by the notation of algorithm series of steps that can be
systematically followed for producing the answer to a certain type of
problem.
Python is a general-purpose interpreted, interactive, object-oriented,
and high-level programming language. It was created by Guido van
Rossum during 1985- 1990. Like Perl, Python source code is also
available under the GNU General Public License (GPL).
This tutorial gives enough understanding on Python
programming language.
Why to Learn Python?
Python is a high-level, interpreted, interactive and object-oriented
scripting language. Python is designed to be highly readable. It uses
English keywords frequently where as other languages use punctuation,
and it has fewer syntactical constructions than other languages.
Python is a MUST for students and working professionals to become a
great Software Engineer specially when they are working in Web
Development Domain. I will list down some of the key advantages of
learning Python:
Python is Interpreted − Python is processed at runtime by the
interpreter. You do not need to compile your program before
executing it. This is similar to PERL and PHP.
Python is Interactive − You can actually sit at a Python prompt and
interact with the interpreter directly to write your programs.
Python is Object-Oriented − Python supports Object-Oriented style
or technique of programming that encapsulates code within objects.
Python is a Beginner's Language − Python is a great language for
the beginner-level programmers and supports the development of a
wide range of applications from simple text processing to WWW
browsers to games.
Characteristics of Python
Following are important characteristics of Python Programming −
It supports functional and structured programming methods as well
as OOP.
It can be used as a scripting language or can be compiled to byte-
code for building large applications.
It provides very high-level dynamic data types and supports dynamic
type checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and
Java.
Hello World using Python.
Just to give you a little excitement about Python, I'm going to give you a
small conventional Python Hello World program, You can try it using
Demo link.
Live Demo
print("Hello, Python!");
Applications of Python
As mentioned before, Python is one of the most widely used language
over the web. I'm going to list few of them here:
Easy-to-learn − Python has few keywords, simple structure, and a
clearly defined syntax. This allows the student to pick up the
language quickly.
Easy-to-read − Python code is more clearly defined and visible to
the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very
portable and cross-platform compatible on UNIX, Windows, and
Macintosh.
Interactive Mode − Python has support for an interactive mode
which allows interactive testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms
and has the same interface on all platforms.
Extendable − You can add low-level modules to the Python
interpreter. These modules enable programmers to add to or
customize their tools to be more efficient.
Databases − Python provides interfaces to all major commercial
databases.
GUI Programming − Python supports GUI applications that can be
created and ported to many system calls, libraries and windows
systems, such as Windows MFC, Macintosh, and the X Window
system of Unix.
Scalable − Python provides a better structure and support for large
programs than shell scripting.
Apart from the above-mentioned features, Python has a big list of good
features, few are listed below −
It supports functional and structured programming methods as well
as OOP.
It can be used as a scripting language or can be compiled to byte-
code for building large applications.
It provides very high-level dynamic data types and supports dynamic
type checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and
Java.
Python is available on a wide variety of platforms including Linux and
Mac OS X. Let's understand how to set up our Python environment.
What is an algorithm?
An algorithm (pronounced AL-go-rith-um) is a procedure or formula for
solving a problem, based on conducting a sequence of specified
actions.
Computer Hardware:
o It includes the all-important components of the central processing
unit(CPU) and main memory.
o It also includes peripheral components such as
keyboard,monitor,mouse, and printer.
print"Hello, Python!"
We assume that you have Python interpreter available in /usr/bin
directory. Now, try to run this program as follows −
$ chmod+x test.py # This is to make file
executable
$./test.py
This produces the following result −
Hello, Python!
Python Identifiers
A Python identifier is a name used to identify a variable, function, class,
module or other object. An identifier starts with a letter A to Z or a to z or
an underscore (_) followed by zero or more letters, underscores and
digits (0 to 9).
Python does not allow punctuation characters such as @, $, and %
within identifiers. Python is a case sensitive programming language.
Thus, Manpower and manpower are two different identifiers in Python.
Here are naming conventions for Python identifiers −
Class names start with an uppercase letter. All other identifiers start
with a lowercase letter.
Starting an identifier with a single leading underscore indicates that
the identifier is private.
Starting an identifier with two leading underscores indicates a
strongly private identifier.
If the identifier also ends with two trailing underscores, the identifier
is a language-defined special name.
Reserved Words
The following list shows the Python keywords. These are reserved
words and you cannot use them as constant or variable or any other
identifier names. All the Python keywords contain lowercase letters only.
And exec not
Assert finally or
Def if return
Elif in while
Else is with
# First comment
print"Hello, Python!"# second comment
This produces the following result −
Hello, Python!
You can type a comment on the same line after a statement or
expression −
name = "Madisetti" # This is again comment
You can comment multiple lines as follows −
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
Following triple-quoted string is also ignored by Python interpreter and
can be used as a multiline comments:
'''
This is a multiline
comment.
'''
Using Blank Lines
A line containing only whitespace, possibly with a comment, is known as
a blank line and Python totally ignores it.
In an interactive interpreter session, you must enter an empty physical
line to terminate a multiline statement.
Python - Variable Types
Variables are nothing but reserved memory locations to store
values.
This means that when you create a variable you reserve some
space in memory.
Based on the data type of a variable,
The interpreter allocates memory and decides what can be stored in
the reserved memory. Therefore, by assigning different data types
to variables, you can store integers, decimals or characters in these
variables.
Assigning Values to Variables
Python variables do not need explicit declaration to reserve memory
space. The declaration happens automatically when you assign a value
to a variable. The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and
the operand to the right of the = operator is the value stored in the
variable. For example −
#!/usr/bin/python
print counter
print miles
print name
Here, 100, 1000.0 and "John" are the values assigned to counter, miles,
and name variables, respectively. This produces the following result −
100
1000.0
John
Multiple Assignment
Python allows you to assign a single value to several variables
simultaneously. For example −
a = b = c = 1
Here, an integer object is created with the value 1, and all three
variables are assigned to the same memory location. You can also
assign multiple objects to multiple variables. For example −
a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a
and b respectively, and one string object with the value "john" is
assigned to the variable c.
Standard Data Types
The data stored in memory can be of many types. For example, a
person's age is stored as a numeric value and his or her address is
stored as alphanumeric characters. Python has various standard data
types that are used to define the operations possible on them and the
storage method for each of them.
Python has five standard data types −
Numbers
String
List
Tuple
Dictionary
Python Numbers
Number data types store numeric values. Number objects are created
when you assign a value to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del
statement. The syntax of the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del
statement. For example −
Delvar
delvar_a, var_b
Python supports four different numerical types −
int (signed integers)
long (long integers, they can also be represented in octal and
hexadecimal)
float (floating point real values)
complex (complex numbers)
Examples
Here are some examples of numbers −
Int long float comple
x
- -052318172735L - 3e+26J
0x26 32.54e10
0 0
#!/usr/bin/python
str='Hello World!'
list=['abcd',786,2.23,'john',70.2]
tinylist=[123,'john']
#!/usr/bin/python
tuple=('abcd',786,2.23,'john',70.2)
tinytuple=(123,'john')
tuple=('abcd',786,2.23,'john',70.2)
list=['abcd',786,2.23,'john',70.2]
tuple[2]=1000# Invalid syntax with tuple
list[2]=1000# Valid syntax with list
Python Dictionary
Python's dictionaries are kind of hash table type.
They work like associative arrays or hashes found in Perl and consist of
key-value pairs.
A dictionary key can be almost any Python type, but are usually
numbers or strings. Values, on the other hand, can be any arbitrary
Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be
assigned and accessed using square braces ([]).
For example −
dict={}
dict['one']="This is one"
dict[2]="This is two"
tinydict={'name':'john','code':6734,'dept':'sales'}
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
Example
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
Indentation
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Short Hand If
Example
One line if statement:
if a > b: print("a is greater than b")
And
Example
Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Nested If
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
The pass Statement
Example
a = 33
b = 200
if b > a:
pass
Python While Loops
Python Loops
Example
Print i as long as i is less than 6:
i = 1
while i< 6:
print(i)
i += 1
Example
Exit the loop when i is 3:
i = 1
while i< 6:
print(i)
if i == 3:
break
i += 1
The continue Statement
Example
Continue to the next iteration if i is 3:
i = 0
while i< 6:
i += 1
if i == 3:
continue
print(i)
The else Statement
Example
Print a message once the condition is false:
i = 1
while i< 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Python For Loops
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
The break Statement
Example
Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
Example
Exit the loop when x is "banana", but this time the break comes
before the print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
The continue Statement
Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
The continue Statement
Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.
Example
Using the range() function:
for x in range(6):
print(x)
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
Python Functions
A function is a block of code which only runs when it is called.
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Parameters
Information can be passed to functions as parameter.
Parameters are specified after the function name, inside the parentheses. You can add as many parameters as
you want, just separate them with a comma.
The following example has a function with one parameter (fname). When the function is called, we pass along
a first name, which is used inside the function to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
E.g. if you send a List as a parameter, it will still be a List when it reaches the function:
Example
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Return Values
To let a function return a value, use the return statement:
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Arbitrary Arguments
If you do not know how many arguments that will be passed into your function, add a * before the parameter
name in the function definition.
This way the function will receive a tuple of arguments, and can access the items accordingly:
Example
If the number of arguments are unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
Recursion
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls itself. This has
the benefit of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a function which
never terminates, or one that uses excess amounts of memory or processor power. However, when written
correctly recursion can be a very efficient and mathematically-elegant approach to programming.
In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use
the k variable as the data, which decrements (-1) every time we recurse. The recursion ends when the
condition is not greater than 0 (i.e. when it is 0).
To a new developer it can take some time to work out how exactly this works, best way to find out is by
testing and modifying it.
Example
Recursion Example
deftri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result
Python Lambda
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
Syntax
lambda arguments : expression
Example
A lambda function that adds 10 to the number passed in as an argument, and print the result:
x = lambda a : a + 10
print(x(5))
Example
A lambda function that multiplies argument a with argument b and print the result:
x = lambda a, b : a * b
print(x(5, 6))
Example
A lambda function that sums argument a, b, and c and print the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))