Python Listenin Elemalarını Çıkartmak. Python велосипед


Python Turtle Graphics - The Complete Guide.

Python turtle graphics is one of the cool ways to implement your knowledge in Python before you start writing complex programs to solve problems in life.

In this tutorial, I will make Python more practical for you and also fun.

I know that before you came across this tutorial, you were looking for fun things to do with Python.

So I will do my best to make every bit of this tutorial exciting.

let’s get to the basics now.

Don’t forget to:

To create a turtle window on your computer screen, please open a new file editor window and type the following code snippet. Save it as Turtle_window.py

from turtle import Turtle t=Turtle()

from turtle import Turtle

t=Turtle()

When you run this program, you will get this result on your screen.

Python Turtle Graphics Window

You can see an arrow head at the middle point of the window pointing to the east which is the default position. This location is called home.

The position of the turtle is specified with the two-dimensional coordinate system, (x,y).

The default position of the turtle(arrow head) is (0,0) which is the center of the window.

I will have to talk about some things that are important and it is for those that will use Python IDE (pycharm, spyder etc) for this tutorial.

When you run the code snippets of this tutorial in any Python IDE you will notice that the turtle window will open and close immediately.

To allow the turtle window stay so you can see the output of your program, include t.screen.mainloop() in your program. It should be the last statement of your program.

To make the turtle window disappear after viewing the turtle screen when you click on the turtle canvas, use the method screen.exitonclick() .

Include t.screen.exitonclick() before t.screen.mainloop().

The following code snippet shows you how you can use them.

from turtle import Turtle t=Turtle() t.screen.exitonclick() t.screen.mainloop()

from turtle import Turtle

 

t=Turtle()

 

t.screen.exitonclick()

 

t.screen.mainloop()

When you run the code snippet above in any Python IDE such as Pycharm or Spyder, the turtle screen won’t disappear immediately unless you click on the turtle canvas.

The default background color is white which can be boring.

To change the color of the turtle window background, please open a new file editor window and type the following code snippet. Save it as Turtle_window_background.py

from turtle import Turtle t=Turtle() t.screen.bgcolor('black')

from turtle import Turtle

t=Turtle()

t.screen.bgcolor('black')

When you run this program, you will get this result on your screen.

Python Turtle Graphics Window

The background color of the turtle window is black but there is no turtle because the default color of the turtle is black.

Note :

The screen.bgcolor() method accepts one argument which is the color of the turtle window as a string.

The default color of Python turtle window is white. You can change it using the method screen.bgcolor()

To change the color of the turtle,

Type the following code snippet into a new file editor and save it as any name you like.

from turtle import Turtle t=Turtle() t.screen.bgcolor("black") t.color("blue")

from turtle import Turtle

t=Turtle()

t.screen.bgcolor("black")

t.color("blue")

When you run this program, you will get this result on your screen.

Blue turtle on a black canvas

t.color(“blue”) changes the color of the turtle to blue.

How to change the Background picture of the Turtle Screen.

Here’s a code snippet that changes the background image of the turtle screen( turtle_background_pic.py) .

from turtle import Turtle t=Turtle() t.hideturtle() t.screen.bgpic("night-owl-75.gif")

from turtle import Turtle

 

t=Turtle()

 

t.hideturtle()

 

t.screen.bgpic("night-owl-75.gif")

Here’s the output of the program(turtle_background_pic.py)

An Owl image on turtle canvas

Note:

  • Only the gif image format is accepted.
  • Let your program and the gif image be in the same folder on your computer.
  • I provided some gif images in the source code download file.

By default the turtle faces the east, to change the direction in which the turtle is facing,

from turtle import Turtle t=Turtle() t.setheading(180)

from turtle import Turtle

t=Turtle()

t.setheading(180)

The syntax is,

t.setheading(angle)

Angle 90 sets the turtle to face the North.

Angle 180 sets the turtle to face the West.

Angle 270 sets the turtle to face the South.

Angle 360 or 0 set turtle to face the East

You can set the turtle to face any angle of your choice.

You can change the direction of the turtle using the following syntax

t.left(angle)

t.right(angle)

The above is used to rotate the turtle either to the left or to the right at the angle specified.

The default shape of a turtle is known as a classic.

To change the shape of the turtle you use the shape() method.

The shape() method accepts a string as an argument. The string is the name of a valid shape in the TurtleScreen’s shape dictionary.

The valid turtle shapes are:

  • Arrow
  • Circle
  • Square
  • Triangle
  • Turtle
  • Classic

Like I said earlier, the default shape of the turtle is known as a classic.

I will show you my favorite turtle shape which you will love as well.

Open a new file editor window and type the following code snippet. Save it as turtle_shape.py

from turtle import Turtle t=Turtle() t.shape("turtle")

from turtle import Turtle

t=Turtle()

t.shape("turtle")

when you run the program above, you will get:

Turtle Shape-“Turtle”

From the above screenshot, the turtle is small. To increase the size of the turtle, use the shapesize() method.

To illustrate this, run the following code snippet.

from turtle import Turtle t=Turtle() t.shape("turtle") t.shapesize(20)

from turtle import Turtle

t=Turtle()

t.shape("turtle")

t.shapesize(20)

Here is the output of the above program.

Turtle shape with a bigger shape size

To draw a line use the syntax below

t.fd(distance)

or

t.goto(x,y)

distance is the value of the length of the line.

t.goto(x,y) moves the turtle to an absolute position

Note:

The Cartesian system is the coordinate system for Turtle. So x and y represent values in the x and y axis respectively.

t.fd(distance)  moves the turtle by the specified distance.

Open a new file editor window and type the following code snippet. Save it as draw_line.py

from turtle import Turtle t=Turtle() t.fd(100)

from turtle import Turtle

t=Turtle()

t.fd(100)

When you run the program above you will get:

A line with a distance of 100 pixels

 

The above program moves the turtle 100 pixels to the east.

Open a new file editor window and type the following code snippet. Save it as turtle_go_to.py

from turtle import Turtle t=Turtle() t.screen.bgcolor("black") t.color("blue") t.goto(100,50)

from turtle import Turtle

t=Turtle()

t.screen.bgcolor("black")

t.color("blue")

t.goto(100,50)

Running turtle_go_to.py you would get,

Drawing a line with the method goto()

How to Increase the Thickness of a Line

t.pensize() accepts an integer as an argument to set the thickness of the line.

Open a new file editor and save the following code snippet as  turtle_line_thickness.py

from turtle import Turtle

t=Turtle() t.screen.bgcolor("black") t.color("blue") t.pensize(10) t.fd(100)

t=Turtle()

t.screen.bgcolor("black")

t.color("blue")

t.pensize(10)

t.fd(100)

when you run the code snippet above, you will get:

You may not need the turtle to appear in your drawing as you just need a line. To achieve this open a new file editor and save the following code snippet as draw_line_without_turtle.py

from turtle import Turtle t=Turtle() t.fd(100) t.hideturtle()

from turtle import Turtle

t=Turtle()

t.fd(100)

t.hideturtle()

Running this program will give you,

How to make turtle disappear

You have learned a lot, so let us do something fun with Python.

Project 1:

Write a program to draw a square on the computer screen and save it as turtle_square.py

Let the background screen color be black and color of the line drawn red.

Solution 1: for a beginner that doesn’t know Python function and for loop

from turtle import Turtle t=Turtle() t.screen.bgcolor("black") t.color("red") t.hideturtle() t.fd(100) t.left(90) t.fd(100) t.left(90) t.fd(100) t.left(90) t.fd(100)

from turtle import Turtle

t=Turtle()

t.screen.bgcolor("black")

t.color("red")

t.hideturtle()

t.fd(100)

t.left(90)

t.fd(100)

t.left(90)

t.fd(100)

t.left(90)

t.fd(100)

The above program first changes the window background to black and the turtle to red using t.screen.bgcolor(“black”) and  t.color(“red”).

The turtle is then made invisible using this line of code t.hideturtle()

The turtle moves 100 pixels to the east (t.fd(100)) and draws a horizontal line.

It then faces the north by rotating 90degrees(t.left(90)) to the left and moves 100 pixels to the north, drawing a vertical line.

t.left(90)  makes the turtle face the west by rotating it 90 degrees left. It then moves 100 pixels to the west, drawing a horizontal line.

t.left(90) makes the turtle face the south by rotating it 90 degrees left. It then moves 100 pixels to the south, drawing a vertical line.

The turtle turns 90 degrees left to face the east, it then moves 100 pixels to the east which is the default position of the turtle.

Finally, a square is drawn.

Solution 2:

Let’s make our code more readable and maintainable with function and a for loop. Save this as turtle_square1.py

from turtle import Turtle t=Turtle() t.screen.bgcolor("black") t.color("red") t.hideturtle() def square(length): for steps in range(4): t.fd(length) t.left(90) square(100)

from turtle import Turtle

t=Turtle()

t.screen.bgcolor("black")

t.color("red")

t.hideturtle()

 

def square(length):

    for steps in range(4):

        t.fd(length)

        t.left(90)

 

square(100)

Running turtle_square1.py, you will get a square on your computer screen.

A square

Note:

Basically, the for loop runs through the code below four times.

 t.fd(length)

 t.left(90)

Did you ever do an isometric or auxiliary drawing?

Well, I did and to be honest with you, it was boring to me.

But Python made it fun as I could write some bunch of codes and my computer would do the drawing.

In the next project, you will draw an isometric block.

Project 2:

Write a program to draw a rectangle inclined to 30 degrees on the computer screen and save it as turtle_rectangle.py

Let the screen background color be black and color of the line drawn red.

Solution 1: for a beginner that doesn’t know Python function and for loop

from turtle import Turtle t=Turtle() t.screen.bgcolor("black") t.color("red","blue") t.left(30) t.hideturtle() t.fd(100) t.left(90) t.fd(200) t.left(90) t.fd(100) t.left(90) t.fd(200)

from turtle import Turtle

t=Turtle()

t.screen.bgcolor("black")

t.color("red","blue")

t.left(30)

t.hideturtle()

t.fd(100)

t.left(90)

t.fd(200)

t.left(90)

t.fd(100)

t.left(90)

t.fd(200)

Solution 2:

Open a new file editor window and type the following code snippet. Save it as turtle_rectangle1.py

from turtle import Turtle t=Turtle() t.screen.bgcolor("black") t.hideturtle() t.color("red") def slanted_rectangle(length,width,angle): t.setheading(angle) for steps in range(2): t.fd(width) t.left(90) t.fd(length) t.left(90) slanted_rectangle(length=200,angle=45,width=100)

from turtle import Turtle

t=Turtle()

t.screen.bgcolor("black")

t.hideturtle()

t.color("red")

 

def slanted_rectangle(length,width,angle):

    t.setheading(angle)

    for steps in range(2):

        t.fd(width)

        t.left(90)

        t.fd(length)

        t.left(90)

 

slanted_rectangle(length=200,angle=45,width=100)

Running program turtle_rectangle.py and turtle_rectangle2.py you would get

An Inclined Rectangle

Can we do one more project?

Yes, of course.

Project 3:

Write a program to draw a triangle on the computer screen and save it as turtle_triangle.py

Let the screen background color be black and color of the line drawn red.

Solution:

from turtle import Turtle t=Turtle() t.screen.bgcolor("black") t.color("red") t.hideturtle() def triangle(length,angle=120): for steps in range(3): t.fd(length) t.left(angle) triangle(200)

from turtle import Turtle

t=Turtle()

t.screen.bgcolor("black")

t.color("red")

t.hideturtle()

 

