19
1 Baku State University Applied-mathematics & cybernetics faculty INF-11 group Python Programming Language Adil Aliev Teacher: Ramin Mahmudzade Information Technologies & Programming chair

Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

  • Upload
    others

  • View
    11

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

1

Baku State University

Applied-mathematics & cybernetics facultyINF-11 group

Python Programming Language

Adil Aliev

Teacher: Ramin Mahmudzade

Information Technologies & Programming chair

Page 2: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

2

Contents

1. General Knowledge 1.1 About Python …………………………………………………………………….. 31.2 Using Interpreter …………………………………………………………………. 41.3 Basic syntax ……………………………………………………………………… 51.4 Arithmetic operations ……………………………………………………………. 61.5 Mathematical operations ............................................................................... 72. Explaining Python on samples2.1 Hello World! ................................................................................................... 92.2 ODD numbers ................................................................................................ 102.3 ax2+bx+c=0 equation ...................................................................................... 102.4 Prime numbers ............................................................................................... 112.5 Fibonacci numbers .......................................................................................... 122.6 Max & min array elements ............................................................................... 122.7 Calculating n

x ............................................................................................. 12

2.9 Palindrome strings .......................................................................................... 133. Qt Applications on Python3.1 What is Qt? ..................................................................................................... 143.2 PyQt 143.3 Simple Hello World! application ...................................................................... 153.4 Qt Designer .................................................................................................... 163.5 pyuic .............................................................................................................. 173.6 Simple calculator ........................................................................................... 17

Page 3: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

3

General Knowledge

1.1 About Python programming language Python is a dynamic object-oriented programming language that can be used for many kinds of software development. It offers strong support for integration with other languages and tools, comes with extensive standard libraries, and can be learned in a few days. Many Python programmers report substantial productivity gains and feel the language encourages the development of higher quality, more maintainable code.

Python was created by Guido van Rossum in 1990.

Python fully supported on Windows, Linux, Unix and Mac OS X platforms. Python is supported on these platforms too:

● AIX operating system● Amiga● AROS● AS/400● BeOS● BSD● FreeBSD● Mac OS 9● NetBSD● OpenBSD● OS/2● OS/390● Other Unixes, e.g. Irix● Palm OS● Plan 9● PlayStation 2● Psion● QNX● RISC OS (formerly Acorn)● Sharp Zaurus● SPARC Solaris● Symbian OS● VMS● VxWorks● Windows CE/Pocket PC● Xbox (Used primarily in the XBMC project)● z/OS

Python is widely used in many ranges. It can be used for web programming, system programming, for software developing for scripting and etc.

Page 4: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

4

Popular companies like Google, Yahoo, Nokia, Firaxis Games, Industrial Light & Magic, NASA STSCI uses Python for many tasks.

For scripting Python is used on Anaconda(installer of RedHat), BitTorent.

On the base of Python developed Iron Python for integrating Microsoft .NET framework, Jython – Pyhton version for Java Virtual Machine.

1.2 Using Interpreter

Python programs are executed by interpreter as we know. Interpreter can work on interactive mode and non-interactive. Interactive mode is needed to execute program step-by-step.

On UNIX machine Python interpreter is launched by typing

