Tag Archives: Python tutorials

Learn Python By Example – while Statement

Hits: 12 while Statement Import the random module import random Create a variable of the true number of deaths of an event deaths = 6 Create a variable that is denotes if the while loop should keep running running = True while running is True while running: /* Create a variable that randomly create a …

Learn Python By Example – Selecting Items In A List With Filters

Hits: 1 Selecting Items In A List With Filters /* Create an list of items denoting the number of soldiers in each regiment, view the list */ regimentSize = (5345, 6436, 3453, 2352, 5212, 6232, 2124, 3425, 1200, 1000, 1211); regimentSize (5345, 6436, 3453, 2352, 5212, 6232, 2124, 3425, 1200, 1000, 1211) One-line Method This …

Learn Python By Example – Mathematical Operations

Hits: 3 Mathematical Operations Import the math module import math Display the value of pi. math.pi 3.141592653589793 Display the value of e. math.e 2.718281828459045 Sine, cosine, and tangent math.sin(2 * math.pi / 180) 0.03489949670250097 Exponent 2 ** 4, pow(2, 4) (16, 16) Absolute value abs(-20) 20 Summation sum((1, 2, 3, 4)) 10 Minimum min(3, 9, …

Learn Python By Example – Iterate Over Multiple Lists Simultaneously

Hits: 5 Iterate Over Multiple Lists Simultaneously Create Two Lists names = [‘James’, ‘Bob’, ‘Sarah’, ‘Marco’, ‘Nancy’, ‘Sally’] ages = [42, 13, 14, 25, 63, 23] Iterate Over Both Lists At Once for name, age in zip(names, ages): print(name, age) James 42 Bob 13 Sarah 14 Marco 25 Nancy 63 Sally 23   Python Example …

Learn Python By Example – Indexing And Slicing NumPy Arrays

Hits: 2 Indexing And Slicing NumPy Arrays Slicing Arrays Explanation Of Broadcasting Unlike many other data types, slicing an array into a new variable means that any chances to that new variable are broadcasted to the original variable. Put other way, a slice is a hotlink to the original array variable, not a separate and …

Learn Python By Example – How To Use Default Dictionary

Hits: 5 How To Use Default Dictionary Preliminaries import collections Create A DefaultDict Default Dicts work just like regular dictionaries, except a key is called that doesn’t have a value, a default value (note: value, not key) is supplied. /* Create a defaultdict with the default value of 0 (int’s default value is 0) */ …

Learn Python By Example – Generating Random Numbers With NumPy

Hits: 4 Generating Random Numbers With NumPy Import Numpy import numpy as np Generate A Random Number From The Normal Distribution np.random.normal() 0.5661104974399703 Generate Four Random Numbers From The Normal Distribution np.random.normal(size=4) array([-1.03175853, 1.2867365 , -0.23560103, -1.05225393]) Generate Four Random Numbers From The Uniform Distribution np.random.uniform(size=4) array([ 0.00193123, 0.51932356, 0.87656884, 0.33684494]) Generate Four Random Integers …

Learn Python By Example – Functions Vs. Generators

Hits: 3 Functions Vs. Generators Create A Function /* Create a function that */ def function(names): /* For each name in a list of names */ for name in names: /* Returns the name */ return name /* Create a variable of that function */ students = function([‘Abe’, ‘Bob’, ‘Christina’, ‘Derek’, ‘Eleanor’]) /* Run the …

Learn Python By Example – Formatting Numbers

Hits: 5 Formatting Numbers Create A Long Number annual_revenue = 9282904.9282872782 Format Number /* Format rounded to two decimal places */ format(annual_revenue, ‘0.2f’) ‘9282904.93’ /* Format with commas and rounded to one decimal place */ format(annual_revenue, ‘0,.1f’) ‘9,282,904.9’ /* Format as scientific notation */ format(annual_revenue, ‘e’) ‘9.282905e+06’ /* Format as scientific notation rounded to two …

Learn Python By Example – Flatten Lists Of Lists

Hits: 1 Flatten Lists Of Lists Create A List Of Lists /* Create a list containing three lists of names */ list_of_lists = [[‘Amy’,’Betty’,’Cathryn’,’Dana’], [‘Elizabeth’,’Fay’,’Gora’], [‘Heidi’,’Jane’,’Kayley’]] Flatten The Lists Of Lists Into A Single List /* For each element in list_of_lists, take each element in the list */ flattened_list = [i for row in list_of_lists …

Learn Python By Example – Exiting A Loop

Hits: 2 Exiting A Loop Create A List /* Create a list: */ armies = [‘Red Army’, ‘Blue Army’, ‘Green Army’] Breaking Out Of A For Loop for army in armies: print(army) if army == ‘Blue Army’: print(‘Blue Army Found! Stopping.’) break Red Army Blue Army Blue Army Found! Stopping. Notice that the loop stopped …

Learn Python By Example – Display Scientific Notation As Floats

Hits: 9 Display Scientific Notation As Floats Create Values /* Create a numbers in scientific notation */ value_scientific_notation = 6.32000000e-03 /* Create a vector of numbers in scientific notation */ vector_scientific_notation = [6.32000000e-03, 1.80000000e+01, 2.31000000e+00, 0.00000000e+00, 5.38000000e-01, 6.57500000e+00, 6.52000000e+01, 4.09000000e+00, 1.00000000e+00, 2.96000000e+02, 1.53000000e+01, 3.96900000e+02, 4.98000000e+00] Display Values As Floats /* Display value as a float …

learn Python By Example – Dictionary Basics

Hits: 5 Dictionary Basics Basics Not sequences, but mappings. That is, stored by key, not relative position. Dictionaries are mutable.   Build a dictionary via brackets unef_org = {‘name’ : ‘UNEF’, ‘staff’ : 32, ‘url’ : ‘http://unef.org’} View the variable unef_org {‘name’: ‘UNEF’, ‘staff’: 32, ‘url’: ‘http://unef.org’} Build a dict via keys who_org = {} …

Learn Python By Example – Date And Time Basics

Hits: 0 Date And Time Basics /* Import modules */ from datetime import datetime from datetime import timedelta /* Create a variable with the current time */ now = datetime.now() now datetime.datetime(2014, 5, 11, 20, 5, 11, 688051) /* The current year */ now.year 2014 /* The current month */ now.month 5 /* The current …

Learn Python By Example – Data Structure Basics

Hits: 1 Data Structure Basics Lists “A list is a data structure that holds an ordered collection of items i.e. you can store a sequence of items in a list.” – A Byte Of Python Lists are mutable. /* Create a list of countries, then print the results */ allies = [‘USA’,’UK’,’France’,’New Zealand’, ‘Australia’,’Canada’,’Poland’]; allies …

Machine Learning for Beginners in Python: How to Group Observations Using K-Means Clustering

Hits: 9 Group Observations Using K-Means Clustering Preliminaries /* Load libraries */ from sklearn.datasets import make_blobs from sklearn.cluster import KMeans import pandas as pd Create Data /* Make simulated feature matrix */ X, _ = make_blobs(n_samples = 50, n_features = 2, centers = 3, random_state = 1) /* Create DataFrame */ df = pd.DataFrame(X, columns=[‘feature_1′,’feature_2’]) …