def triangle(length,angle=120):

    for steps in range(3):

        t.fd(length)

        t.left(angle)

 

triangle(200)

Running the above program you would get

Don’t be over excited yet, there’s a ton of room for improvement in our programs.

How to Draw a Circle

The circle() method is used to draw a circle and it can accept three arguments which are:

  1. radius
  2. extent
  3. steps

The most important is radius and extent. Though, extent and steps are optional(i.e a circle can still be drawn without including them.)

The radius accepts an integer which is the radius of the circle.

The extent accepts an integer which is an angle. To cut short the technical explanation, it determines the part of the circle that will be drawn.

If you assign 360, a full circle will be drawn, 180 will draw a semi-circle. (Do you now understand why I said extent represents an angle?)

Let’s do some coding. The code snippet below will draw a semi-circle.

Open a new file editor window and type the following code snippet. Save it as turtle_semi_circle.py

from turtle import Turtle t=Turtle() t.circle(50,180) t.hideturtle()

from turtle import Turtle

 

t=Turtle()

 

t.circle(50,180)

 

t.hideturtle()

Here’s the output of the code snippet.

Semi circle

Well, let’s do something a bit harder so you can learn more.

Can you do something like this?

Semi Circle

If you could not do it, don’t worry.

Open a new file editor window and type the following code snippet. Save it as  semi_circle1.py

from turtle import Turtle t=Turtle() t.hideturtle() t.up() t.setx(50) t.down() t.setheading(90) t.circle(50,180)

from turtle import Turtle

 

t=Turtle()

 

t.hideturtle()

 

t.up()

 

t.setx(50)

 

t.down()

 

t.setheading(90)

 

t.circle(50,180)

The only thing strange about this code snippet is t.setx().

The method setx() positions the turtle on the x-axis leaving the y-axis unchanged.

In addition, the method sety() positions the turtle on the y-axis leaving the x-axis unchanged.

In the next section, we will draw a full circle.

Imagine the turtle as a paint brush in the hand of an artist. The artist can lift up the brush off the canvas to place it on another position on the canvas.

To do a similar action with the turtle, you use this syntax below,

t.up()  

To put back the turtle on the canvas, use this syntax below,

t.down()

Note:

No drawing is done when the turtle is up.

Drawing is done when the turtle is down.

Let me explain the following syntax by writing cool programs

  • up()
  • down()
  • goto(x,y)
  • circle(radius)

I want you to observe the following code snippet and the diagram.

Code snippet 1:

Open a new file editor window and type the following code snippet. Save it as code_snippet_1.py

from turtle import Turtle t=Turtle() t.screen.bgcolor("black") t.color("red") t.goto(100,50) t.circle(50) t.hideturtle()

from turtle import Turtle

t=Turtle()

t.screen.bgcolor("black")

t.color("red")

t.goto(100,50)

t.circle(50)

t.hideturtle()

If you run the code above you will get;

code snippet 1 screenshot

From the diagram above you can observe that the turtle moved to an absolute position (t.goto(100,50))

and a circle with a radius of 50 is drawn(t.circle(50))

The next code snippet will remove the line in the diagram above.

Code snippet 2:

Open a new file editor window and type the following code snippet. Save it as code_snippet_2.py

from turtle import Turtle t=Turtle() t.screen.bgcolor("black") t.color("red") t.up() t.goto(100,50) t.down() t.circle(50) t.hideturtle()

from turtle import Turtle

t=Turtle()

t.screen.bgcolor("black")

t.color("red")

t.up()

t.goto(100,50)

t.down()

t.circle(50)

t.hideturtle()

If you run the code above you will get;

code snippet 2 screenshot

 

t.up() – raises the turtle up and no drawing is done when the turtle is up.

t.goto(100,50) – moves the turtle to an absolute position.

t.down() – brings down the turtle.

t.circle(50) – draws a circle with a radius of the value 50

You can replace t.up(), t.goto(100,50), t.down(), t.circle(50) with the method setposition()

The setposition() method accepts two arguments which are the coordinates x and y.

This method moves the turtle to an absolute position. If the turtle pen is down, a line will be drawn to the specified position.

We have been drawing many shapes but we have not applied colors to our drawing.

Here are some ways to apply colors to your drawing.

t.begin_fill() and t.end_fill() –

t.begin_fill() is called before drawing a shape to be filled with the color of the turtle.

t.end_fill() fills the shape drawn with the color of the turtle after t.begin_fill() has been called.

Open a new file editor window and type the following code snippet. Save it as red_circle.py

from turtle import Turtle t=Turtle() t.screen.bgcolor("black") t.color("red") t.begin_fill() t.circle(50) t.end_fill() t.hideturtle()

from turtle import Turtle

t=Turtle()

t.screen.bgcolor("black")

t.color("red")

t.begin_fill()

t.circle(50)

t.end_fill()

t.hideturtle()

If you run the code above you will get:

Red circle

t.fillcolor()

This meth0d changes the color of the turtle only, when the turtle moves, the color path remains the default color (black) .

The color can be passed as a string such as:

t.fillcolor(“blue”)

The next thing we are going to do will blow your mind.

Open a new file editor window and type the following code snippet. Save it as turtle_random_walk.py

from turtle import Turtle import random t=Turtle() t.screen.bgcolor("black") def random_drawing(turns,distance): for x in range(turns): right=t.right(random.randint(0,360)) left=t.left(random.randint(0,360)) t.color(random.choice(["blue","red","green"])) random.choice([right,left]) t.fd(distance) random_drawing(100,50)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

from turtle import Turtle

import random

 

t=Turtle()

t.screen.bgcolor("black")

 

def random_drawing(turns,distance):

    for x in range(turns):

        right=t.right(random.randint(0,360))

        left=t.left(random.randint(0,360))

        t.color(random.choice(["blue","red","green"]))

        random.choice([right,left])

        t.fd(distance)

 

 

 

random_drawing(100,50)

My output of the program is:

Random drawing

 Note:

We can’t get the same result.

Why?

This is because I use the random module.

A random module picks random element in a sequence.

Imagine how long it will take for your turtle to draw something like this:

Random drawing

It would take you a lot of time.

But here’s the best part of turtle,

You can increase the speed of the turtle.

How then?

t.speed() accepts an integer as an argument to set the speed of the turtle. The value 0(zero) is the fastest speed of the turtle

So to increase the speed of the program (turtle_random_walk.py) include t.speed(0) before defining the function randomwalk.

The dot() method receives two optional arguments, which are:

  • The size of a dot
  • The color of the dot

Here is a simple dot of size 20 and blue in color.

A dot

Here is the code snippet.

from turtle import Turtle t = Turtle() t.screen.bgcolor("black") t.hideturtle() t.dot(20,"blue")

from turtle import Turtle

t = Turtle()

t.screen.bgcolor("black")

t.hideturtle()

t.dot(20,"blue")

So we have been drawing shapes on our computer screen, and am getting really bored of it.

Let’s do something a bit different by writing text on the computer screen.

To write on your computer screen, use the write() method.

The write() method accepts four arguments, which are:

  • arg– this is the string object of the text you want to write to the TurtleScreen.
  • move– this argument is optional and it can only be assigned to the value “True” or “False”. When True a line will be drawn below the text.
  • align– you assign this argument either to the left, right or center. This argument is also optional
  • font– this argument basically determines the font name, font size, font type of your text.

To understand this better, let’s write some codes.

Project 4:

Write a program to display Cool Python Codes on the turtle screen.

Open a new file editor and save the following code snippet as write_program.py

from turtle import Turtle t = Turtle() t.hideturtle() t.write("Cool Python Codes",move=True,align="center",font=("Freestyle Script",50,"normal"))

from turtle import Turtle

t = Turtle()

t.hideturtle()

t.write("Cool Python Codes",move=True,align="center",font=("Freestyle Script",50,"normal"))

Here is the output of the program.

Cool Python Codes

The cool font I used is “Freestyle Script” and I got it from Microsoft word application.

Let’s do something fun in Python.

I want to do some logo designs for my blog, and I don’t want to use Photoshop.

Guess what?

I will do it in Python.

Project 5: How to do logo design with Python

Here are some code snippets to the logo design for my blog.

Logo design 1:

Open a new file editor and save the following code snippet as Cool_Python_Codes_Logo1.py

from turtle import Turtle t=Turtle() t.screen.bgcolor("black") t.color("white") def square(length): for steps in range(4): t.fd(length) t.left(90) def draw_square(x,y,length): t.hideturtle() t.up() t.goto(x,y) t.down() t.begin_fill() square(length) t.end_fill() def rectangle(length,width): for steps in range(2): t.fd(width) t.left(90) t.fd(length) t.left(90) def draw_rectangle(length,width,x,y): t.hideturtle() t.up() t.goto(x,y) t.down() t.begin_fill() rectangle(length,width) t.end_fill() t.write("Cool Python Codes", move=True, align='center', font=('Cambria', 18, 'normal')) draw_square(-120,-20,20) draw_square(-120,30,20) draw_square(-140,0,20)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

from turtle import Turtle

t=Turtle()

t.screen.bgcolor("black")

t.color("white")

 

def square(length):

    for steps in range(4):

        t.fd(length)

        t.left(90)

 

def draw_square(x,y,length):

    t.hideturtle()

    t.up()

    t.goto(x,y)

    t.down()

    t.begin_fill()

    square(length)

    t.end_fill()

 

def rectangle(length,width):

    for steps in range(2):

        t.fd(width)

        t.left(90)

        t.fd(length)

        t.left(90)

 

def draw_rectangle(length,width,x,y):

    t.hideturtle()

    t.up()

    t.goto(x,y)

    t.down()

    t.begin_fill()

    rectangle(length,width)

    t.end_fill()

 

t.write("Cool Python Codes", move=True, align='center',

        font=('Cambria', 18, 'normal'))

 

draw_square(-120,-20,20)

draw_square(-120,30,20)

draw_square(-140,0,20)

Here is the output of the program above.

Code Python Codes logo design 1.

Logo design 2:

Open a new file editor and save the following code snippet as Cool_Python_Codes_Logo_2.py

from turtle import Turtle t=Turtle() t.screen.bgcolor("black") t.color("blue") def square(length): for steps in range(4): t.fd(length) t.left(90) def draw_square(x,y,length): t.hideturtle() t.up() t.goto(x,y) t.down() t.begin_fill() square(length) t.end_fill() def rectangle(length,width): for steps in range(2): t.fd(width) t.left(90) t.fd(length) t.left(90) def draw_rectangle(length,width,x,y): t.hideturtle() t.up() t.goto(x,y) t.down() t.begin_fill() rectangle(length,width) t.end_fill() t.write("Cool Python Codes", move=True, align='center', font=('Cambria',18, 'normal')) draw_square(-120,-20,20) draw_square(-120,30,20) draw_rectangle(30,10,-130,0)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

from turtle import Turtle

 

t=Turtle()

t.screen.bgcolor("black")

t.color("blue")

 

def square(length):

    for steps in range(4):

        t.fd(length)

        t.left(90)

 

def draw_square(x,y,length):

    t.hideturtle()

    t.up()

    t.goto(x,y)

    t.down()

    t.begin_fill()

    square(length)

    t.end_fill()

 

def rectangle(length,width):

    for steps in range(2):

        t.fd(width)

        t.left(90)

        t.fd(length)

        t.left(90)

 

def draw_rectangle(length,width,x,y):

    t.hideturtle()

    t.up()

    t.goto(x,y)

    t.down()

    t.begin_fill()

    rectangle(length,width)

    t.end_fill()

 

 

 

