Input optional
Output
|
Learn python
Saturday, 27 April 2019
Hello, World!
Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.
Python is Interpreted - Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP.
Python is widely used in Artificial Intelligence, Natural Language Generation, Neural Networks and other advanced fields of Computer Science. Python had deep focus on code readability & this class will teach you python from basics. So if you want to start learning AI or deep learning. Learning python is a great start !
To print a string, just write:
To print a string, just write:
print ("Hello World!")
Readability
Python is all about ease. It is a very readable language. Python has Python uses indentation for blocks, instead of curly braces. Both tabs and spaces are supported, but the standard indentation requires standard Python code to use four spaces.For example:
a=0
def printfnc():
print (a)
printfnc()
Types
Another remarkable aspect of Python: Not only the value of a variable may change during program execution but the type as well. You can assign an integer value to a variable, use it as an integer for a while and then assign a string to the same variable.
In the following line of code, we assign the value 42 to a variable:
i = 42The equal "=" sign in the assignment shouldn't be seen as "is equal to". It should be "read" or interpreted as "is set to", meaning in our example "the variable i is set to 42". Now we will increase the value of this variable by 1:
>> i = i + 1
>>> print(i)
43
>>>
As we have said above, the type of a variable can change during the execution of a script. Or to be precise: A new object, which can be of any type, will be assigned to it. We illustrate this in our following example:
i = 42 # data type is implicitly set to integer
i = 42 + 0.11 # data type is changed to float
i = "forty" # and now it will be a string
Python automatically takes care of the physical representation for the different data types, i.e. an integer values will be stored in a different memory location than a float or a string.Object References
We want to take a closer look on variables now. Python variables are references to objects, but the actual data is contained in the objects: As variables are pointing to objects and objects can be of arbitrary data type, variables cannot have types associated with them. This is a huge difference to C, C++ or Java, where a variable is associated with a fixed data type. This association can't be changed as long as the program is running. Therefore it is possible to write code like the following in Python:
>>> x = 42
>>> print(x)
42
>>> x = "Now x references a string"
>>> print(x)
Now x references a string
We want to demonstrate something else now. Let's look at the following code:
>>> x = 42
>>> y = x
We created an integer object 42 and assigned it to the variable x. After this we assigned x to the variable y. This means that both variables reference the same object. The following picture illustrates this: What will happen, when we executey = 78
after the previous code? Python will create a new integer object with the content 78 and then the variable y will reference this newly created object, as we can see in the following picture: Most probably, we will see further changes to the variables in the flow of our program. There might be for example a string assignment to the variable x. The previously integer object "42" will be orphaned after this assignment. It will be removed by Python, because no other variable is referencing it.id Function
You may ask yourself, how can we see or prove that x and y really reference the same object after the assignmenty = x
of our previous example?The identity function id() can be used for this purpose. Every instance (object or variable) has an identity, i.e. an integer which is unique within the script or program, i.e. other objects have different identities.
So, let's have a look at our previous example and how the identities will change:
>>> x = 42
>>> id(x)
10107136
>>> y = x
>>> id(x), id(y)
(10107136, 10107136)
>>> y = 78
>>> id(x), id(y)
(10107136, 10108288)
>>>
Valid Variable Names
The naming of variables follows the more general concept of an identifier. A Python identifier is a name used to identify a variable, function, class, module or other object.A variable name and an identifier can consist of the uppercase letters "A" through "Z", the lowercase letters "a" through "z" , the underscore _ and, except for the first character, the digits 0 through 9. Python 3.x is based on Unicode. This means that variable names and identifier names can additionally contain Unicode characters as well. But in Python 2, identifiers can only be ASCII letters, numbers and underscores.
Identifiers are unlimited in length. Case is significant. The fact that identifier names are case-sensitive can cause problems to some Windows users, where file names are case-insensitive for example.
Standard Data Types
- Numbers
- String
- List
- Tuple
- Dictionary
Numbers
Python supports four types of numbers - int,long,float and complexFor example
3(int),4.0(float),51924361L(long),3.14j(complex)A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.
To define an integer, use the following syntax:
myint = 7
To define a floating point number, you may use one of the following notations:
myfloat = 7.0
myfloat = float(7)
Strings
Strings are defined either with a single quote or a double quotes.
mystring = 'hello'
mystring = "hello"
There are additional variations on defining strings that make it easier to include things such as carriage returns, backslashes and Unicode characters. These are beyond the scope of this tutorial, but are covered in the Python documentation.
Simple operators can be executed on numbers and strings:
one = 1
two = 2
three = one + two
hello = "hello"
world = "world"
helloworld = hello + " " + world
Assignments can be done on more than one variable "simultaneously" on the same line like this
a, b = 3, 4
Lists
Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type.The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example −
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists
Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-onlylists. For example
tuple = ( 'abcd', 786 , 2.23, 'john' )
print tuple # Prints complete list
print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
Lists
This section will give you a more deeper insight on lists
Here is an example of how to build a list.
Two common operations are indexing and assigning to an index position. Both of these operations take the same amount of time no matter how large the list becomes. When an operation like this is independent of the size of the list they are O(1)O(1).
Another very common programming task is to grow a list. There are two ways to create a longer list. You can use the append method or the concatenation operator. The append method is O(1)O(1). However, the concatenation operator is O(k)O(k) where kk is the size of the list that is being concatenated. This is important for you to know because it can help you make your own programs more efficient by choosing the right tool for the job.
Let’s look at four different ways we might generate a list of n numbers starting with 0. First we’ll try a for loop and create the list by concatenation, then we’ll use append rather than concatenation. Next, we’ll try creating the list using list comprehension and finally, and perhaps the most obvious way, using the range function wrapped by a call to the list constructor.
def test1():
l = []
for i in range(1000):
l = l + [i]
def test2():
l = []
for i in range(1000):
l.append(i)
def test3():
l = [i for i in range(1000)]
def test4():
l = list(range(1000))
list=[1,'abc',2]
Basic List Operations
Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string.
In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.
Python Expression | Results | Description |
---|---|---|
len([1, 2, 3]) | 3 | Length |
[1, 2, 3] + [4, 5, 6] | [1, 2, 3, 4, 5, 6] | Concatenation |
['Hi!'] * 4 | ['Hi!', 'Hi!', 'Hi!', 'Hi!'] | Repetition |
3 in [1, 2, 3] | True | Membership |
for x in [1, 2, 3]: print x, | 1 2 3 | Iteration |
Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. For example -
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]
Deleting List Elements
To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. For example -
list1 = ['physics', 'chemistry', 1997, 2000];
print list1
del list1[2];
print "After deleting value at index 2 : "
print list1
Indexing, Slicing, and Matrixes
Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.Assuming following input −
L = ['spam', 'Spam', 'SPAM!']
Python Expression | Results | Description |
---|---|---|
L[2] | 'SPAM!' | Offsets start at zero |
L[-2] | 'Spam' | Negative: count from the right |
L[1:] | ['Spam', 'SPAM!'] | Slicing fetches sections |
Built-in List Functions & Methods
Python includes the following list functions −Sr.No. | Function with Description |
---|---|
1 | cmp(list1, list2)Compares elements of both lists. |
2 | len(list)Gives the total length of the list. |
3 | max(list)Returns item from the list with max value. |
4 | min(list)Returns item from the list with min value. |
5 | list(seq)Converts a tuple into list. |
Basic Operators
Arithmetic Operators
Just as any other programming languages, the addition, subtraction, multiplication, and division operators can be used with numbers.Try to predict what the answer will be. Does python follow order of operations?
number = 1 + 2 * 3 / 4.0
print number
Another operator available is the modulo (%) operator, which returns the integer remainder of the division. dividend % divisor = remainder.
remainder = 11 % 3
print remainder
Using two multiplication symbols makes a power relationship.
squared = 7 ** 2
cubed = 2 ** 3
print squared
print cubed
Using Operators with Strings
Python supports concatenating strings using the addition operator:helloworld = "hello" + " " + "world"
print helloworld
lotsofhellos = "hello" * 10
print lotsofhellos
Operator | Description | Example |
---|---|---|
+, - | Addition, Subtraction | 10 -3 |
*, % | Multiplication, Modulo | 27 % 7 Result: 6 |
/ | Division This operation results in different results for Python 2.x (like floor division) and Python 3.x | Python3:>>> 10 / 3
3.3333333333333335
and in Python 2.x:>>> 10 / 3 3 |
// | Truncation Division (also known as floordivision or floor division) The result of this division is the integral part of the result, i.e. the fractional part is truncated, if there is any. It works both for integers and floating-point numbers, but there is a difference in the type of the results: If both the divident and the divisor are integers, the result will be also an integer. If either the divident or the divisor is a float, the result will be the truncated result as a float. | >>> 10 // 3
3
If at least one of the operands is a float value, we get a truncated float value as the result.>>> 10.0 // 3 3.0 >>>A note about efficiency: The results of int(10 / 3) and 10 // 3 are equal. But the "//" division is more than two times as fast! You can see this here: In [9]: %%timeit for x in range(1, 100): y = int(100 / x) ...: 100000 loops, best of 3: 11.1 μs per loop In [10]: %%timeit for x in range(1, 100): y = 100 // x ....: 100000 loops, best of 3: 4.48 μs per loop |
+x, -x | Unary minus and Unary plus (Algebraic signs) | -3 |
~x | Bitwise negation | ~3 - 4 Result: -8 |
** | Exponentiation | 10 ** 3 Result: 1000 |
or, and, not | Boolean Or, Boolean And, Boolean Not | (a or b) and c |
in | "Element of" | 1 in [3, 2, 1] |
<, <=, >, >=, !=, == | The usual comparison operators | 2 <= 3 |
|, &, ^ | Bitwise Or, Bitwise And, Bitwise XOR | 6 ^ 3 |
<<, >> | Shift Operators | 6 << 3 |
Operations
Strings are bits of text. They can be defined as anything between quotes:astring = "Hello world!"
astring2 = 'Hello world!'
Below code will prints out 12, because "Hello world!" is 12 characters long, including punctuation and spaces.
astring = "Hello world!"
print len(astring)
Below code will prints out 4, because the location of the first occurrence of the letter "o" is 4 characters away from the first character. Notice how there are actually two o's in the phrase - this method only recognizes the first.
astring = "Hello world!"
print astring.index("o")
These make a new string with all letters converted to uppercase and lowercase, respectively.
astring = "Hello world!"
print astring.upper()
print astring.lower()
Conditions
For Example:
x = 2
print x == 2 # prints out True
print x == 3 # prints out False
print x < 3 # prints out True
Boolean Operators
The "and" and "or" boolean operators allow building complex boolean expressions,For Example:
name = "John"
age = 23
if name == "John" and age == 23:
print "Your name is John, and you are also 23 years old."
if name == "John" or name == "Rick":
print "Your name is either John or Rick."
True or False
Unfortunately it is not as easy in real life as it is in Python to differentiate between true and false: The following objects are evaluated by Python as False:
- numerical zero values (0, 0L, 0.0, 0.0+0.0j),
- the Boolean value False,
- empty strings,
- empty lists and empty tuples,
- empty dictionaries.
- plus the special value None.
All other values are considered to be True.
"In" Operator
The "in" operator could be used to check if a specified object exists within an iterable object container, such as a list:name = "Rick"
if name in ["John", "Rick"]:
print "Your name is either John or Rick."
Python uses indentation to define code blocks, instead of brackets. The standard Python indentation is 4 spaces, although tabs and any other space size will work, as long as it is consistent. Notice that code blocks do not need any termination.
Here is an example for using Python's "if" statement using code blocks:
if (statement is true):
(do something)
....
....
elif (another statement is true): # else if
(do something else)
....
....
else:
(do another thing)
....
....
Subscribe to:
Posts (Atom)
Online Compiler - Techie Delight TECHIE DELIGHT </> Bash (4.4) Bash (4.0) Basic (fbc 1.05.0) ...
-
Basic Operators This section explains how to use basic operators in Python. Arithmetic Operators Just as any other programming la...
-
Online Compiler - Techie Delight TECHIE DELIGHT </> Bash (4.4) Bash (4.0) Basic (fbc 1.05.0) ...
-
Conditions Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is...