On Windows machine interpreter can be called by this method too if it`s on the search path. Or executing C:\Python24\python.exe (the path may be differs).

On interactive mode interpreter looks like shell and executes every command when we type.

For example:

Above the example after pressing “enter” key it will interpreter will execute print “Hello World” command and according the command interpreter will print Hello World as shown:

[root@laptop ~]# python

[root@laptop ~]# pythonPython 2.4.2 (#1, Feb 12 2006, 03:59:46)[GCC 4.1.0 20060210 (Red Hat 4.1.0-0.24)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> print "Hello World!"

[root@laptop ~]# pythonPython 2.4.2 (#1, Feb 12 2006, 03:59:46)[GCC 4.1.0 20060210 (Red Hat 4.1.0-0.24)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> print "Hello World!"Hello World!>>>

Page 5: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

5

After executing it will wait for our next input.

For exiting it must type end-of-file. It is usually done by pressing CTRL+D key combination on Unix, and CTRL+Z on Windows machines.

Interactive mode is not recommended for writing serious programs. Because you will not able to save it. For it use non-interactive mode. Write any program to file hello.py:

Then type

Interpreter will execute your program (or informs you about error & warnings).

1.3 Basic syntax

Python is scalar typed programming languages. In Python program you dont need declare variable types. If we need assign to any variable a any value we must write it like this:

If you know any C Like syntax language, as you know every operator ends by “;”. In Python operators don't end and aren't separate by “;”. Every operator must be written on the new line.

Example:

a=5b=10print a+b

When writing “subprograms” in cycles, in “if”s and etc. “subprograms” must be written after “:” symbol. If it consist of one line you may write it directly after “:” symbol, else if it consists of more lines it must be written after current line with any spaces(count must be same) before line.

print “Hello World”

root@localhost# python hello.py

a=55 # Integer numbera=5.5 # Real numbera=”Baku State University” # string valuea=’Baku State University’ # string value

Page 6: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

6

Example:

if a==b: print 'a is equal to b' else: print 'a is not equal to b'

if a==b: print 'a is equal' print 'to b'

else: print 'a is not equal' print 'to b'

1.4 Arithmetic operations

As a programming language there are some elementary and non-elementary arithmetic operations in Python.

Addition.Addition operation is defined on Python as “+” like most programming languages.f.e.: c=a+b

Subtraction.Subtraction is defined as “-”. f.e.: c=a-b

Multiplication.Multiplication is defined as “*”. f.e.: c=a*b

Division.Division is defined as “/”. f.e.: c=a/b

Page 7: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

7

#Examples for elementary arithmetic operations

a=5b=7

addt=a+b #Additionsubt=a-b #Subtractionmultp=a*b #Multiplicationdivs=a/b #Division

print (addt,subt,multp,divs)

In this case divs will return 0. 0 is integer part of a/b expression as we understand. Because a and b are described as an integer number and it will return an integer part. For calculating real answer of expression a/b we must describe a as 5.0 or 5. and b as 7.0 or 7.

RemainderOn Python remainder operator is similar to C. For calculating remainder when x is divided to y we can write

[root@ADIL_COMP ~]# python

Python 2.4.2 (#1, Feb 12 2006, 03:59:46)

[GCC 4.1.0 20060210 (Red Hat 4.1.0-0.24)] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>> 6 % 4

2

>>>

As we see we got 2 as a result. It means 6 / 4 = 1 (2)

1.5 Mathematical operations

PowerThere is a useful mathematical operation which it is not defined on other programming languages. This operation is “**” operation. It will be used to calculate an

First operand will be a and the second operand will be n in programs.For example:

Page 8: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

8

A=2**8 #256

B=2**4 #16

C=3**2 #9

Most mathematical operations are not included in standard library. For example sqrt() operation is not included in standard library. It is included in math library.

For using this function math library must be included into our program as described:

>>>import math

>>>math.sqrt(9)

3.0

>>>

There are several other functions for mathematical operations in math library.

pow(x,y)Calculates and returns xy . This function is equivalent to x**y.

fabs(x)Returns modulo of x. This function is equivalent to abs(x)

floor(x)Returns integer part of x where x is real number.

exp(x)Returns x**e

log(x)Return natural logarithm of x.

log10(x)Return logarithm of x 10th base.

Page 9: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

9

ceil(x)This function is useful in many situations especially creating pages. For example: we have 57 lines and we must prepare pages which consist of 10 results per page. We get 6 pages five of them consist of 10 lines and last 7. And ceil(57) will return 6 as we understand.

fmod(x,y)This function is equivalent to x % y.

Trigonometrical functions

acos(x)Returns arccos of x argument.

asin(x)Returns arcsin of x argument.

atan(x)Returns arctg of x argument.

atan2(x,y)This function is equivalent to atan(x/y). In case of y=0 will returned pi/2

cos(x)Returns cos of x argument.

cosh(x)Returns hyperbolic cosinus value of x argument.

sin(x)Returns sin of x argument.

sinh(x)Returns hyperbolic sinus of x argument.

tan(x)Returns tg of x argument.

tanh(x)Returns hyperbolic tg of x argument.

Note: There are constants like Pi and e in math library.

2. Explaining Python on samplesI think that to look over some programs for explaining Python is a good idea. That is here we will look for simple programs written on Python.

Page 10: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

10

2.1 Hello World!

Idea of “Hello World!” is simple. Program must print “Hello World!” expression.

print ('Hello World!\n')

Inserting “\n”at the end of line will make that cursor will be moved to the next line.We may write “\t” to insert here tabulation.May be you have a question which sounds like this:“Expression begins with ' and end with ' symbol. What I must do if I want to write ' as a part of expression?”

Very simple. In this case we must insert ' symbol in the expression as \'. For example:

print (' \'Hello World \' \n')

2.2 ODD numbers

Here is described program which checks a. If a is an odd number prints information.

On 1st line as a CGI application described path to python.

def defines function named odd and x is argument of odd. return operator returns to odd true if x is an odd or returns false if x is not an odd number.

#!/usr/bin/env python

def odd(x): if ((x % 2)==0) : return True else: return False

a=input()

if odd(a): print a,'is an odd number'else: print a,'is not an odd number'

a=input() asks for input. And typed value will be assigned to a.

2.3 ax2+bx+c=0 equation

Page 11: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

11

One of methods solving ax2+bx+c=0 equation is to calculate discriminant and according it to find x1 and x2 .

D= b2 4ac

if D<0 there are nothing to solve,if D=0 there is one x,

if D>0 there are two different xs

x= b±D2a

from math import sqrt imports sqrt function from math library for using sqrt directly.

#!/usr/bin/env pythonfrom math import sqrta=input()b=input()c=input()

D=b**2-4*a*c

if D<0: print 'Nothing to solve'elif D==0: x=(-b+sqrt(D))/(2*a) print xelse: x1=(-b+sqrt(D))/(2*a) x2=(-b-sqrt(D))/(2*a) print x1,x2

2.3 Prime numbers

Prime numbers divides only to itself and 1. The program checks for numbers which is prime and which is not.

Page 12: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

12

#!/usr/bin/env pythonfrom math import sqrtfrom math import floor

def prime(x): c=True for i in range(2,a): print x,i,x % i if (x % i) == 0 : c=False break return c

a=input()

if prime(a): print a,'is prime'else: print a,'is not a prime'

2.4 Fibonacci numbers

n=input()a=0b=1while b<n: print b a,b=b,a+b

Calculating Fibonacci numbers on Python very simple as you see.

2.5 Min & Max array elements

Let we have an array a with elements like described: a=[4,1,6,1,7,8,3,2,5,6,7]We want to change the indexes of maximal element and minimal.

Page 13: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

13

#!/usr/bin/env python

a=[4,1,6,1,7,8,3,2,5,6,7]

def maxi(): for i in range(len(a)): if a[i]==max(a): return i

def mini(): for i in range(len(a)): if a[i]==min(a): return i

temp=a[maxi()]a[maxi()]=a[mini()]a[mini()]=temp

print a

maxi function defined us will find index of maximum, mini will find index of minimum.max() function is built-in function of Python which finds maximum element of an array.len() is for getting length of array a.

2.6 Calculating n x

We have learned how to calculate x . But sometimes we need calculate any

expressions by n x formula. For calculating it, e

1n

ln x formula will help us.

But on calculating by this formula, our answer will a bit differ from real answer if 1/n will cyclic. Because the computer will calculate 1/n first. And then will multiplicity it to ln(x).

For this reason we will bit change this formula: eln x

n

And our program will :

#!/usr/bin/env pythonfrom math import logfrom math import exp

def nroot(n,x): if x<0: return -exp(log(abs(x))/n) else: return exp(log(x)/n)

print (nroot(3,27))

Above program will calculate 27 from root 3.

2.7 Palindrome strings

This program will check for is given string is palindrome or not

Page 14: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

14

#!/usr/bin/env pythona='SalaS'

c=Truefor i in range(len(a) / 2): if a[i]!=a[len(a)-i-1]: print a,'is not a polindrome' c=False breakif (c): print a,'is polindrome'

3.Qt Applications on Python

On Python we can create Qt applications too.

3.1 What is Qt?

Qt is very advanced: the library offers a large set of well-designed screen objects, or widgets, and many utility classes. In addition, Qt has a clean object-oriented design that is easy to grasp and intuitive to use.

There are two kinds of objects in the Qt library— visual and non-visual. The mother of all visual objects is QWidget, widget being the term Qt uses for what the Windows world usually calls control. There are simple widgets such as labels and buttons, and complex widgets such as canvas views. Even dialog windows are descended from Qwidget.

3.2 PyQtUnlike a tool like Visual Basic, which consists of a GUI engine with a scripting language built-in, Python does not have a native GUI interface. But there are many GUI libraries available for Python — examples are wxPython, Tkinter, PyGTK, PyFLTK, FoxPy, and PyQt. PyQt is based on Qt, an advanced GUI library for Windows and Unix written in C++ by Eirik Eng and Arnt Gulbrantsen of Trolltech in Norway. It's quite easy to wrap C++ or C libraries so they can be used from Python — and when Phil Thompson was looking around for a good GUI library for Python he decided to wrap Qt, producing PyQt. PyQt forms the basis for the BlackAdder rapid development environment.

PyQt applications can run without any change, without recompiling, both on Windows and Unix/X11 systems — and soon on Apple's OS X, too.

Page 15: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

15

PyQt widgets can be drawn in styles, to make them appear exactly like the native widgets of the operating system the application runs on (or like something different altogether, if you want).

Scripting languages like Python have a reputation for bad performance, but PyQt applications perform very well indeed; there is just a thin wrapper between the GUI objects and Python. Those GUI objects do most of the heavy work of pixel shifting, and they are written in well-optimized C++. If you try to do things like writing your own DTP layout engine from scratch using the Qt drawing primitives, you might be hindered by the slowness inherent in a byte-code interpreted language like Python, but on the whole, your application will be as responsive as one written in pure C++, and you'll have a working application where you would still be hacking the first prototype in C++.

3.3 Simple Hello World! Application

Simple Qt based Hello World program can be written like this:

#!/usr/bin/env pythonimport sysfrom qt import *

class HelloButton(QLabel):

def __init__(self, *args): apply(QLabel.__init__, (self,) + args) self.setText("Hello World")

class HelloWindow(QMainWindow):

def __init__(self, *args): apply(QMainWindow.__init__, (self,) + args) self.label=HelloButton(self) self.setCentralWidget(self.label)

def main(args): app=QApplication(args) win=HelloWindow() win.show() app.exec_loop()

if __name__=="__main__": main(sys.argv)

Result of it will:

Page 16: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

16

3.4 Qt Designer

Qt Designer is a powerful GUI layout and forms builder, which enables rapid development of high-performance user interfaces with native look and feel across all supported platforms. Stand-alone, or integrated with IDEs like Microsoft Visual Studio .NET, Qt Designer includes powerful features such as preview mode, automatic widget layout, support for custom widgets, an advanced property editor and more.

Qt Designer makes it easy to visually design advanced user interfaces - at any time, you can generate the code required to reproduce and preview your interface, changing and adjusting your design as often as you like.

Qt Designer helps you build cross-platform user interfaces with layout tools that move and scale your controls (widgets) automatically at runtime, taking font sizes and language use into consideration. The resulting interfaces are both functional and native-looking, comfortably suiting your users' operating environments and preferences.

The designer's native file format (*.ui files) is a well-defined true XML format. And it helps to write programs on any language which will be used our designed programs.

Page 17: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

17

3.5 pyuic(PyQt User Interface Compiler)

pyuic is command line utility which converts XML based .ui files which created by Qt Designer to Python classes. After finishing to design user interface, Qt Designer saves that file to XML based .ui file. And pyuic will help us to convert this files to Python code.

3.6 Simple Calculator

Lets create simple GUI calculator.

At first lets create GUI on Qt Designer.

There are one lineEdit component to display result, 10 pushButtons component to enter number, 4 pushButtons to enter operations, and a button “equal” to display result.Then save it by name bsucalc.ui under /root directory.

Open terminal, type there:

[root@ADIL_COMP ~]# pyuic -o bsucalc.py bsucalc.ui

Page 18: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

18

This command will convert .ui file to Python program and will write it to bsucalc.py file.

Then execute the bsucalc.py

[root@ADIL_COMP ~]# python bsucalc.py

Thats all. You will see this window:

Page 19: Python Programming Language - TUV · path. Or executing C:\Python24\python.exe (the path may be differs). On interactive mode interpreter looks like shell and executes every command

19

Literature:

1. Г. Россум, Ф.Л.Дж. Дрейк, Д.С. Откидач - Язык программирования Python2. Wikipedia.org3. http://www.citforum.ru4. Чаплыгин А. Н. -Учимся программировать вместе с Питоном5. David M. Beazley - Python Essential Reference6. http://www.commandprompt.com/community/pyqt