t.write("Cool Python Codes", move=True,

        align='center',

        font=('Cambria',18, 'normal'))

 

draw_square(-120,-20,20)

draw_square(-120,30,20)

draw_rectangle(30,10,-130,0)

Here is the output of the program above.

Cool Python Codes logo design 2

Logo design 3:

Open a new file editor and save the following code snippet as Cool_Python_Codes_Logo_3.py

from turtle import Turtle t=Turtle() t.screen.bgcolor("black") t.color("magenta") def square(length): for steps in range(4): t.fd(length) t.left(90) def draw_square(x,y,length): t.hideturtle() t.up() t.goto(x,y) t.down() t.begin_fill() square(length) t.end_fill() def rectangle(length,width): for steps in range(2): t.fd(width) t.left(90) t.fd(length) t.left(90) def draw_rectangle(length,width,x,y): t.hideturtle() t.up() t.goto(x,y) t.down() t.begin_fill() rectangle(length,width) t.end_fill() t.write("Cool Python Codes", move=True, align='center', font=('Cambria', 18, 'normal')) draw_square(-120,-20,20) draw_square(-120,30,20) draw_rectangle(30,40,-140,0) draw_rectangle(70,10,-170,-20) draw_rectangle(10,70,-170,-30) draw_rectangle(10,70,-170,50)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

from turtle import Turtle

 

t=Turtle()

t.screen.bgcolor("black")

t.color("magenta")

 

def square(length):

    for steps in range(4):

        t.fd(length)

        t.left(90)

 

def draw_square(x,y,length):

    t.hideturtle()

    t.up()

    t.goto(x,y)

    t.down()

    t.begin_fill()

    square(length)

    t.end_fill()

 

def rectangle(length,width):

    for steps in range(2):

        t.fd(width)

        t.left(90)

        t.fd(length)

        t.left(90)

 

def draw_rectangle(length,width,x,y):

    t.hideturtle()

    t.up()

    t.goto(x,y)

    t.down()

    t.begin_fill()

    rectangle(length,width)

    t.end_fill()

 

t.write("Cool Python Codes", move=True, align='center',

        font=('Cambria', 18, 'normal'))

 

draw_square(-120,-20,20)

draw_square(-120,30,20)

draw_rectangle(30,40,-140,0)

draw_rectangle(70,10,-170,-20)

draw_rectangle(10,70,-170,-30)

draw_rectangle(10,70,-170,50)

Here is the output of the program above.

Cool Python Codes logo design 3

The logo below was designed using Photoshop by Tutorial Graphics.

Cool Python Codes logo

Can this tutorial get more exciting?

Yes, it can.

Let’s write programs to respond to user’s mouse clicks.

onclick() method

This method calls a function whenever the mouse is used to click on a particular coordinate.

It accepts three arguments which are:

  • fun– this is a function with two arguments, to which will be assigned the coordinates(x,y) of the clicked point on the canvas.
  • btn– this argument is assigned to one by default, which means you click the left mouse button to call a function. If you assign it to two, you will have to click both the left and right mouse button simultaneously to call a function.
  • add– True or False. If True, a new binding will be added, otherwise, it will replace a former binding.

I usually use one argument which is the function I want to call when I click my mouse.

Here is a program that draws a circle when you click on the turtle. Save the code snippet as click_to_draw_circle.py

from turtle import Turtle t=Turtle() t.screen.bgcolor("black") t.color("orange") def circle(x,y): t.circle(60) t.onclick(circle)

from turtle import Turtle

t=Turtle()

t.screen.bgcolor("black")

t.color("orange")

 

def circle(x,y):

    t.circle(60)

 

t.onclick(circle)

Note:

The function name “circle” has two arguments, x and y which are the coordinates you will have to click to draw a circle.

ondrag() method

This method is basically used when you what to click on the turtle and move it. It accepts three arguments like the onclick() method.

Here is a program to illustrate the ondrag() method.

The code snippet below is saved as turtle_ondrag.py.  

from turtle import Turtle t=Turtle() t.screen.bgcolor("black") t.color("blue") def goto(x,y): t.goto(x,y) t.ondrag(goto)

from turtle import Turtle

 

t=Turtle()

t.screen.bgcolor("black")

t.color("blue")

 

def goto(x,y):

    t.goto(x,y)

 

t.ondrag(goto)

Here’s what I drew using the program above.

I drew a cup.

onrelease() method

This method is also similar to onclick and ondrag method. To understand what this method does,

I wrote a program to draw a circle when you left click on the turtle and when you remove your hand from the mouse, the circle will disappear.

Here is the code snippet and it is saved as turtle_onrelease.py

from turtle import Turtle t=Turtle() def draw_circle(x,y): t.circle(50) def erase_drawing(x,y): t.clear() t.onclick(draw_circle) t.onrelease(erase_drawing)

from turtle import Turtle

 

t=Turtle()

 

def draw_circle(x,y):

    t.circle(50)

 

def erase_drawing(x,y):

    t.clear()

 

t.onclick(draw_circle)

t.onrelease(erase_drawing)

Note:

You have to leave your hand on the left-hand button of the mouse until the circle is drawn on the screen.

When the circle has been drawn, you can then remove your hand from your mouse. Once you remove your hand from the mouse, the circle disappears.

This circle disappears because of the clear()  method. The clear() method deletes the turtle’s drawing on the screen.

This section is going to be fun as we will control the turtle with the keyboard of our computer.

Before we write some codes, let me explain the following concepts.

  1. onkey()
  2. listen()

onkey()

This method is similar to onclick() method. The only differences is that the onclick() method responds to clicks on the mouse while the onkey() method responds to commands from your computer keyboard.

The onkey() method accepts two arguments which are:

  • fun: this is a function without any argument
  • keyboard command: this is basically any alphabet on your keyboard (e.g n) or any keyboard command key. e.g space, your direction keys(up, down). You have to pass this command as a string

listen()

I will avoid using any technical word because I’m as well bored with them. Basically, without including this method, the turtle won’t obey your commands.

The listen() method is like a cane you use on a child to obey your instruction.

Alright, let’s write some codes.

Project 6:

Write a program to control the turtle to move up, down, left and right using the computer keyboard. The turtle should move constantly to any pixels of your choice.

Include an undo action.

Open a new file editor and save the following code snippet as turtle_keyboard_control.py

from turtle import Turtle t=Turtle() def up(): if not(t.heading() == 90): t.setheading(90) t.fd(50) else: t.fd(50) def down(): if not(t.heading() == 270): t.setheading(270) t.fd(50) else: t.fd(50) def right(): if not (t.heading() == 0): t.setheading(0) t.fd(50) else: t.fd(50) def left(): if not (t.heading() ==180): t.setheading(180) t.fd(50) else: t.fd(50) def undo_button(): t.undo() def keyboard_commands(): t.screen.onkey(up,"Up") t.screen.onkey(down,"Down") t.screen.onkey(right,"Right") t.screen.onkey(left,"Left") t.screen.onkey(undo_button,"End") t.screen.listen() keyboard_commands() t.screen.mainloop()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

from turtle import Turtle

t=Turtle()

 

def up():

    if not(t.heading() == 90):

        t.setheading(90)

        t.fd(50)

    else:

        t.fd(50)

    

def down():

    if not(t.heading() == 270):

        t.setheading(270)

        t.fd(50)

    else:

        t.fd(50)

    

def right():

    if not (t.heading() == 0):

        t.setheading(0)

        t.fd(50)

    else:

        t.fd(50)

    

def left():

    if not (t.heading() ==180):

        t.setheading(180)

        t.fd(50)

    else:

        t.fd(50)

 

def undo_button():

    t.undo()

        

def keyboard_commands():

    t.screen.onkey(up,"Up")

    t.screen.onkey(down,"Down")

    t.screen.onkey(right,"Right")

    t.screen.onkey(left,"Left")

    t.screen.onkey(undo_button,"End")

    t.screen.listen()

 

keyboard_commands()

t.screen.mainloop()

Don’t let the long code snippet to confuse you.

I will quicky explain the program above.

I mentioned early that :

Angle 90 sets the turtle to face the North.

Angle 180 sets the turtle to face the West.

Angle 270 sets the turtle to face the South.

Angle 360 or 0 set turtle to face the East

Alright!!!…

Now the “if”, “ else “ and “not” tells the turtle that if it’s not facing the desired direction, that it should change the direction.

t.heading() returns the  current turtle’s current heading.

t.undo() undo the last action of the turtle.

The key commands are “Up”, “Down”, “Left”, “Right” and “End” which are your direction keys and end key on the keyboard. Note that they all start with capital letters.

The rest of the code snippets are easy to understand.

stamp() method

This method basically pastes the turtle shape on the canvas on the current turtle’s position.

To illustrate this, open a new file editor and save the following code snippet as turtle_stamp.py

 

from turtle import Turtle t=Turtle() t.up() t.setx(-50) t.down() t.hideturtle() for i in range(4): t.fd(50) t.stamp()

from turtle import Turtle

 

t=Turtle()

t.up()

t.setx(-50)

t.down()

t.hideturtle()

 

for i in range(4):

    t.fd(50)

    t.stamp()

Here’s the output of the above code snippet.

Observing the above screenshot, you will see that the turtle shape appeared 4 times. This makes the concept of for loop more practical. For every 50pixels to the east, a turtle shape will appear.

position() method:

This method returns the position of the turtle, both the coordinates of the x and y axis is returned.

xcor() method:

This method returns the x coordinate of the turtle.

ycor() method:

This method returns the y coordinate of the turtle.

One more last thing before I end this tutorial.

How to Change the Title of the Turtle Screen

The default title of the turtle screen is “Python Turtle Graphics”, which can be boring.

It will be fun if your name or your friend’s name is on it. Your friends will know that you’re a Pro programmer.

To change the title of the turtle screen, use the method screen.title(). This method only accepts a string.

To illustrate this method, open a new file editor and save the following code snippet as turtle_screen_title.py

from turtle import Turtle t=Turtle() t.screen.title("Cool Python codes")

from turtle import Turtle

 

t=Turtle()

 

t.screen.title("Cool Python codes")

Here is the output of the program above.

How to change the title of Python turtle.

Here are some amazing drawings I did with Python Turtle including the code snippet.

Try and study the code snippet and do a lot of experiments to come up with new designs.

The below code snippet is saved as beautiful_circles.py

from turtle import Turtle t=Turtle() t.screen.bgcolor("black") colors=["red","yellow","purple"] t.screen.tracer(0,0) for x in range(100): t.circle(x) t.color(colors[x%3]) t.left(60) t.screen.exitonclick() t.screen.mainloop()

from turtle import Turtle

 

t=Turtle()

t.screen.bgcolor("black")

colors=["red","yellow","purple"]

t.screen.tracer(0,0)

 

for x in range(100):

    t.circle(x)

    t.color(colors[x%3])

    t.left(60)

 

t.screen.exitonclick()

t.screen.mainloop()

Here’s the output of the above code snippet.

Beautiful circles with Python Turtle

The below code snippet is saved as beautiful_square.py

from turtle import Turtle t=Turtle() t.screen.bgcolor("black") colors=["blue","purple","red","yellow"] t.screen.tracer(0,0) for x in range(300): t.color(colors[x%4]) t.fd(x) t.left(90) t.screen.exitonclick() t.screen.mainloop()

from turtle import Turtle

 

t=Turtle()

t.screen.bgcolor("black")

colors=["blue","purple","red","yellow"]

t.screen.tracer(0,0)

 

for x in range(300):

    t.color(colors[x%4])

    t.fd(x)

    t.left(90)

 

