Make delicious recipes!

Python


Installing python

To begin learning python, download python here.
Install it as per the directions given in the above link.
Then go the folder where python is installed and double-click python.exe to start the python shell.

In the shell that opens, type the first command as print ("Hello World") and see the output as follows:



Congratulations!
Python is up and running and your first python line has just been executed.



Some more code to whet your appetite:

Example 1: Creating a list

foo = []              # declares 'foo' as a list
foo.append(1)         # add an integer variable
foo.append("Hello");  # add a string in quotes
foo.append('World');  # add another string but in single quotes
foo.append(2.0);      # add a floating point number


# iterate over the list and print the elements.
for v in foo:
 print (v) # note the indentation before print statement!


# Python provides several function for easy list manipulation:
>>> l = [4, 1, 7, 2, 9]
>>> l
[4, 1, 7, 2, 9]

>>> sorted(l)
[1, 2, 4, 7, 9]
>>> l
[4, 1, 7, 2, 9]

# sorted() does not change the input list argument.
# If that is desired, use list.sort
>>> l.sort()
>>> l
[1, 2, 4, 7, 9]



# Reversing a list is easy!
>>> list(reversed(l))
[9, 7, 4, 2, 1]

>>> l.reverse()
>>> l
[9, 7, 4, 2, 1]


Output:
1
Hello
World
2.0


Example 2: Tuples (immutable structures)
tple = (1,2,3);   # a tuple is created using round brackets.
print (tple[1]);  # prints 2
a,b,c,d = tple;   # assigns values from the tuple one by one.

tple[1] = 5;      # tuples are immutable!
# Traceback (most recent call last):
# TypeError: 'tuple' object does not support item assignment
Note: Tuples are similar to those in Erlang except that tuples in Erlang use curly braces and are mutable.


Example 3: Operators and string conversion
print ( 
    "hello "*2 + "world" +   # strings can be multiplied by numbers and added by + operator
    "\n" +                   # \n is used for newline
    str(1 + 2 * 6 / 2) +     # all normal operators like + - * /
    "\n" +                   # Use str () to convert to string
    str ((3**2) % 5)         # ** is for power and % is for remainder.
)

print ( [1,2,3]*2 + [0,0] )  # lists can also be multiplied with numbers and added like strings
Output:
hello hello world
7.0
4

[1, 2, 3, 1, 2, 3, 0, 0]




Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal