Login Register






My Python Tutorial filter_list
Author
Message
My Python Tutorial #1
I wrote a little Python Tutorial. It contains only printing, variables and formatted printing. If you like it I will continue it. Please post comments.

Lesson 1:
Spoiler: Introduction
This is first lesson of Mihai's Python Tutorial. I will start by say you why you should learn Python.

Why?

Because Python is powerful, object-oriented, you can use it on web, you can share very easy your
programs, NASA and GOOGLE use it, with some libraries you can make games and GUI applications
and it is easy! EDIT: Python is not only object-oriented. Python is a multi-paradigm programming language, meaning it supports many different programming styles, such as; object-oriented, imperative and functional programming or procedural styles.

First, you will need to install on your computer Python 2.7, DON'T INSTALL ANY VERSION > 2.X.Y!!!

! If you use python 3.x.y , you need to use print() in next examples.
So, for python 3 use: print("Hello") NOT print "Hello"

If you are using Windows you must download from www.python.org, if you are using Linux you already have it.
! I don't know how to get it for Mac, I don't use it, but I will write how in future.
! For windows users: after you installed Python, go on web and search: "How to add Python 2.7 on envroiement variables"

Second, I propose to you to install gedit, is a good tool for edit. After you installed it, go to Edit->Preferences and click on
"Display line numbers" box, after in editor tab click on "Insert spaces insted of tabs" and "Endable automatic indentation" boxes. At last close preferences box.
! Linux users already has gedit.

OK, now create a file named: hello.py
Open it and write next code in it:

Code:
print "Hello, World!" print "This is my first Python Program!\n" print "Bye!"

Save the file and enter in terminal(comand prompt in windows) and change directory to location where you made the file.
After, run in terminal the command: python hello.py
This will run the program and you will see the next screen:

a) in Windows:

Code:
C/Users/Administrator/Desktop> python hello.py Hello, World! This is my first Python Program! Bye!

b) in Linux:

Code:
administrator@computer:~/Desktop$ python hello.py Hello, World! This is my first Python Program! Bye!

Now let's explain the code:

1. print is a Python keyword what write to the screen a message or a variable.

2. "Hello, World!" -> this is a string = a set of multiple characters, the quotes("") mark the string start and end.
You can use this '' , not only "". If you want to print a quote or an apostroph you must write: print "\'" , print "\""
This is an escape sequence. Escape sequences are used to print
special character like:
'\n' -> new line
'\b' -> back space
etc... Search more about it.

3. Each print ends with a new line, so when you write print "Some messages", after computer print message it go to the next line.

4. If you want to add more new lines you can use next escape sequence: "\n"

Now delete some parts of program like: one quote, two quotes, one line of code and after run program. See what happens. What errors you receive? Go to web and read a little bit about errors.

Exercises
1.Create a file ex1.py and use it to print next text:

Code:
How are you, Mihai?\t I am fine! So, do you know Python? \tYes, \t test me!

Run program and see result. You can send your exercises resolved at email: anonimatanonimus@Gmail.com and I will say if it is right.
PS Go to web and read about \t character.

Thanks for reading. We can be friends if you mail me.


Lesson 2:
Spoiler: Variables and Formatted printing
A. Variables

Now we will talk about one of the basic thing of a programming language: VARIABLES
What are variables? Variables are locations in memory where is stored data, variables can be modified. ! IN OTHER LANGUAGES LIKE
C++ EXIST CONSTANTS, CONSTANTS CAN'T BE MODIFIED.

In python we have next types of variables(=vars.):

1.integers -> numbers without decimal part: 4567, -34, 864, etc...
2.floating point -> numers with decimal part: 34.56, -6975.233, 57.7, etc...
3.strings -> sets of characters: "Hello bwrkbfer" , 'ewjhnfwfgr', 'fwefwfwrwgerg', etc...
4.booleans -> logical values: True, False

! If a number is between quotes or apostrophes, it is a string! If not, it is a number!

! How to print a number:
Code:
print 13 print 23.76 print 13+56 # you can make operations directly after print statement

! In a python file, the symbol: # represent a comment, so interpreter ingnore it, you can use comments to explain your code.

Now let's see how a variable look:
1.it has a name
2.you must give it a values via '=' symbol

Create a file vars.py and write in it:

