Sie sind auf Seite 1von 68

Difference between C and Python

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:

Python programming language


C language is fast. is slow

Below are some facts about Python.


1. Python is a widely used general-purpose, high-level programming
language.
2. Python allows programming in Object-Oriented and Procedural
paradigms.
3. Python programs generally are smaller than other programming
languages like Java. Programmers have to type relatively less and
indentation requirement of the language, makes them readable all the
time.
4. Python language is being used by almost all tech-giant companies
like – Google, Amazon, Facebook, Instagram, Dropbox, Uber… etc.
5. The biggest strength of the Python is large library which can be used
for the following
 Machine Learning
 GUI Applications (like Kivy, Tkinter, PyQt etc. )
 Web frameworks like Django (used by YouTube, Instagram,
Dropbox)
 Image processing (like OpenCV, Pillow)
 Web scraping (like Scrapy, BeautifulSoup, Selenium)
 Test frameworks
 Multimedia
 Scientific computing
 Text processing and many more..

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: ")

# Adding two numbers


# User might also enter float numbers
sum = float(number1) + float(number2)
print(sum)
output:
First number: 12 Second number: 34 46.0

Python Program for factorial of a number


Factorial of a non-negative integer, is multiplication of all integers smaller
than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720.
Fundamentals:
What is Computer Science?
 The primary activity of computer science is programming.
 Programming Languages and computers are only tools.
 Computer science is fundamentally about is “computational problem
solving” means “solving problems by the use of computation.

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.

Local Environment Setup


Open a terminal window and type "python" to find out if it is already
installed and which version is installed.
 Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX, etc.)
 Win 9x/NT/2000
 Macintosh (Intel, PPC, 68K)
 OS/2
 DOS (multiple versions)
 PalmOS
 Nokia mobile phones
 Windows CE
 Acorn/RISC OS
 BeOS
 Amiga
 VMS/OpenVMS
 QNX
 VxWorks
 Psion
 Python has also been ported to the Java and .NET virtual machines

First Python Program