t.screen.exitonclick()

t.screen.mainloop()

Here’s the output of the code snippet above.

Beautiful Square

The below code snippet is saved as beautiful_spiral.py

from turtle import Turtle t=Turtle() t.screen.bgcolor("black") colors=["blue","purple","red","yellow","orange","brown"] t.screen.tracer(0,0) for x in range(300): t.color(colors[x%6]) t.fd(x) t.left(59) t.screen.exitonclick() t.screen.mainloop()

from turtle import Turtle

 

t=Turtle()

t.screen.bgcolor("black")

colors=["blue","purple","red","yellow","orange","brown"]

t.screen.tracer(0,0)

 

for x in range(300):

    t.color(colors[x%6])

    t.fd(x)

    t.left(59)

 

t.screen.exitonclick()

t.screen.mainloop()

Here’s the output of the above code snippet.

beautiful spiral

You have come to the end of this tutorial.

Please don’t forget to:

Please if you have any questions or contributions, please leave it in the comment section.

Thanks for reading. If you enjoyed this tutorial, hit the share button. It would mean a lot to me and it helps other people to see the tutorial.

It would mean a lot to me and it helps other people to see the tutorial.

ad: Install Python and other important software on any device no matter where you are with a virtual cloud desktop by CloudDesktopOnline.com . Get additional cloud related business software such as SharePoint from Apps4Rent.com .

Related

coolpythoncodes.com

VPython3D Programming for Ordinary Mortals

VPython makes it easy to create navigable 3D displays and animations, even for those with limited programming experience. Because it is based on Python, it also has much to offer for experienced programmers and researchers. Click here to see a variety of examples.

For a quick introduction, see the following YouTube videos, but be aware that for the current VPython 7 version of VPython the name of the module is "vpython", not "visual", and the graphics display is shown in a browser tab rather than in a bare window.

3D Objects

Variable Assignment

Beginning Loops

Loops and Animation

Scale Factors

Debugging Syntax Errors

Lists, Part 1

Lists, Part 2

How to get started using VPython

New to Python and/or VPython? GlowScript VPython is a good place to start:

·         Go to glowscript.org and create an account.   

o   You should see the sentence “You are signed in as <yourusername> and your programs are here." Click on "here”.

o   Click on “Create New Program”.  Name it “box”.  You will see this line:     Glowscript 2.6 VPythonAdd this statement on the next line:     box()

·         Then click on “Run this program”.  You will see a white box on a black background.

o   Use the right button (or CTRL-drag left button) of the mouse to rotate the camera to view the scene from different angles.

o   To zoom in and out use two buttons, or ALT/OPTION-drag, or the mouse scrollwheel. Touch screen:  swipe or two-finger rotate; pinch/extend to zoom.

o   Click on Help to see what graphical objects are available. Additional sources of information are provided below.

Experienced Python / VPython user? Need access to all Python modules? Try VPython 7:

·         Install the Continuum Anaconda (or Enthought Canopy) Python distribution.  We recommend choosing Python 3.5 or later, especially if you already have “Classic” VPython / Python 2.7 installed on your machine.  If you are an expert Python user and want to use Jupyter notebooks, you can install the IPython and Jupyter modules in your current Python installation; see jupyter.org.

 

·         In a Power Shell or Command Prompt (Windows) or Terminal (Mac / Linux) run this command, which will install VPython 7 for Python 2.7, 3.4, 3.5, or 3.6:pip install vpython

      Or if using Anaconda, conda install -c vpython vpython

 

     There will be frequent updates to this module. You can get the latest version this way: pip install vpython --upgrade

      Or if using Anaconda, conda update -c vpython vpython

You can run from the Spyder editor/launcher with Python 3.5 (3.5.3 or greater) or 3.6, but the newest Spyder 3.2 does not support the use of vpython. The Spyder developers are aware of the issue and have offered to address the problem in a later version. Here are the details about the issue, with information on workarounds. A simple option is to install the older Spyder 3.1.4 by executing this in a terminal:

     conda install spyder=3.1.4

 

      You can start Spyder by clicking the Spyder icon that is installed with Anaconda, or you can start Spyder from a command prompt by typing "spyder". In Spyder you must go to Run > Configure and specify "Execute in a new dedicated Python console".