Code:
number1 = 10 # this is definition of a var. named 'number1' number2 = 13.5 # variables names can contain numbers, letters and '_' symbol String = "Hello" a_bool = True # this will print variables print number1 print number2 print number1 + number2 print String print a_bool String = "new value" # you can change vars. values after define they. print String # this will print new value

Run file and you will see how computer print your varables and sum of number1 and number2

B.Formatted printing

All vars. types can be printed in a string using formaters:

%d -> for integers
%f -> for floating point
%s -> for other strings

So if you write in a file:

Code:
print "Hello Mihai. I am %d years, I have %f kilos and my name is %s." % (13, 34.56, "Alex")

You will see:

Code:
Hello Mihai. I am 13 years, I have 34.56 kilos and my name is Alex
.

First formatter was replaced by 13 , second by 34.56 and last by "Alex". Easy, ok? You can use variables in formatted printing:

Code:
name = "Mihai" age = 13 print "Hello %s, I am %d years old." % (name, age) # test this

! Let's play:

Code:
print "%s" % 13 # this will write 13 print "%s" % 13.56 # this will write 13.56 print "%d" % 12.45 # this will print only integer part, so will print only 12 print "%f" % 12 # this will print 12.000000 print "%f" % "Hello" or print "%d" % "Hello" # this two statements will generate an error, you can't print strings as numbers

Exercises
1.Use formated printing and variables to print a little description about you, send me at: anonimatanonimus@Gmail.com
If you want you can play a little bit with errors and send me some funny errors you obtained.

2.Write a program with 3 variables: num1, num2 and text. Using text var. , print the sum and difference of num1 and num2 on two lines.
Hint: you can define text var. in next style:
Code:
text = "Hello, %s!"


For any problems, comments and others, my mail is above.
Thanks for reading.

Lesson 3:
Spoiler: 3.Input and more strings and printing BONUS: import keyword
Welcome back! Now I will talk about a very cool part of Python: INPUT and CONCENTRATION OF STRINGS!

A.More on strings

I will start from an example:

Code:
num1 = 10 num2 = 13.56 s = "Hello" print s + "\n" + str(num1) + " " + str(num2) # for Python 3: print (s + "\n" + str(num1) + " " + str(num2))

This will print:
Code:
Hello 10 13.56
Let's explain code:
str() function converts a number to string
in a print statement you can use '+' symbol to add two numbers or combine strings, so:
Code:
print "Hello," + " " + "Mihai"
will print: Hello, Mihai

Tip: if you don't want to print automatically new line you can use: print "Hello", or for Python 3 print("Hello", end='')

Another way to format strings is:

Code:
print "Hello, {0}! How are {1}?".format("Mihai", "you")

Test it and you will understand it.

B.Input

a) input directly from user

write this in a file:
Code:
text = raw_input("Enter text: ") # use text = input(Enter text: ) for Python 3
When you will run it, program will wait text from keyboard, so type something and press enter. Your entered text will be
storaged in text var. "Enter text: " is a prompt, it will be printed before request of input.

If you want to read -> an integer use: int(raw_input()) or int(input()) # for Python 3
-> a floating point: float(raw_input()) or float(input()) # for Python 3

Now play with input and make some funny programs.

OPTIONAL:
if you have 2 python files and you want to connect this 2 files you can use 'import' keyword.
Example: we have 2 files: main.py and lib.py

in lib.py:
Code:
text = "Hello!"

in main.py:
Code:
import lib # get access to lib.py file print lib.text # you need to write lib. before access its variables, if you don't want to write allways this prefix you can import file n next file: from lib import * , but some people don't recommend this, or you can import only one variable: from lib import text and you won't need to write prefix for this variable

Now play with this! Imported files are named libraries or modules.
PS Don't forget to read on web and explore errors

b) input from arguments
You will learn about it in future, or search on web now!

TEST:
After 3 lessons is time for a little test with 3 exercises:

1. Write a program what take next input from user: name, age and kilos and after use formatted printing(in all ways you learnt) to
show it to user. (30p)

2. Write a program what take next input:
name -> string,
money -> floating point,
tax -> floating point,
salary -> integer
It will calculate
Code:
salary - salary * tax
and it will add this calculation to money var. and it will print
Code:
name + ", you have %f" + " dollars." % money
. (30p)

3.Fix next program:

