Intro to Python ? – Part 2

You can find Part 1 here.

Intro

In this part of the series we are going to cover the very basics of Python. You may be asking: “Its Python, how hard can it get ? Its just sudo code” well that is both true and false to a degree.

Variables

Python is a dynamically typed language, however it is strongly typed. This just means that you can set a variable to any sort of data type you want without declaring it first. However it doesn’t implicitly convert types for you.

# dynamic typing in action below
#Numbers
a = 5
print(a) # 5
a = 'afasdadfs'
print(a) # afasdadfs
print(2 + 10 * 10 + 3) # python follows bedmass !
#Strings
mystring = 'This is a basic string'
mystring = 'helloGoodBye'
print(mystring) # helloGoodBye
# Slicing Strings
# Strings are like char arrays
print(mystring[0])
# Slicing aka getting what you need out of them
print(mystring[2:]) # it includes everything from 2 and onwards
# output "lloGoodBye"
print(mystring[:3]) # up to but not indluding the index 3
# output "hel"
print(mystring[2:3]) # that is way the output of this is just "l"
# cause its not including the 3rd index
# output "l"
print(mystring[:]) # graps the whole string
# output "helloGoodBye"
print(mystring[::2]) # graps every second character
# starts from the very beginning, and includes the last answer in each step count
# always starts the count from Zero !
# output "hloody"
print(mystring[::3]) # graps every third character
# output "hloB"
# strings do not support char re-assignment
# mystring[0] = "t" <- does not work
# Some string methods
print(mystring.capitalize())
print(mystring.upper())
newstring = "I had a nice day today, hope tommorow is just as good"
print(newstring.split()) # if you put nothing in there, it will just split along the spaces
# you also have string interpolation
emotion = "Happy"
color = "Blue"
print("The color of the sky is making me {}. I love the {} color of the sky".format(emotion,color))
# can also do it this way as well
print("The color of the sky is making me {x}. I love the {y} color of the sky".format(x=emotion,y=color))
#booleans
# can use 0 or 1 to represent boolen values
sam = True
print(sam) # outputs "True"
max = False
print(max) # outputs "False"

view raw
Variables.py
hosted with ❤ by GitHub

Collections

Python also contains different types array like structures. And they are all get dynamically sized of course. You have Lists and Dictionaries, they all work the way you intuitively think do, coming from another programming language. The only new sort of collection type, you will encounter is the Tuple. A Tuple is pretty much the same thing as a List however they are immutable and can not contain repeats of the same value.

#LISTS
# Can have mixed data types
# lists are mutable, they can have any sort of data type, or a mixture of different data types
mylist = [1,2,3]
mylist = ['random',3,4,2,32323,True,23232323,[2,3,2]]
print(mylist) # output "['random', 3, 4, 2, 32323, True, 23232323, [2, 3, 2]]""
print(mylist[1]) # output "3"
print(mylist[:3]) # also supports slicing, also has the same rules as slicing
#output "['random', 3, 4]"
# can have assignemnts
mylist[0] = "Love you"
print(mylist) # output "['Love you', 3, 4, 2, 32323, True, 23232323, [2, 3, 2]]"
mylist.append("NewItem1") # adds a enity to the end
print(mylist) # output "['Love you', 3, 4, 2, 32323, True, 23232323, [2, 3, 2], 'NewItem1']"
# can also extend the list aka merging another list to the end
mylist.extend([1,2,3,4,22,1,4])
print(mylist) # output "['Love you', 3, 4, 2, 32323, True, 23232323, [2, 3, 2], 'NewItem1', 1, 2, 3, 4, 22, 1, 4]"
#taking things off the list
print(mylist.pop())# pop modifys the list
# output "4"
print(mylist.pop(0))# pop also taking in where you want to take something out
# output "Love you"
print(mylist) # now the list is one value short of what it used to be
# output "[3, 4, 2, 32323, True, 23232323, [2, 3, 2], 'NewItem1', 1, 2, 3, 4, 22, 1]"
print(mylist.reverse())# reverse modifys the list permenantly as well. It does not return anything
print(mylist)
# output "[1, 22, 4, 3, 2, 1, 'NewItem1', [2, 3, 2], 23232323, True, 32323, 2, 4, 3]"
mylist2 = [1,4,"55555",56,73,23,4,[1,2,3]]
print(mylist2.sort()) # by default sorts from lowest to highest. It does not return anything
print(mylist2)
# output "[1, 4, 4, 23, 56, 73, [1, 2, 3], '55555']"
#DICTIONARIES
# Key is always first, value is always second
# Have no order
# Can have different data types in other data types
my_stuff = {"key1":"Value","key2":"Value2","key3":{"123":[1,2,3]}}
print(my_stuff["key1"]) # output "Value"
print(my_stuff["key3"]["123"][0]) # output "1"
# can reassign different values to different pairs
my_stuff2 = {'lunch':'pizza'}
my_stuff2['lunch'] = 'burger'
print(my_stuff2['lunch']) # output "burger"
# tuples are "immutable" sequences
# the syntax difference between this, and a list is that it uses "()"
# rather then "[]"
t = (1,2,30,30)
print(t) # output "(1,2,3)"
#sets are unordered collections of "unique" elements
# if they are the same, then it does not include them
x = set()
x.add(1)
x.add(2)
x.add(3.4)
x.add(4)
x.add(4)
x.add(4)
x.add(5)
print(x) #output "set([1, 2, 3.4, 5, 4])"
# every time you look at them, they come in a new order
# converting a list into a set, takes out all the same numbers
converted = set([1,2,3,4,5,6,7,3,3,3,3,32,"2",2,2]) # cannot do this -> set([1,2,3,4,5,6,7,3,3,3,3,32,2,2,2,2],[12])
print(converted) # outputs "set([32, 1, 2, 3, 4, 5, 6, 7])"

view raw
Collections.py
hosted with ❤ by GitHub

Control Flow

It’s pretty basic.

x = 1
y = 1
# basic ifs
if x == y:
print("Hello")
if 2 > 1:
print("Hello as well")
# an else if is a "elif"
if 1 == 1:
print("HEY")
elif 2 == 3:
print("meh")
else:
print("YOLO")

view raw
Control_Flow.py
hosted with ❤ by GitHub

Loops

Python does not find “for” loops pythonic that is way it favors “For In” loops instead. maybe asking: “What if I just want to print something 3 times ? do I have to make a list with three elements ?” The answer is no, you can use a “generator” shown in the gists below. Python also has something called “list comprehension” its very nifty to write compact and concise code.

#For Loops
seq = [1,2,3,4,5,6,3]
for item in seq:
print(item)
dick = {"SAM":1,"FRANK":2,"Dan":3}
for it in dick:
print(it) #outputs the keys
print(dick[it]) #outputs the values
myPairs = [(1,2),(3,4),(5,6)]
for item in myPairs:
print(item) # just prints the tuples in the list
# can also be used in: tuple1,tuple2
for (tuple1, tuple2) in myPairs:
#known as unpacking tuples
print(tuple1)
print(tuple2)
#While Loops
i = 0
while i < 5:
print("i is: {}".format(i))
i = i + 1
range(0,20) # generates up to, but not including 20
# is a generator
# have to convert it to a list, to properly use it
for s in list(range(0,22)):
print("YOLO")
# also stuff like "list comprehension"
x = [1,2,3,4,5]
# your taking each value in "x" and taking the power of 2 of it
# then you putting all results into a list by using the square braces
print([num**2 for num in x])

view raw
Loops.py
hosted with ❤ by GitHub

 

You can go here to find all the relevant code, in order.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s