Let us execute programs in different modes of programming.
Interactive Mode Programming
Invoking the interpreter without passing a script file as a parameter
brings up the following prompt −
$ python
Python2.4.3(#1,Nov112010,13:34:43)
[GCC 4.1.220080704(RedHat4.1.2-48)] on linux2
Type"help","copyright","credits"or"license"for more
information.
>>>
Type the following text at the Python prompt and press the Enter −
>>>print"Hello, Python!"
If you are running new version of Python, then you would need to use
print statement with parenthesis as in print ("Hello, Python!");.
However in Python version 2.4.3, this produces the following result −
Hello, Python!
Script Mode Programming
Invoking the interpreter with a script parameter begins execution of the
script and continues until the script is finished. When the script is
finished, the interpreter is no longer active.
Let us write a simple Python program in a script. Python files have
extension .py. Type the following source code in a test.py file −
Live Demo
print"Hello, Python!"
We assume that you have Python interpreter set in PATH variable. Now,
try to run this program as follows −
$ python test.py
This produces the following result −
Hello, Python!
Let us try another way to execute a Python script. Here is the modified
test.py file −
Live Demo
#!/usr/bin/python

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

Break for pass

Class from print


continue global raise

Def if return

Del import try

Elif in while

Else is with

Except lambda yield

Lines and Indentation


Python provides no braces to indicate blocks of code for class and
function definitions or flow control. Blocks of code are denoted by line
indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements
within the block must be indented the same amount. For example −
if True:
print "True"
else:
print "False"
However, the following block generates an error −
ifTrue:
print"Answer"
print"True"
else:
print"Answer"
print"False"
Multi-Line Statements
Statements in Python typically end with a new line. Python does,
however, allow the use of the line continuation character (\) to denote
that the line should continue. For example −
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use
the line continuation character. For example −
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote
string literals, as long as the same type of quote starts and ends the
string.
The triple quotes are used to span the string across multiple lines. For
example, all the following are legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All
characters after the # and up to the end of the physical line are part of
the comment and the Python interpreter ignores them.

# 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

counter=100# An integer assignment


miles=1000.0# A floating point
name="John"# A string

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

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-786 0122L -21.9 9.322e-


36j

080 0xDEFABCECBDAECBFB 32.3+e18 .876j


AEl

- 535633629843L -90. -.6545+


0490 0J

- -052318172735L - 3e+26J
0x26 32.54e10
0 0

0x69 -4721885298529L 70.2-E12 4.53e-7j

 Python allows you to use a lowercase l with long, but it is


recommended that you use only an uppercase L to avoid confusion
with the number 1. Python displays long integers with an uppercase
L.
 A complex number consists of an ordered pair of real floating-point
numbers denoted by x + yj, where x and y are the real numbers and
j is the imaginary unit.
Python Strings
 Strings in Python are identified as a contiguous set of characters
represented in the quotation marks.
 Python allows for either pairs of single or double quotes.
 Subsets of strings can be taken using the slice operator ([ ] and [:] )
with indexes starting at 0 in the beginning of the string and working
their way from -1 at the end.
 The plus (+) sign is the string concatenation operator and the
asterisk (*) is the repetition operator.
 For example −

#!/usr/bin/python

str='Hello World!'

printstr# Prints complete string


printstr[0]# Prints first character of the string
printstr[2:5]# Prints characters starting from 3rd to
5th
printstr[2:]# Prints string starting from 3rd
character
printstr*2# Prints string two times
printstr+"TEST"# Prints concatenated string
This will produce the following result −
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python Lists
 Lists are the most versatile of Python's compound data types.
 A list contains items separated by commas and enclosed within
square brackets ([]).
 To some extent, lists are similar to arrays in C.
 One difference between them is that all the items belonging to a list
can be of different data type.
 The values stored in a list can be accessed using the slice operator
([ ] and [:]) with indexes starting at 0 in the beginning of the list and
working their way to end -1.
 The plus (+) sign is the list concatenation operator, and the asterisk
(*) is the repetition operator.
For example −
#!/usr/bin/python

list=['abcd',786,2.23,'john',70.2]
tinylist=[123,'john']

print list # Prints complete list


print list[0]# Prints first element of the list
print list[1:3]# Prints elements starting from 2nd
till 3rd
print list[2:]# Prints elements starting from 3rd
element
printtinylist*2# Prints list two times
print list +tinylist# Prints concatenated lists
This produce the following result −
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Python Tuples
 A tuple is another sequence data type that is similar to the list.
 A tuple consists of a number of values separated by commas. Unlike
lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in
brackets ( [ ] ) and their elements and size can be changed, while tuples
are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can
be thought of as read-only lists. For example −

#!/usr/bin/python
tuple=('abcd',786,2.23,'john',70.2)
tinytuple=(123,'john')

print tuple # Prints complete list


print tuple[0]# Prints first element of the list
print tuple[1:3]# Prints elements starting from 2nd
till 3rd
print tuple[2:]# Prints elements starting from 3rd
element
printtinytuple*2# Prints list two times
print tuple +tinytuple# Prints concatenated lists
This produce the following result −
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
The following code is invalid with tuple, because we attempted to update
a tuple, which is not allowed. Similar case is possible with lists −
#!/usr/bin/python

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'}

printdict['one']# Prints value for 'one' key


printdict[2]# Prints value for 2 key
printtinydict# Prints complete dictionary
printtinydict.keys()# Prints all the keys
printtinydict.values()# Prints all the values
This produce the following result −
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Dictionaries have no concept of order among elements. It is incorrect to
say that the elements are "out of order"; they are simply unordered.
Data Type Conversion
Sometimes, you may need to perform conversions between the built-in
types. To convert between types, you simply use the type name as a
function.
There are several built-in functions to perform conversion from one data
type to another. These functions return a new object representing the
converted value.
Sr.No. Function & Description
1 int(x [,base])
Converts x to an integer. base specifies the base if x is a
string.
2 long(x [,base] )
Converts x to a long integer. base specifies the base if x is a
string.
3 float(x)
Converts x to a floating-point number.
4 complex(real [,imag])
Creates a complex number.
5 str(x)
Converts object x to a string representation.
6 repr(x)
Converts object x to an expression string.
7 eval(str)
Evaluates a string and returns an object.
8 tuple(s)
Converts s to a tuple.
9 list(s)
Converts s to a list.
10 set(s)
Converts s to a set.
11 dict(d)
Creates a dictionary. d must be a sequence of (key,value)
tuples.
12 frozenset(s)
Converts s to a frozen set.
13 chr(x)
Converts an integer to a character.
14 unichr(x)
Converts an integer to a Unicode character.
15 ord(x)
Converts a single character to its integer value.
16 hex(x)
Converts an integer to a hexadecimal string.
17 oct(x)
Converts an integer to an octal string.

Python If ... Else


Python Conditions and If statements
Python supports the usual logical conditions from mathematics:

 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.

An "if statement" is written by using the if keyword.

Example
If statement:
a = 33
b = 200
if b > a:
  print("b is greater than a")
Indentation

Python relies on indentation (whitespace at the beginning of a


line) to define scope in the code. Other programming languages
often use curly-brackets for this purpose.
Example
If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
Elif

The elif keyword is pythons way of saying "if the previous


conditions were not true, then try this condition".
Example
a = 33
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
Else

The else keyword catches anything which isn't caught by the


preceding conditions.

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

If you have only one statement to execute, you can put it on


the same line as the if statement.

Example
One line if statement:
if a > b: print("a is greater than b")
And

The and keyword is a logical operator, and is used to combine


conditional statements:
Example
Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
  print("Both conditions are True")
Or

The or keyword is a logical operator, and is used to combine


conditional statements:

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

You can have if statements inside if statements, this is


called nested if statements.

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

if statements cannot be empty, but if you for some reason


have an if statement with no content, put in
the pass statement to avoid getting an error.

Example
a = 33
b = 200

if b > a:
  pass
Python While Loops
Python Loops

Python has two primitive loop commands:


 while loops
 for loops

The while Loop

With the while loop we can execute a set of statements as long


as a condition is true.

Example
Print i as long as i is less than 6:
i = 1
while i< 6:
  print(i)
  i += 1

Note: remember to increment i, or else the loop will continue


forever.
The while loop requires relevant variables to be ready, in this
example we need to define an indexing variable, i, which we
set to 1.

The break Statement

With the break statement we can stop the loop even if the while


condition is true:

Example
Exit the loop when i is 3:
i = 1
while i< 6:
  print(i)
  if i == 3:
    break
  i += 1
The continue Statement

With the continue statement we can stop the current iteration,


and continue with the next:

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

With the else statement we can run a block of code once when


the condition no longer is true:

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

A for loop is used for iterating over a sequence (that is either a


list, a tuple, a dictionary, a set, or a string).
This is less like the for keyword in other programming
languages, and works more like an iterator method as found in
other object-orientated programming languages.
With the for loop we can execute a set of statements, once for
each item in a list, tuple, set etc.
Example
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
Looping Through a String

Even strings are iterable objects, they contain a sequence of


characters:

Example
Loop through the letters in the word "banana":
for x in "banana":
  print(x)
The break Statement

With the break statement we can stop the loop before it has


looped through all the items:

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

With the continue statement we can stop the current iteration


of the loop, and continue with the next:

Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)
The continue Statement

With the continue statement we can stop the current iteration


of the loop, and continue with the next:

Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)

The range() Function


To loop through a set of code a specified number of times, we can use the range() function,

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)

Else in For Loop


The else keyword in a for loop specifies a block of code to be executed when the loop is finished:

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.

You can pass data, known as parameters, into a function.

A function can return data as a result.

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")

Default Parameter Value


The following example shows how to use a default parameter value.

If we call the function without parameter, it uses the default value:

Example
def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Passing a List as a Parameter


You can send any data types of parameter to a function (string, number, list, dictionary etc.), and it will be
treated as the same data type inside the function.

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

print("\n\nRecursion Example Results")


tri_recursion(6)

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

The expression is executed and the result is returned:

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))

Lambda functions can take any number of arguments:

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))

Das könnte Ihnen auch gefallen