Code:
text = '' text = raw_input("What is your name? ) # get name print "How are you, %f?" % (text) print "If you are fine say "OK"!' text = ra_input("> ") print 'So, you're {1}".format(text)
(30p)

You receive 10p for resolve all exercises. Max points you can obtain: 100p

Send me the files with solutins to: anonimatanonimus@Gmail.com

Thanks for reading!

Lesson 4:
Spoiler: 4.Conditionals and loops


A.Conditionals

In Python you can make programs who give to you more options and make different things depend by your choices.
Let's start from an example: if you want to make a program what take as input a number and if the number is bigger than 3 you will print "OK" else you will print "Bad".

Code:
num = raw_input("Enter a number: ") # get number if num > 3: # if number is > than 3 print "OK" # print OK else: # else(if number isn't > than 3) print "Bad" # print Bad

The code is very easy to understand. Now we need to talk about indentation:
In Python you must indent code (the placement of text farther to the right to separate it from surrounding text.
). After if statement you must put ":" and after(on next line) you must indent code, because this will say to compiler to execute this block of code if the if statement return True. My indentation is 4 spaces.

Syntax of if statement:

Code:
if "expression": # if expression is True, the next block of code will be executed # don't forget indentation "code..." elif "another expresion": # if the first statement didn't is True, computer will check this "code..." elif "another expresion": # another expresion to check "code..." else: # if no one expression is true, this block of code will be executed "code..."

B.Loops

Before talk about loops, we need to talk about lists!

A list is a variable with more than one values.
Define of list:

Code:
myList = ["hello", 23, 45.67, True] # a list can be empty myList = []

Access the values of a list:

Each list have an index:

Code:
myList = ["hello", 23, 45.67, True] #index 0 1 2 3

To access a value you need to use this: myList[i]
So, print myList[1] will print 23, because at index 1 of my list is 23 value.
Get index of an element: myList.index(True) -> return 3
Add more elements: myList.append(newElement) # new element will have last index + 1
Modify an element: myList[3] = "newValue" # now, if we access myList[3] -> return "newValue"

Now go and explore errors. Access element 4 from my list and others errors.


Now, let's talk about loops:

a) while loop

"while" instruction will evaluate a expression and will execute a block of code until expresion is False

Syntax:

Code:
while "expression": # don't forget to indent (I use 4 spaces) "code..."

Example:
Code:
i = 1 while i < 10: # if i is lower than 10 print "Good" i = i + 1 # incrase i by 1 # "while" instrution will print "Good" until i become 10

Now go and practice a little bit with "while".

b) for loop

"for" instruction will execute a block of code for every value of a variable in a list. You will understand this now.
Example:
Code:
myList = [1, 2, 3] for i in myList: # i will have each value from myList print i # so when you run this , program will print 1 2 3

Syntax:
Code:
for "variable" in "list": # don't forget to indent "code..."

! If you want to stop a loop, you can use "break" keyord:

Code:
i = 0 while i < 10: print i if i == 5: print "Stop!!!" break i = i + 1

This loop will print i until i >= 10, but if i = 5, program will print "Stop!!!" and stop loop.
! Diference between "=" and "==":
"=" -> assign a value to a variable -> i = 10 # i has value of 10
"==" -> test if a variable has a value -> if i==10 # test if i has value of 10

Exercise:

1.Create a guess game:
One player enter a number(<10). After you clear screen(go on web and search how)
Next player have 3 tries to guess number. If he guess number print "You win!", if tries run out print "You loose!"
Try to add a menu and a replay feature.

2.Create a "bag". You will make a list named "bag"(empty at start). After ask user if he want to add more items or drop items.
If he want to add an item, you request item name and add it to bag. If he want to drop an item, request item name, check if item exist in bag and after remove it. Use web to read about remove and checking items in list. Put all this things in a loop and add an exit feature.

PS the code:
Code:
while True: print "Hello"
will run for eternyty, because "True" is allways a true expression. You can stop "while True: ..." using a "break" keyword.

Send to my mail this two programs.




1 like = 1 second

Reply

RE: My Python Tutorial #2
Nice tut, for those wanting more on python and want to dive in a recommend bucky's channel on youtube. www.youtube.com/thenewboston

Reply

RE: My Python Tutorial #3
I find it great that you're at such a young age, already feel like sharing information. Keep it up!

But I still have a few things to point out.

Quote:Because Python is powerful, object-oriented, you can use it on web, you can share very easy your
programs,

Python is not only object-oriented. Python is a multi-paradigm programming language, meaning it supports many different programming styles, such as; object-oriented, imperative and functional programming or procedural styles.

