whathetech Python Python Basics

# Python Basics

This is a crash course on Python. What’s different, few examples etc
Lets just get into it.

Lets write a simple code which will print if a given number if odd or even.

```import numpy as np
numbers = np.random.randint(99, size=(1, 10))
print (numbers)
for number in numbers:
print (number)
if (number % 2 == 0):
print (" Number is even")
else:
print (" Number is Odd ")
print ("Done")
```

There are many ways to generate this random, but, as you can see, we are using numpy to generate 10 random number between 10 to 99.
np.random.randint returns an list or list of numbers.
We will then iterate though the list by saying every number in numbers.
If you notice, all statements have TABS. This is important as they have special meaning. It tells to which block a code belongs to.

Now when you run this code, you will see the output which will list all the generated numbers and mention if its even or odd

Lists

```import numpy as np
numbers = np.random.randint(99, size=(1, 10))
print (len(numbers))
```

As you saw above, numpy generated a list of numbers. We will use the same to perform some operation on the list

```Slicing a list: Get the first three elements of a list
print (numbers)
Output: [23 12 49 12 91 89 45 95 81 37]
print (numbers[:4])
Output: [23 12 49 12]
Slicing a list: Get all the elements after 4
print (numbers[4:])
Output: [91 89 45 95 81 37]
Slicing a list: Get the last two elements
print (numbers[-2:])
Output: [81, 37]
Extend a list
numbers.extend([101, 102])
print (numbers)
Output: [23, 12, 49, 12, 91, 89, 45, 95, 81, 37, 101, 102]
Adding just One number:
numbers.append(109)
print (numbers)
Output: [23, 12, 49, 12, 91, 89, 45, 95, 81, 37, 101, 102, 109]
Complex Data Structure: Can have numbers, strings or even lists
x = [1,2,3]
listoflists = [x, numbers]
print (listoflists)
Output: [[1, 2, 3], [23, 12, 49, 12, 91, 89, 45, 95, 81, 37, 101, 102, 109]]
```

Tags: , , , ,