If you read or write data files, and you want by default for them to go into the same folder as your Python program, go to Tools > Preferences > Run and choose the "Default working directory" to be "the script directory". You may also wish in Tools > Preferences > Global working directory to specify what directory Spyder first looks in for programs.

 

      Some Mac users have reported that running from Spyder doesn't work. The following workaround, making and invoking a new environment, does work:

      conda create -n vpclean -c vpython vpython python=3      source activate vpclean

 

      To use a Jupyter notebook (Python 2.7, 3.4, 3.5, 3.6): There are two ways to start a Jupyter notebook. In a terminal, execute "jupyter notebook". Or (depending on what operating system you're using), doubleclick the icon "Jupyter Notebook" that is shown as one of the Anaconda-related tools. At the right there is a pulldown menu to create a New notebook, and if you choose "VPython" you will get the following import, which if using Python 3 is unnecessary (you can change the notebook type through the menu Kernel > Change kernel):from __future__ import division, print_function

If you have a recent release of the Mac operating system, to start the Jupyter notebook you may need to execute this:jupyter notebook --browser=Chrome

Either with or without a Jupyter notebook, "from vpython import *" also imports all math functions, clock(), random(), and arange(). This simplifies moving programs between GlowScript VPython and VPython 7.

 

·         Write a test program: This short program will display a white box on a black background:from vpython import *box()

Running a VPython program in a Jupyter notebook: Click in the first cell (containing the vpython import statement), then click the run icon, the one that is a rightward-facing triangle touching a vertical line. Currently, to re-run a VPython program you need to click the circular arrow icon to "restart the kernel" and then click the red-highlighted button, then click in the first cell, then click the run icon.

Some users find it convenient to iinclude in the first cell just these statements:from vpython import*scene = canvas()

Then put the rest of the program in later cells. The result is that the 3D display will be shown just under the first cell instead of at the end of the last cell. It also ensures that the vpython module has been fully initialized before continuing. Moreover, you can re-run the program more easily.

·         Rotating and zooming the camera is the same as for GlowScript VPython; see above.

 

·         Documentation: See the GlowScript VPython Help for documentation. The only GlowScript feature not yet implemented is keyboard interactions, pending an understanding of the relationship to keyboard inputs being processed by the Jupyter notebook.

·         Demo programs: There is a suite of demo programs for Jupyter notebooks (zip file) and for use without a Jupyter notebook (zip file).

·         Run demo programs remotely: There is a Binder package of some demo programs, which lets you run Jupyter VPython programs even on computers or mobile devices that do not have Python installed. Here is an explanation of the Binder mechanism. Because the Binder servers are shared among a large number of people, performance can vary a great deal from day to day and from hour to hour.

·         Those who DO have Classic VPython installed and want to keep it should instead create a new environment in which to try the new VPython: "conda create -c vpython -n vpython_jup_env vpython python". After creating the new environment you will need to activate it to try out the new VPython.

How GlowScript VPython and VPython 7 differ from Classic VPython 6

·         Vectors must be represented as vector(x,y,z) or vec(x,y,z), not as (x,y,z).

·         The name display has been changed to canvas (for technical reasons).

·         The name gdisplay has been changed to graph.

·         curve objects and points objects have a new set of methods.

In the VPython Help at glowscript.org is a conversion program to convert from Classic to GlowScript syntax; It does an imperfect but useful job of dealing with the main differences.

Plans for future developments

·         Here is a description of the plan for future development of VPython.

 

The older Classic VPython 6

·         Here is documentation on the older VPython 6, which is still available but no longer supported.

Additional sources of information

Documentation: Overview, tutorials, and detailed documentation

User forum. (Until Feb. 2013, there was a mailing list whose archives may be found at https://sourceforge.net/mailarchive/forum.php?forum_name=visualpython-users. Please do not write to that list; instead post on the User forum.)

VPython on Stack Overflow: A third party question and answer site for users to share about VPython. We do encourage people to post to the User forum, as there is a larger number of knowledgeable users there.

Python web site: The Python programming language, on which VPython is based

Using tools at trinket.io it is easy to add both editing and execution of GlowScript VPython to your own web pages. Rhett Allain in his physics blog for Wired magazine has shown examples of this.

Jay Wang has posted a gallery of photos and movies of a variety of interesting VPython programs.

A podcast interview with Ruth Chabay and Bruce Sherwood about the history of VPython.

A blog article on A time line for VPython development by Bruce Sherwood.

A poster on the relationship between GlowScript VPython and Jupyter VPython

A technical presentation on the relationship between GlowScript VPython and VPython 7.

Matter & Interactions: Introductory physics using VPython

Some advanced-level textbooks in which VPython is used:

Computational Physics:Problem Solving with Python, Rubin H. Landau, Manuel J. Páez, Cristian Bordeianu (2015)

Computational Physics with Python Mark Newman (2012)

An Introduction to Statistical Mechanics and Thermodynamics Robert H. Swendsen (2012)

Equilibrium Statistical Physics With Computer Simulations in Python Leonard M. Sander (2013)

Soil Physics with Python: Transport in the Soil-Plant-Atmosphere SystemMarco Bittelli, Gaylon S. Campbell, and Fausto Tomei (2015)

Computational Modeling and Visualization of Physical Systems with Python Jay Wang (2016)

Write to if you don't find what you need, or to tell us how you are using VPython.

Romanian translation of this page by Jessica Parker

Estonian translation of this page by Sonja Kulmala

Indonesian translation of this page by Jordan Silaen

Russian translation of this page by Akhmetov Rauan

German translation of this page by André Lungstraß

Spanish translation of this page

Chinese tranlation of this page by 殷文锋

French translation of this page by Eddie Vigor

Polish translation by Milana Sharapovan of an earlier version of this page

Ukrainian translation of this page

Dutch translation of this page by Kim Schievink

Development of VPython was supported in part by the National Science Foundation

www.vpython.org

Python Nedir? | Python Türkiye

Python Dili Nedir?

Python, Guido Van rossum adlı hollandalı bir programcı tarafından yazılmış bir programlama dilidir. Geliştirilmesine 1990 yılında başlayan Python; C ve C++ gibi programlama dillerine kıyaslarsak şöyle sonuçlar elde edebiliriz.

  • Daha kolay öğrenilir.
  • Program geliştirme sürecini kısaltır yani hızlı yazılır.
  • Yukaridaki verilen programlama dillerine aksine ayrı bir derleyici ihtiyaci duymaz.
  • Hem daha okunaklı, hem daha temiz kodsal söz dizimine sahiptir.

Python’un bu ve buna benzer özelliklerinden dolayı, dünya çapında ün sahibi büyük kuruluşlar ( Google, Yahoo! ve Dropbox gibi) bünyelerinde herzaman Python programcılarına ihtiyaç duyuyor.

Mesela pek çok büyük şirketin Python bilen programcılara iş olanağı sunduğu, Python’un baş geliştiricisi Guido Van Rossum‘un 2005 ile 2012 yılları arasında Google’de çaliştığını, 2012 yılının sonlarında doğru ise Dropbox şirketine geçtiğini söylersek, bu programlama dilinin önemi ve geçerliliğini herhalde daha belirgin bir şekilde ortaya çıkaracaktır.

Bu arada Python dilinin, her nekadar Python Programlama dili ile ilgili çoğu görsel malzemeninn üzerine yılan resmi olarak görsek de, Python kelimesi aslında çoğu kişinin zannetiği aksine Piton anlamına gelmiyor. Python programlama dili ismini, Guido Van Rossum’un çok sevdiği Monty Python adlı altı kişilik bir ingiliz komedi grubun Monty Python’s Flying Circus adlı gösterisinden gelmektedir.

Diğer programlama dilleri gibi tahmin edebilceğiniz gibi Python (C,C++,Perl,Ruby ve benzeri gibi) bir programlama dilidir. Tıpkı öteki yazılım dilleri gibi, önünüzde duran kara kutuya yani bilgisayara hükmetmenizi yani yönetmenizi sağlar.

Python dilinin öne çıkaran unsurlardan biri ise bilimsel yöntemlerde kullanılması ve çok hızlı işlem yapmasıdır. Bir başka yönden incelediğimizde Python ile Arduino,Raspi ve benzeri programlamanabilir elektronik kartlar ile harika işler çıkardığını biliyoruz.

Paul McWhorter tarafından Python dili üzerinden arduino ile cisim algılama sistemi örneği yaptı. Gerçekten bu video izlediğinizde python’un gücünü biraz daha görebilcekseniz.

Python dilinin yeni nesil, diğer dillerin hatalarını görrek gelişirilmeside büyük bir avantaj olduğu ortaya koymaktadır. Python dilinin bir seçilme sebebi ise şöyle örnekle anlatabiliriz. Örneğin Php dilinin bilen bir kişi Sunucu taraflı php yazılım yapabilir. Fakat Python bilen biri Masa üstü uygulaması ( her işletim sisteminde çalişan ) , Web uygulaması ( Her ortamda çalişan ve açık kaynaklı ) , Mobil uygulama ( Kivy ile ) gibi bütün ortamlara hükmedebiliyorsunuz.

Pythonun gücünü şöyle bi örneklede kanıtlayabiliriz. Bildiğiniz üzere yukarada bahsettiğim gibi Python dilinin Google tarafından kullanıldığını biliyoruz. Peki nerede kullaniyor hiç düşündünüz mü ?

Google’nin arama motoruna örneğin “Python” yazdığımda belki 1 milyon kaynak önümüze dökücektir. Bu işlemi mili saniyece sürece yanıt vermesini sağlayan pythondur.

 

Python, nesne yönelimi, yorumlamalı, birimsel ve etikileşimli yüksek seviyeli bir programlama dilidir.

Python bilim ve teknoloji bilgi sanayesinde önemli rol oynamaktadır. Yazılım teknolojileri özgür yazılım platformu her dalda ayrı compiler ile çalışan bu dil uluslar arası Askeri savunma ve hacking network sistemleri üzerinde uluslar arası bir öneme sahip programlama dilidir.

Özetlemek gerekirse ;

  • Yüksek seviyeli bir programlama dili.
  • Bilim ve teknoloji bilgi sanayesinde önemli rolu var.
  • Uluslar arası alanda etkili.
  • Askeri savunma alanda etkili.
  • Hacking network sistemleri üzerinde etkili.

Bir dilden beklenenden daha fazlasını karşıladığını sizde görüyorsunuz.

1991 Yılında çıktığını görüyoruz yani köklü bir dil olduğunu kanitliyor.

Geliştirici durumu bir Yazılım vakfı tarafından ele alınmış aslında güzel bir durum arkadaşlar tamamen ücretsiz bir platform olduğunu kanıtlıyor.

Tıp sisteminde güçlü ve dinamik olduğunu görüyoruz, gerçekten mutlu oluyor insan 🙂

İTÜ fizik bölümünden Berkin Malkoç, “Temel Bilimler ve Mühendislik Eğitiminde Programlama Dili Olarak Python” başlıklı makalesinde etraflı bir inceleme sunuyor. Kısa başlıklarla özetlersek:

  • Açık kaynaklı. Kullanmakta özgürsünüz, bir şirkete bağlı olmak zorunda değilsiniz. Üstelik ücretsiz.
  • Yapısı sade. Okuması ve yazması çok kolay. Çok hızlı öğrenilebiliyor.
  • “Dinamik” dil. Yorumlayıcıyla çalışıyor. Çok karmaşık işlemleri basit komutlarla yaptırabilirsiniz.
  • Etkileşimli. Yorumlayıcı penceresinde ardarda komutlar verip işlemler yapabilirsiniz.
  • Aklınıza gelen bir fikri çabucak bir program oluşturarak deneyebilirsiniz.
  • OOP’yi destekler ama mecbur tutmaz. Basit işler için class tanımlamak zorunda değilsiniz.
  • Genel kullanım alanı geniş ve yazılım sanayiinde çok seviliyor. Bu sayede sürekli geliştiriliyor. Öğretici kaynak bulmak kolay.
  • Bilimsel araştırmalarda çok yaygın olarak kullanılıyor. Çeşitli bilim dallarında kullanılmak üzere özel hazırlanmış kütüphaneleri var. Bu kütüphaneler kendini bu işe adamış profesyonel yazılım ekipleri tarafından hazırlanıyor, yoğun şekilde test ediliyor, ve yine açık kaynaklı.

Python tamamen harika değil. Dinamik ve yorumlanan bir dil olması, ister istemez yavaş çalışmasını gerektiriyor. Yoğun hesaplama gerektiren işleri C veya Fortran’la yazılmış programlara yaptırmak daha doğru olur.

dolasıyla şöyle , Python çeşitli ara çözümler de sunuyor. Sözgelişi, C ile yazılmış programlar Python koduna entegre edilebilir, epeyce hızlı Python programları hazırlanabilir. Meselâ bilimsel hesaplama için geliştirilen SciPy kütüphanesi böyle hazırlanmış.

Dahası, birçok durumda, yavaş çalışan bir Python programı bile size zaman kazandırabilir. Meselâ C ile bir hafta uğraşarak yazabileceğiniz bir programı Python ile bir günde yazmanız mümkün olabilir.  Neden Python cevabı verilmiş oldu sanırım.

Ek olarak Neden Python adına Youtube üzerinde harika bi grup videosu çekildi. Python üzerinde uzman kişiler arasında 2 saat konuşma yapıldı. Videoyu sonuna kadar izlemenizi tavsiye ediyorum :

Python İle Yazılmış Uygulamalar

  • Emesene
  • Ubuntu Yazılım Merkezi
  • Gwibber
  • Civilization IV ( Oyuın)
  • Battlefield 2 (Oyun)
  • Reddit başlangıçta lisp ile, daha sonra baştan Python ile yazılmış. Python ile yazılım geliştirme süreci çok hızlı ve web uygulaması geliştirme çok yaygın olduğu için tercih etmişler. İsteyenler reddit kaynak kodlarını okuyabilir.
  • Django Siteleri sayı bakımından oldukça fazla. djangosites adresinde kayıtlı 4500 adet websitesi var.
  • Portage Gentoo Linux’un kullandığı paket yönetim sistemi. Python ve kabuk programlarıyla yazılmış.
  • Sage açık kaynaklı ve Python tabanlı bir matematik seti. Sage, 100’den fazla açık kaynak program ve kütüphaneyi bir araya getirmiş. Matlab, Stata, Mathematica gibi programlara alternatif sunuyor.
  • GNU Mailman e-posta listesi yönetim aracı. Bildiğim kadarıyla birçok açık kaynak yazılımın mail grupları gnu mailman ile yönetiliyor.
  • Planet çok sayıda rdf, rss ve atom beslemesini toplayıp, tek bir belge içinde birleştiren ve çeşitli formatlarda çıktı verebilen yazılım. Dive into python kitabından tanıdığımız Mark Pilgrim’in yazdığı feed parser kütüphanesini kullanıyor.
  • Trac bir yazılım geliştirme yönetim sistemi. Subversion ve git ile entegre, wiki ve sorun bildirme özellikleri bulunuyor.
  • GNU Bazaar ve Mercurial kısmen Python ve kısmen C ile geliştirilmiş iki versiyon kontrol sistemi.
  • Calibre açık kaynak e-book yönetimi aracı. E-book’larını bir server oluşturarak paylaşma imkanı da sağlıyor.
  • Yum RPM sistemleri için otomatik paket yükleyici ve kaldırıcısı. Bağımlılıkları denetler ve bir paketin yüklenmesi için neler olması gerektiğini anlar.

 

Bunlar Python kullanan uygulamalardan bazılarıydı. Bunların dışında, Python’u başka programların içine gömerek, o programın Python kodlarını kullanmasını sağlamak mümkün. Python’u bu şekilde kullanan uygulamalardan örnek vermek gerekirse:

  • Maya 3 boyutlu animasyon, modelleme ve simülasyon yazılımı. Birçok oyun ve animasyon film tarafından kullanılıyor. Maya ile Python kodları kullanmanın temelleri videosunu izleyebilirsiniz.
  • Blender Maya’nın açık kaynak alternatifi. Aynı şekilde, Blender içinde de Python kodları kullanmak mümkün.
  • Inkscape vektörel grafik tasarım programı. İnkscape’in python kütüphanelerini import edip Python ile svg oluşturabiliyorsunuz. Python scripti ile oluşturulmuş bir svg animasyonu buldum Youtube’da.

Python ile yapılabilecekler bunlarla sınırlı değil; Python ile yapılan oyunlar, yapay zeka kütüphaneleri, çeşitli web, grafik, gui framework’leri, bilimsel uygulamalar da var. Google, Youtube ve NASA’nın da çeşitli işleri için Python kullandığı yaygın olarak söyleniyor, ancak bunu teyit edemedim.

Kaynak : http://ysar.net/python/python-ile-yazilmis-programlar.html

Yazılımcılara Tavsiye

Programlama bir sanattır. bir Programlama diline ait bilgiler program yazıcısının beceri ve düşüncesi ile birleşince orta program çıkıcaktır. Bu bakış açısı ile baktığımızda, her başlık altında öğreneceğiniz bilgiler ayrı ayrı değerlendirdiğimizde bir işe yaramiyacaktır. Bunları ancak birlikte kullandığımızda ortaya ürün cıkacaktır. Herkes programlama dilinin temel öğelerini öğrenebilir ancak asıl iş bu parçaları bir araya getirip ustaca kullanmaktadır. Nasıl ki bir sanatçı edindiği tecrübeleri yaratıcı fikirleri birleştirince sanat ve eseri ortaya cıkarsa, bir programcı da öğrendiklerini yaratıcı fikirleri ile yoğurunca program ortaya çıkar.  Bu neden Python öğrenmeye karar verdiyseniz Python temel programlamayı sağlamlaştırmanız gerekiyor. Öğrendiğiniz örnekleri farklı yorumlayarak değişik örnekler cıkarmaya çalışın.

 

 

Python Toplulukları

Python öğrenmeye karar verdiniz, ama toplulukları bilmiyorsunuz. Mevcut olan toplulukları sizler için sıralayacağım.

  • Python.TC : Python dili için blog yazıları yayınlayan bir yapıdır.
  • Pyistanbul.org : İstanbul’daki Python programcıları topluluğudur. Eğer Python ilginizi çekiyorsa siz de bu topluluğa katılabilirsiniz.
  • Facebook Python Türkiye Grubu : Pyistanbul tarafından kurulan, facebook grubudur.
  • İstihza : Python dili için pdf kitapları bulunan aynı zamanda python forumu bulunan bir sistemdir.

Belki anlatabilcek daha çok şey var ama , inşallah ilerleyen makalerde eksiklere değineceğiz, sizlere yararlı olması acısından teknik bilgiler vermeye çalıştık. Yararlı olması dileğiyle , sağlıcakla kalınız…

www.python.tc

Python Listenin Elemalarını Çıkartmak | Python Türkiye

Python Listenin Elemalarını Çıkartmak

Merhaba arkadaşlar, liste yapısının özelliklerinden ikinci konumuza geçik burada 2 adet özellikden bahsedicem ikisininde temel amacı listeden eleman çıkarmaktadır. Daha önceki örneklerde Fabrikaya işçi kayit eden bir program yapmıştık. Şimdi mantıken eklediğimiz işçileri bazen çıkarma durumu olacak. İşte tam burada bu çıkarma fonksiyonlarını kullaniyoruz.

Python Listenin Son elemanını Çıkartmak : POP()

Bir listenin en sondaki elemanını çıkartmak için pop() özelliğini kullanılır. Konuyu daha iyi anlamak adına örnekler üzerinden gidelim.

meyveler = ['Elma','Armut','Karpuz','Kavun','Çilek'] print(meyveler.pop(),'Silindi') print(meyveler)

meyveler = ['Elma','Armut','Karpuz','Kavun','Çilek']

print(meyveler.pop(),'Silindi')

print(meyveler)

Yukarıda bir liste oluşturduk. Pop fonksiyonu ile sildiğimiz elemanı ekrana çağırdık ve listenin son halini ekrana yazdırdık. Bakalım nasıl bir çıktı veriyormuş.

Çilek Silindi ['Elma', 'Armut', 'Karpuz', 'Kavun']

Çilek Silindi

['Elma', 'Armut', 'Karpuz', 'Kavun']

Aslında Pop fonksiyonu parametresiz kullanımında, son elemanı siler fakat parametre aldığında ise istediğimiz elemanı silme imkanı sağlıyor. Bu listede Sıfırncı elemanı yani ‘elma’ verisini silelim.

meyveler = ['Elma','Armut','Karpuz','Kavun','Çilek'] print(meyveler.pop(0),'Silindi') print(meyveler)

meyveler = ['Elma','Armut','Karpuz','Kavun','Çilek']

print(meyveler.pop(0),'Silindi')

print(meyveler)

ÇIKTI :

Elma Silindi ['Armut', 'Karpuz', 'Kavun', 'Çilek']

Elma Silindi

['Armut', 'Karpuz', 'Kavun', 'Çilek']

Şeklinde çıktı vericektir.

Kısaca şöyle özetleyebiliriz.

Eğer parametre alınmassa POP() şeklinde kullanılırsa son elemanı siler.

Liste.Pop()

Eğer parametre alırsa, istediğimiz indeksteki elemanı silebiliriz.

Liste.Pop(indeks)

Python Listeden Eleman Çıkartmak : Remove()

Listenin son elemanı yerine veya indeks numarasına göre silmek yerine remove() fonksiyonu ile çıkarmak istediğimiz yani silmek istediğimiz elemanı, ismini belirterek silebiliriz. Konuyu daha iyi anlamak adına örnekler üzerinden gidelim.

Genel Yapısı şu şekildedir ;

Liste.Remove(‘silmek istediğin eleman‘)

meyveler = ['Elma','Armut','Karpuz','Kavun','Çilek'] meyveler.remove('Karpuz')

meyveler = ['Elma','Armut','Karpuz','Kavun','Çilek']

meyveler.remove('Karpuz')

Yukarıda bir dizi oluşturduk, remove() fonksiyonu sildik fakat silindiğini anlamak içine ekrana yazdırmadık. Yazdıralım sonucu görelim.

meyveler = ['Elma','Armut','Karpuz','Kavun','Çilek'] meyveler.remove('Karpuz') print(meyveler)

meyveler = ['Elma','Armut','Karpuz','Kavun','Çilek']

meyveler.remove('Karpuz')

print(meyveler)

ÇIKTI :

['Elma', 'Armut', 'Kavun', 'Çilek']

['Elma', 'Armut', 'Kavun', 'Çilek']

Görüldüğü üzere ‘karpuz’ liste içerisinde olmayacaktır. Yanlız karpuz diye diye canımız cekmedi inşallah 😀

Dikkat Edilecek Durumlar

Remove() özelliği pop() özelliği gibi çıkartılan elemanları geri döndüremessiniz. Aynı zamandada Listede olan elemanı çıkartmaya çalırşanız ise hata ile karşılaşırsınız.

Bir diğer önemli nokta ise, mesala ‘karpuz’ elemanını çıkarıcaz fakat dizide iki adet karpuz elemanı mevcut, bu durumda sıralama göre ilk gelen elemanı siler.

Yukarıda bahsettiğimiz unsurlara örnek yaparak pekiştirelim.

Aynı elemanı tekrar çıkarmaya çalışırsak şöyle olacaktır ;

meyveler = ['Elma','Armut','Karpuz','Kavun','Çilek'] meyveler.remove('Karpuz') meyveler.remove('Karpuz') print(meyveler)

meyveler = ['Elma','Armut','Karpuz','Kavun','Çilek']

meyveler.remove('Karpuz')

meyveler.remove('Karpuz')

print(meyveler)

ÇIKTI :

meyveler.remove('Karpuz') ValueError: list.remove(x): x not in list

    meyveler.remove('Karpuz')

ValueError: list.remove(x): x not in list

‘karpuz’ ifadesi liste içinde yok, ne yapiyorsun dostum! diyor 🙂

Diğer durum, ise ‘karpuz’ ifadesinden iki tane olursa nasıl silebilirizdi , örnek üzerinden gidelim :

meyveler = ['Karpuz','Karpuz']

meyveler = ['Karpuz','Karpuz']

Şeklinde bir dizi oluşturalım, fakat ben burada silme işlemi yaparsam sadece bir eleman gidecek. Burada count() fonksiyonu ile kaç adet var öğrenip, duruma göre önlem alabiliyoruz.

Python Eleman Sayısını Öğrenme – Count()

meyveler = ['Karpuz','Karpuz'] a = meyveler.count('Karpuz') print(a)

meyveler = ['Karpuz','Karpuz']

a = meyveler.count('Karpuz')

print(a)

Çıktı :

Dolasıyla, Karpuz ifadesinden kaç tane var öğrenebilirsek döngü kurarak hepsini silebiliriz :

meyveler = ['Karpuz','Karpuz','Karpuz','Karpuz','Karpuz','Elma'] for oku in [0,1,2,3,4]: # meyveler içinden oku print(oku,'. Eleman Silindi!') # okuduğunu tek tek yaz meyveler.remove('Karpuz') print(meyveler)

meyveler = ['Karpuz','Karpuz','Karpuz','Karpuz','Karpuz','Elma']

for oku in [0,1,2,3,4]: # meyveler içinden oku

    print(oku,'. Eleman Silindi!') # okuduğunu tek tek yaz

    meyveler.remove('Karpuz')

 

print(meyveler)

Yukarıdaki yapıyı incelediğimiz zaman , şöyle bir çıktı alacağız :

0 . Eleman Silindi! 1 . Eleman Silindi! 2 . Eleman Silindi! 3 . Eleman Silindi! 4 . Eleman Silindi! ['Elma']

0 . Eleman Silindi!

1 . Eleman Silindi!

2 . Eleman Silindi!

3 . Eleman Silindi!

4 . Eleman Silindi!

['Elma']

Ana kodları ve çıktıyı gördüğümüze göre, çalışma mantığını açıklayabiliriz :

  • “meyveler” adlı dizimizi oluşturduk.
  • for döngüsünde

[0,1,2,3,4] şeklinde olan yapıda 0'dan 4'e döngü işlemi olacağını belirttik. Yani 5 kere kod bloku çalişiçaktır.

[0,1,2,3,4] şeklinde olan yapıda 0'dan 4'e döngü işlemi olacağını belirttik. Yani 5 kere kod bloku çalişiçaktır.

  • meyveler.remove(‘Karpuz’) diyerek 5 kere silme işlemi yaptığımızda sadece Elma elemanı kalacaktır.çünkü Karpuz’dan dört tane 5 tane olduğu için 0-4 arası sayma işlemi yapıldığından karpuzdan eser kalmadı 🙂

 

 

www.python.tc

Learn Python the Hard Way

This document serves as a collection of reasons why beginners should avoid Python 3 as of November 22nd, 2016. I give two sets of reasons as I see them now. One for total beginners, and another for people who are more knowledgeable about programming. The first section attempts to explain the case against starting with Python 3 in non-technical terms so a beginner can make up their own mind without being influenced by propaganda or social pressure. The second section then explains the reasons in a series of direct challenges to the Python project of problems that need to be fixed before a beginner (and probably most programmers) can use Python 3 effectively.

I cannot teach Python 3 to total beginners because I don't want them to think they "suck at programming" when really it's Python 3's fault. That's simply not fair to them, so I have to teach Python 2 so they have the best chance at learning to code.

Before getting into the main technical reasons I would like to discuss the one most important social reason for why you should not use Python 3 as a beginner:

There is a high probability that Python 3 is such a failure it will kill Python.

Python 3's adoption is really only at about 30% whenever there is an attempt to measure it. Nobody is all that interested in finding out what the real complete adoption is, despite there being fairly simple ways to gather metrics on the adoption. In my honest opinion the language is dead and will not advance far simply because of the technical reasons I list below. These reasons are simple usability problems that can be fixed easily, but the Python project has adopted an arrogant stance that these defects are in fact "features" that are good for you. This is a death sentence for the language, and if you're planning on using Python 3 in the future you will most likely be in trouble.

It's as simple as that. If you learn Python 2, then you can still work with all the legacy Python 2 code in existence until Python dies or you (hopefully) move on. But if you learn Python 3 then your future is very uncertain. You could really be learning a dead language and end up having to learn Python 2 anyway.

Also, it's been over a decade (it's been in development for a really long ass time, even though the release was 2008), maybe even multiple decades, and Python 3 still isn't above about 30% in adoption. Even among the sciences where Python 3 is touted as a "success" it's still only around 25-30% adoption. After that long it's time to admit defeat and come up with a new plan.

There are more reasons beyond just the uncertain future of Python 3 even decades later (released 2008, worked on for way longer). I'll attempt to explain the more technical reasons in a way a non-programmer can understand using analogies, but if the analogies annoy you then you can also read the more technical explanations below.

Not In Your Best Interests

The Python project's efforts to convince you to start with Python 3 are not in your best interest, but, rather, are only in the best interests of the Python project.

This should ultimately be the only reason you need to not start with Python 3. Ask yourself, why are they so keen on having you use a language that has only about 30% adoption, is constantly changing, and full of issues? The reason is getting beginners hooked on Python 3 means more adoption, which benefits Python 3. They don't care that you'll have problems, struggle too much, and potentially fail because of technical limitations in Python 3. They only care that you, a beginner, will amount to one more user. One more true believer.

I want you to just get started programming and that is all. I don't care what language you use, which is why I have a free book on Python and on Ruby. The language doesn't matter to me at all, and I'm not going to push a broken language on you. The Python project, however, has no problem pushing a broken language on you so that means you should avoid it until they fix it. Some people go so far as to ban my book because it does not support Python 3, even though my book is the most effective method for learning to code. The second someone starts banning books you know they don't care about anything but their own agendas.

Ultimately though, if Python 3 were good they wouldn't need to do any convincing to get you to use it. It would just naturally work for you and you wouldn't have any problems. Instead, there are serious issues with Python 3 for beginners, and rather than fix those issues the Python project uses propaganda, social pressure, and marketing to convince you to use it. In the world of technology using marketing and propaganda is immediately a sign that the technology is defective in some obvious way.

This use of social pressure and propaganda to convince you to use Python 3 despite its problems, in an attempt to benefit the Python project, is morally unconscionable to me.

Poor Design Decisions Prevent Adoption

The Python project decided to make it impossible to run legacy Python 2 code under Python 3. They even go so far as to claim this is "impossible" when basic computer science says this is very possible and done all the time. Given they controlled both language implementations and purposefully decided to prevent Python 3 from running legacy code, I have to conclude that Python 3 is defective on purpose. The end result of this defect is that most people will not bother switching to Python 3 as rewriting Python 2 code is the same switching costs as just using a totally different language completely.

This means you are working with a purposefully broken platform when you use Python 3, and I personally can't condone teaching people to use something that is fundamentally broken.

Difficult To Use Strings

The strings in Python 3 are very difficult to use for beginners. In an attempt to make their strings more "international" they turned them into difficult to use types with poor error messages. Every time you attempt to deal with characters in your programs you'll have to understand the difference between byte sequences and Unicode strings. Don't know what that is? Exactly. The Python project took a language that is very forgiving to beginners and mostly "just works" and implemented strings that require you to constantly know what type of string they are. Worst of all, when you get an error with strings (which is very often) you get an error message that doesn't tell you what variable names you need to fix.

In addition to that you will have 3 different formatting options in Python 3.6. That means you'll have to learn to read and use multiple ways to format strings that are all very different. Not even I, an experienced professional programmer, can easily figure out these new formatting systems or keep up with their changing features.

Throw into that a proposal for yet another string type and you have a nightmare for anyone who's starting out in programming. The reason why I loved Python for beginners is it was easy to use. A total beginner could easily start making useful code right away. The Python 3 project has ruined that in their failed attempt to internationalize Python.

When you start out programming the first thing you work with is strings, and python made them far too difficult to use for even an experienced programmer like me to use. I mean, if I struggle to use Python's strings then you don't have a chance.

Core Libraries Not Updated

Many of the core libraries included with Python 3 have been rewritten to use Python 3, but have not been updated to use its features. How could they given Python 3's constant changing status and new features? In my own testing I've found that when a library could detect Unicode it fails to do so and returns raw byte arrays. What that means is you'll use a library, get what you think is a text string, and then have your code explode with a weird error message that has no variable names in it. This then is randomly distributed, with some libraries figuring out the Unicode status of data and others failing, and even some that fail or succeed within the same library.

Until there is a standard for what every library should return you cannot rely on Python 3's libraries to properly give you characters encoded. The solution is to create a "string" type that magically knows how to be Unicode or raw bytes, but the Python community is against anything they consider "magic" so they'd rather beat you over the head with their bad design and tell you it's a nice massage.

Obviously you're then going to show this document to your seemingly knowledgeable friends, or maybe even big high profile people within the Python project. I have written this section for them so they can see, using code samples, exactly why Python 3 sucks for you. You may not understand this currently, but your friend will and hopefully it will make them go away so you can get back to just learning to code.

Before we begin, remember that I have already converted a good portion of Learn Python The Hard Way to Python 3 so any claims that I will not support it are unfounded. I will support it, when it works for beginners. Until then, it's a violation of my ethics to force beginners to use something that is not easy for them to use.

The Python 3 VM Is Poorly Designed

The choice to not have Python 3 run legacy code will be the main reason it does not get adopted. Here's the breakdown of my reasoning:

  • Python 3 uses a Virtual Machine (VM) just like Python 2 did.
  • The original design of Python 3 could have also run Python 2 in this same VM. They controlled both languages, and could make it work. They chose not to do this, and instead tell you to manually translate.
  • F#/C# and JRuby/Java are good examples of doing this. The former, when you have control over both languages. The latter, when you don't.
  • Successive versions of Java are another example of doing this, and may be closer to Python 2/3 integration.
  • Choosing not to support both Python 2 and Python 3 in the same VM makes the transition cost off Python 2 much higher than it needs to be. Rather than support a smooth transition, the Python project instead asks you to manually convert code instead of simply supporting both languages.
  • When asked why they don't run both, members of the Python project have actually told me this is impossible. This is a lie. It is not impossible, and in fact would have been the better design to help with migration.
  • This poor design choice of Python 3 prevents easy migration, reduces adoption, and forces you to do their work for them. The difficulty in having to manually translate code simply because Python 3 refuses to support Python 2 by design means that there is a high probability it will not succeed.
  • When I say "it will not succeed" people think, "compared to Python 2", when I really mean, compared to other languages.
  • To me, I find it unconscionable to use other people's free labor to cover for a poor design decision. I doubt they'll fix this, but it's my evidence that says Python 3 will not see the necessary adoption to be successful.

Note

In the previous version I trolled people by pointing out that, if what the Python project says is true and it would have been "impossible" to support Python 2, then they broke it and Python 3 is not turing complete. Obviously Python 3 is turing complete, but Python project members frequently claim something this basic is "impossible" soooooooooooo alright. I even had a note after the gag saying it was a gag, but everyone is too stupid to read that note even when they do elaborate responses to my writing. Even more telling was when people said this was stupid, I'd feign ignorance further and ask, "Wait, so why doesn't Python 3 support Python 2 then?" This then sent them down a logic loop death spiral of simultaneously trying to defend the design decision and also state that Python 3 is fully capable. It was pretty funny to watch, but after a while I guess I have to straighten this out and simplify it so here you go.

Purposefully Crippled 2to3 Translator

I originally said this was 100% possible but honestly I should have said the 2to3 translator should have just not been necessary. I also think I was wrong in saying it was 100% possible. I think a better wording is, "If they designed Python 2 and 3 correctly the 2to3 translator would work perfectly."

I also feel this section just doesn't help explain why Python 3 isn't usable for beginners. The high switching cost of having to manually rewrite code is a valid concern. The lack of support for running Python 2 code is a valid friction on switching. Having a broken 2to3 translator though is just a symptom of the problem, not a cause.

This version will have this not but eventually I'll strip this down to the essentials and remove this pointless point I tried to make.

Statically Typed Strings

Python is a dynamically typed language. That means I do not have to know the type of variable to use it. As long as it behaves like another type, I am free to effectively pretend it is that other type. Whether that's a good computer science decision or not is pointless. Dynamic typing is what makes Python easy to use and one of the reasons I advocate it for beginners.

In Python 3, I cannot reliably use these function:

def addstring(a, b): return a + b def catstring(a, b): return "{}{}".format(a, b)

If we have a string and a bytes type then when we call the first function we get an error, and the second we get a repr formatted byte string. I actually prefer the first response as it means I'm not randomly sprinkling b'blah' all over the place without knowing it.

Here's me trying to use these two functions in Python 3.5:

Python 3.5.1 (default, Sep 16 2016, 13:36:12) [GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.29)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> def catstring(a, b): ... return "{} {}".format(a,b) ... >>> x = bytes("hello", 'utf-8') >>> y = "hello" >>> catstring(x, y) "b'hello' hello" >>> >>> def addstring(a, b): ... return a + b ... >>> addstring(x, y) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in addstring TypeError: can't concat bytes to str >>> ^D

By comparison here's the Python 2 version:

Python 2.7.11 (default, May 25 2016, 05:27:56) [GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.29)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> def catstring(a, b): ... return "{}{}".format(a,b) ... >>> def addstring(a, b): ... return a + b ... >>> x = "hello" >>> y = bytes("hello") >>> catstring(x, y) 'hellohello' >>> addstring(x, y) 'hellohello' >>>

There is no technical reason for the Python 3 version to differ from the behavior of the Python 2 version, they just decided that you should have to handle all the type problems related to Unicode and bytes with no help. This a classic "Macho Code Guy" move and it has no place in a language for beginners. Difficult usability is not a marker of a better programming language, or better programmers. It is only a marker of arrogant people doing the implementation. However, when you point out that this is hard to use they try to claim it's good for you. It is not. It's simple blustering covering for a poor implementation.

A final note on this is even the error message is macho and terse:

Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in addstring TypeError: can't concat bytes to str

If they're going to require beginners to struggle with the difference between bytes and Unicode the least they could do is tell people what variables are bytes and what variables are strings. They probably consider helpful error messages "magic" though so don't hold your breath they'll actually fix this one.

Dynamic and Static Mismatch

One fatal flaw of this decision to "static type" the strings is Python lacks the type safety gear to deal with it. Python is a dynamic language, and doesn't support type declarations on function arguments. It's also not statically compiled as strongly as it could be, so you can't find these kinds of type errors until you run the code. In the past this wasn't an issue because you'd write tests and the dynamic nature of Python meant things kept working as long as the method signature of types was the same.

Strings are also most frequently received from an external source, such as a network socket, file, or similar input. This means that Python 3's statically typed strings and lack of static type safety will cause Python 3 applications to crash more often and have more security problems when compared with Python 2.

Core Libraries Not Updated

There are several libraries that, despite knowing the encoding of data, fail to return proper strings. The worst offender seems to be any libraries dealing with the HTTP protocol, which does indicate the encoding of the underlying byte stream in many cases. In many cases the library uses the old API that relied on dynamically typed strings, but doesn't update to help with the returned values. It returns what you think is a "string" but is really bytes when the proper return should now most likely be the raw bytes plus any encoding information the library can figure out.

What's even more idiotic about this is, Python has a really good Chardet library for detecting the encoding of byte streams. If Python 3 is supposed to be "batteries included" then fast Chardet should be baked into the core of Python 3's strings making it cake to translate strings to bytes even if you don't know the underlying encoding. In fact, I'd like to see this:

x = bytes('hello', 'utf-8') y = x.guess()

The point being that character encoding detection and negotiation is a solved problem. Other languages do it to varying degrees of success without the constant exceptions being thrown. Python 3 however has taken the stance that, since they think strings being unicode are "important", that means you must constantly be aware of them and constantly have to deal with them. To them, usability is counter to safety, when that's not true at all.

Too Many Formatting Options

Currently Python 3 supports the old style of formatting:

print "Howdy %s" % ('Zed')

The new .format() style:

print "Howdy {}".format('Zed')

And in Python 3.6 we will have a formatting style that's more like Ruby's:

x = 'Zed' print f"Howdy {x}"

I really like this new style, and I have no idea why this wasn't the formatting for Python 3 instead of that stupid .format function. String interpolation is natural for most people and easy to explain.

The problem is that beginner will now how to know all three of these formatting styles, and that's too many. When I update Learn Python The Hard Way to Python 3 I'm only going to teach the 3.6 "f-string" style, and then mention the other two only as legacy code.

Even More Versions of Strings

Finally, I'm told there is a new proposal for a string type that is both bytes and Unicode at the same time? That'd be fantastic if this new type brings back the dynamic typing that makes Python easy, but I'm betting it will end up being yet another static type to learn. For that reason I also think beginners should avoid Python 3 until this new "chimera string" is implemented and works reliably in a dynamic way. Until then, you will just be dealing with difficult strings that are statically typed in a dynamically typed language.

I have resisted writing about these problems with Python 3 for 5 versions because I hoped it would become usable for beginners. Each year I would attempt to convert some of my code and write a couple small tests with Python 3 and simply fail. If I couldn't use Python 3 reliably then there's no way a total beginner could manage it. So each year I'd attempt it, and fail, and wait until they fix it. I really liked Python and hoped the Python project would drop their stupid stances on usability.

After 5 versions I'm ready to admit that Python 3 is simply broken for beginners and move on. I'm hoping that writing this list will prompt some kind of change, but I doubt it. As the versions of Python 3 progressed--and the adoption was lacking--the Python project started using social pressure, propaganda, and marketing to gain traction instead of fixing Python 3's obvious usability problems. This is a dangerous position because it is easy to fix problems that are seen as simple technical or usability flaws. It is very difficult to fix problems that are erroneously viewed as positive social goods.

Currently, the state of strings is viewed as a Good Thing in the Python community. The fact that you can't run Python 2 inside Python 3 is seen as a weird kind of tough love. The brainwashing goes so far as to outright deny the mathematics behind language translation and compilation in an attempt to motivate the Python community to brute force convert all Python 2 code.

The brutal truth is if Python 3 had been designed to run Python 2 and 3 code together, and strings were as dynamic as the Python 2 strings, we would not be in this situation. Now, I fear that everyone who currently codes Python 2 is simply going to move to a more stable language like Go, Rust, Clojure, or Elixir. The switching costs of Python 3 are so high programmers will just switch to another language that isn't broken or is more exciting.

Which is probably why the Python project focuses on convincing unsuspecting beginners to use Python 3. They don't have a switching cost, so if you get them to fumble their way through the Python 3 usability problems then you have new converts who don't know any better. To me this is morally wrong and is simply preying on people to prop up a project that needs a full reset to survive. It means beginners will fail at learning to code not because of their own abilities, but because of Python 3's difficulty.

It's sad to watch Python destroy itself because it's such a great language, but that seems to be where things are headed. It's my hope that this essay wakes them up and they change their path to something much more friendly to everyone. That they admit Python 3's design was seriously flawed and start Python 4 in an attempt to rescue the language. Sadly, I doubt this will happen, and instead they'll just rant about how I don't know what I'm talking about and I should shut up. My book is already banned on many Reddit subreddits, and various high profile Python project members work fairly hard to censor it because of my stance on their strategy. After this essay they will probably double down on their stubbornness and refuse to listen.

No matter what happens though, I'll still continue to teach total beginners in the best way I can so they have the easiest path to code competency and a long love of programming.

Thank you for reading this.

learnpythonthehardway.org

Green Tree Python - Snake Facts and Information

Green Tree Python – Morelia viridis

Introduction

The Green Tree Python lives in areas where most people will never get a chance to see one up close. They are very colorful though and that is what gains them lots of attention. They become very docile in captivity and receive many special care.

Description

The color of the Green Tree Python is a lime green that can be light or dark in color. It has a light white or cream coloration on the belly. They may have a yellow color too depending on their habitat. For that reason though they are often mistaken for other species of snakes. Sometimes they even have blue tint to them. They can be up to 6 ½ feet long when they are fully mature.

Distribution

New Guinea, Indonesia, and the Cape York Peninsula in Australia are the main locations for this species of snake. However, there are many smaller populations of them out there all over the place that have been identified. Since they blend in so well it is hard to know how many of them are really out there.

They live in trees, forest regions, and tall grasses. In some locations their habitat continues to be taken away. Efforts by humans including logging continue to clear out areas where they live.

Behavior

The Green Tree Python spends most of its live living in the trees. They will loop a coil around the trees and place their head in the middle. When they aren’t stretched out they don’t look much like a snake and that can give them the element of surprise with their prey.

They are well known to bite when someone or something provokes them. They can become easily agitated and very protective. The males become more aggressive when they are looking for mates. The females become more aggressive when they have eggs to protect.

Diet /Feeding

Rodents, reptiles, and other small living things make up the majority of the diet for the Green Tree Python. They are often listed as being consumers of birds but that hasn’t been verified. Experts have observed them in the wild and they have carefully evaluated stomach contents. There is no evidence that they consume birds based on such studies.

They bite their prey and they will constrict around it. This is going to suffocate the prey so that it won’t be able to move or to breathe. Then will open up the jaws and swallow the prey. It can take days or weeks for the food they eat to fully digest.

Green tree python – Morelia viridis / Photo taken by Tim Vickers

Reproduction

The males may travel long distances to find a mate. The females won’t always be inviting of his advances. Mating is from August through December. The eggs will be disturbed from November through February. The females will deposit the clutch of eggs into a tree to protect them.

The young will be born with a yellowish coloring and then spots of purple and brown on them. She will keep a watchful eye on the site to prevent predators from disturbing them. However, once they come out of the shells she will leave them to care for themselves.

Venomous Bite /Danger to Humans

While the Green Tree Python will bite there is no venom offered by this species of snake. However, it is still important to be able to get medical attention after such a bite to prevent an infection. Researches suggests they aren’t strong enough or large enough to crush a human but they have been known to try to do so.

www.snaketype.com

Python Listeler ve Kullanımı | Python Türkiye

Python Listeler ve Kullanımı

Merhaba arkadaşlar, Artık yavaş yavaş python temel yapısını ortaladık listeler yapısına geçtik. Farklı yazılım dilleri bilen arkadaşlar (C#,php,java) bu liste yapısını dizi olarak tanımlamaktadır.

Konuyu daha iyi anlatabilmek adına sol taraftakı resimden yaralanıcaz. Liste dediğimiz yapı aslında sol tarafta oluşan resim gibidir. Bu listenin sonsuza giden elemanları mevcuttur. Listeler sıfırdan başlar ve artmaya devam eder. Şimdi sağdaki listenin adı görüldüğü üzere Sayilar‘dır

Burada Sayilar[0] şeklinde ifade edilen nokta sıfırıncı elemanı ifade etmektedir yani “6” . Sayilar[numara], numara yazılan yerler ise indeks olarak ifade edilmektedir.

Liste Yapısı :

Sayilar = [] print(type(Sayilar))

Sayilar = []

print(type(Sayilar))

ÇIKTI :

Köşeli parantezler ile oluşan yapının veri tipi çıktıda görüldüğü gibi “list” yani liste olarak adlandırılır.

Konuyu daha iyi anlamak adına, yukarıda dizi yapısından verdiğimiz resmi koda dökelim.

İlk önce dizi yapımızı oluşturalım ve ekrana yazdıralım bakalım nasıl bir çıktı veriyormuş :

Sayilar = ['6','523','-56','-45','234','35'] print(Sayilar)

Sayilar = ['6','523','-56','-45','234','35']

print(Sayilar)

ÇIKTI :

['6', '523', '-56', '-45', '234', '35']

['6', '523', '-56', '-45', '234', '35']

Dizi elemanlarını bu şekilde görebiliyoruz.

Yukarıda indeks yapısından bahsetmiştik, peki listedeki elemanları indeks numarasına göre nasıl çağırabiliriz. Hemen örnek yapalım.

Sayilar = ['6','523','-56','-45','234','35'] # elemanların 0 dan başladığını unutmayın. print(Sayilar[1]) #Burada 1. elemanı ekrana çağırıyoruz.

Sayilar = ['6','523','-56','-45','234','35']

# elemanların 0 dan başladığını unutmayın.

print(Sayilar[1]) #Burada 1. elemanı ekrana çağırıyoruz.

ÇIKTI :

ListeAdı[indeks] şeklinde indeks numarasına göre ekrana çağırabiliriz.

 Python dilinde liste yapısını az çok anladık, artık daha fazla detaylara inerek örneklerimiz yapabiliriz.

Python Listeye Eleman Ekleme

Python dilinde diziye eleman eklemek için Append() hazır fonksiyonunu kullanabiliriz.

Liste = ['Ali'] Liste.append('Mehmet') #Mehmet verisin ekliyoruz. print(Liste)

Liste = ['Ali']

Liste.append('Mehmet') #Mehmet verisin ekliyoruz.

print(Liste)

Ekrana çağırdığımız zaman şöyle bir çıktı vericektir :

Python Listenin Eleman Sayısını Öğrenme

Python dilinde dizinin eleman sayısını öğrenmek için len() hazır fonksiyonu kullanabiliriz.

Liste = ['Ali'] Liste.append('Mehmet') #Mehmet verisin ekliyoruz. # Toplamda 2 adet verimiz olduğunu görüyoruz. print(len(Liste)) >>> ÇIKTI : 2

Liste = ['Ali']

Liste.append('Mehmet') #Mehmet verisin ekliyoruz.

 

# Toplamda 2 adet verimiz olduğunu görüyoruz.

 

print(len(Liste))

 

>>> ÇIKTI : 2

Dolasıyla çıktımız “2” olucaktır. Eleman değerini ölçmek için kısaca len fonksiyonu len(veri) şeklinde verinin eleman sayısını öğrenebiliriz.

Python Listenin Elemanlarını While Döngüsü İle Ekrana Yazdırma

Yukarıdaki örneklerden fark ettiniz mi bilmiyorum ama , listelerimizin uzun olduğunu düşünersek tek tek Sayilar[indeks] şeklinde çağırmak uzun ve zahmetli olacağından bir döngüye bağlayarak tak tak yazdırmak daha mantıklı olucaktır.

İşlemleri adım adım yapalım, son örneğimiz olacağı için tekrar etmiş oluruz.

  • İlk önce dizimizi oluşturalım. Bildiğiniz üzere diziler [] şeklinde oluşur. Elemanları ise [‘eleman1′,’eleman2’] şeklinde eklenir.

Sayilar = ['6','523','-56','-45','234','35','5','33','65','66']

Sayilar = ['6','523','-56','-45','234','35','5','33','65','66']

  • While döngümüzde koşul koyabilmemiz için listenin eleman sayısını öğrenmemiz gerekiyor. Len() hazır fonksiyonu listedeki tüm elemanların sayısını öğrenebiliriz.

Sayilar = ['6','523','-56','-45','234','35','5','33','65','66'] liste_say = len(Sayilar)

Sayilar = ['6','523','-56','-45','234','35','5','33','65','66']

liste_say = len(Sayilar)

  • Elemanların hepsini yazdırabilmek adına, dışardan bir değişken tanımlayım. Bu değişkene bağlı koşul oluşturalım.

Sayilar = ['6','523','-56','-45','234','35','5','33','65','66'] liste_say = len(Sayilar) baslangic = 0

Sayilar = ['6','523','-56','-45','234','35','5','33','65','66']

liste_say = len(Sayilar)

baslangic = 0

  • Artık döngümüzü oluşturabiliriz :

Sayilar = ['6','523','56','45','234','35','5','33','65','66'] liste_say = len(Sayilar) baslangic = 0 while(baslangic<liste_say): print(Sayilar[baslangic]) baslangic = baslangic+1

Sayilar = ['6','523','56','45','234','35','5','33','65','66']

liste_say = len(Sayilar)

baslangic = 0

while(baslangic<liste_say):

    print(Sayilar[baslangic])

    baslangic = baslangic+1

  • Yukarıdaki while yapımızı incelediğimizde, baslangic değeri sıfır olduğu için , başlangiç değeri liste elemanı olana kadar devam edicektir. Döngü her seferinde döndüğünde baslangic değeri artacak dolasıyla, Sayilar[baslangic] şeklinde olduğu için listedeki tüm elemanları sırasıyla yazdırabiliriz.

ÇIKTI :

6 523 56 45 234 35 5 33 65 66

Durumu özetlemek gerekirse

  • Diğer dillerde olan dizi yapisiyla liste yapisinin aynı olduğunu öğrendik.
  • Liste yapısının ne olduğunu öğrendik.
  • Python dilinde liste oluşturup ekrana yazdırdık.
  • Append() fonksiyonu ile listeye yeni eleman ekledik.
  • Len() fonksiyonu ile listenin eleman sayısını öğrendik.
  • While döngüsü ile tek döngüde listenin tüm elemanları yazdırdık.

 

 

www.python.tc


Смотрите также