Quote:First, you will need to install on your computer Python 2.7, DON'T INSTALL ANY VERSION > 2.X.Y!!!
If you are using Windows you must download from http://www.python.org, if you are using Linux you already have it.
! I don't know how to get it for Mac, I don't use it, but I will write how in future.
! For windows users: after you installed Python, go on web and search: "How to add Python 2.7 on envroiement variables"

Any why do you tell people not to install any other version of Python? The latest stable release of Python is Python 3.4.1. Python 3 has matured a lot lately and is actually pretty nice! People really have to get over the fear for Python 3, it's far better than most people think.

As a side note, Python comes pre-installed in OS X too ;-)

Next part.

Quote:1. print is a Python keyword what write to the screen a message or a variable.
2. "Hello, World!" -> this is a string = a set of multiple characters, the quotes("") mark the string start and end.
You can use this '' , not only "". If you want to print a quote or an apostroph you must write: print "\'" , print "\""
This is an escape sequence.
3. Each print ends with a new line, so when you write print "Some messages", after computer print message it go to the next line.
4. If you want to add more new lines you can use next escape sequence: "\n"

This part seems a bit unclear to me. I'd re-write it if I were you. Give a bit more examples on the escape character, so people truly knows how to use it. We need info, info info!

At the same time, it's great that you tell people to go explore the error messages. This is truly something that's going to help you a lot in the future. Error messages are a key part of programming.

Homework? I'd call it exercise instead, lol. Homeworks sounds boring. But maybe create exercises such as the ones on this page ( http://www.upriss.org.uk/python/session1.html ).

One thing that caught my mind too, is that you give a brief, but ok, definition on variables. But you quickly move into strong formatting? It's awesome that you try to teach about string formatting, but why not tell the reader, why string formatting is preferred over string concatenation? At the same time, why not show the reader how to get user input? I know from when I first began programming, that I found the user interaction one of the most interesting parts. Take input, do actions based on the input, show output etc.

Again, I find it really awesome that you want to share the knowledge you have and even more awesome that you've put time into writing content for other beginners, too. I've given you a few points at where you can improve your guide and maybe, even help beginners reach furhter. Good luck.

Reply

RE: My Python Tutorial #4
thanks for comments. i will correct where I made misstakes and content is unclear.
This is only my first version of tutorial. I will make a lesson 3 with user input and string concentration.

(07-29-2014, 05:51 PM)android() Wrote: Nice tut, for those wanting more on python and want to dive in a recommend bucky's channel on youtube. www.youtube.com/thenewboston

i will make a channel for my tutorial too.

Reply

RE: My Python Tutorial #5
(07-29-2014, 05:51 PM)android() Wrote: Nice tut, for those wanting more on python and want to dive in a recommend bucky's channel on youtube. www.youtube.com/thenewboston

I would never recommend Bucky's tutorials instead get yourself an ebook or study it from the Python DOC
My Blog: http://www.procurity.wordpress.com
Donations: 1HLjiSbnWMpeQU46eUVCrYdbkrtduX7snG

Reply

RE: My Python Tutorial #6
lesson 3 added. Good night!

Reply

RE: My Python Tutorial #7
I honestly would suggest codecademy.com it has a python section. Yes written tutorials are great but the hard part is actually testing yourself. Keep up the good work and I hope to see some interesting posts in the future..
[Image: iQ3pcQu.png]
BTC Address: 1DCKgDaWcmc9dxBkhe9qrTQtrQpoFUzXdn

Reply

RE: My Python Tutorial #8
thanks. codecademy is a good choice if you want to learn python. i made the python section on it.

Reply

RE: My Python Tutorial #9
lesson 4 added!

Reply

RE: My Python Tutorial #10
"After if statement you must put ":" and after(on next line) you must indent code, because this will say to compiler to execute this block of code if the if statement return True. My indentation is 4 spaces."

Python is not traditionally a compiled language it is interpreted.

Also it isn't just after if statements that you place a colon, you do so for while loops, for loops, function declarations, etc.. A colon is placed to announce a code block.


Also in your while loop code
Code:
i = 0 while i < 10: print i if i == 5: print "Stop!!!" break i = i + 1

you could just increment i
Code:
i = 0 while i < 10: print i if i == 5: print "Stop!!!" break ++i

or you can even use i += 1
[Image: iQ3pcQu.png]
BTC Address: 1DCKgDaWcmc9dxBkhe9qrTQtrQpoFUzXdn

Reply