Skip to content

Instantly share code, notes, and snippets.

@OrkunAvci
Last active January 8, 2024 06:29
Show Gist options
  • Save OrkunAvci/a00e5412de20e1f120d071d5d4f9fff2 to your computer and use it in GitHub Desktop.
Save OrkunAvci/a00e5412de20e1f120d071d5d4f9fff2 to your computer and use it in GitHub Desktop.
Python Gist

Jun 26, 2021 - Jun 28, 2021

First seven days of 100 days of code.

  • Variables
  • Input & Print Functions
  • Primitive Data Types
  • Mathematical Operations in Python
  • Strings
  • Number Manipulation and String Formatting in Python
  • Control Flow with if / else and Conditional Operators
  • Nested if statements and elif statements
  • Logical Operators
  • Random Module
  • Understanding the Offset and Appending Items to Lists
  • Index Errors and Working with Nested Lists
  • [Mini Project] Rock Paper Scissors
  • Using the for loop with Python Lists
  • for loops and the range() function
  • [Mini Project] The Fizz Buzz Job Interview Question
  • [Mini Project] Create a Password Generator
  • Defining and Calling Python Functions
  • While Loops
  • [Mini Project] Hangman

Variables

var1 = 20		#	<class 'int'>
var2 = "Text"		#	<class 'str'>
var3 = 1.5		#	<class 'float'>
var4 = []		#	<class 'list'>
var5 = {}		#	<class 'dict'>
var6 = ()		#	<class 'tuple'>

++ Tutorials point


Input & Print Functions

reply = input("Some random text here: ")
print("Your input: " + reply)	#	str + str

reply = input("Give me a number: ")
reply = int(reply)
print("My favorite number is also " + str(reply))

#	Output:
#>> Some random text here: Hex
#>> Your input: Hex
#>> Give me a number: 6
#>> My favorite number is also 6
  • Input can also output the argument string.
  • Input always returns string.
  • int() and str() can be used to interchange variable types.
  • ( “” + str_var ) is string concatenation.
  • ( “” + int_var ) is not possible.

Primitive Data Types and Mathematical Operations

#	Boolean
bool_var1 = True
bool_var2 = False
print(bool_var1 == bool_var2)	#	False
print(bool_var1 != bool_var2)	#	True
print(not bool_var2)		#	True

#	Int
int_var1 = 200
int_var2 = 100
print(int_var1 + int_var2)	#	300
print(int_var1 - int_var2)	#	100
print(int_var1 * int_var2)	#	20000
print(int_var1 / int_var2)	#	2.0 (Float)
print(int_var1 % int_var2)	#	0

#	Float
float_var1 = 65.0
float_var2 = 15.0
print(float_var1 + float_var2)	#	80.0
print(float_var1 - float_var2)	#	50.0
print(float_var1 * float_var2)	#	975.0
print(float_var1 / float_var2)	#	4.333_
print(float_var1 % float_var2)	#	5.0

Bool

  • True and False are case sensitive.
  • Not has less priority than other controls. (X == not Y) is illegal.
  • bool() can be used on other types. These return false:
    • constants defined to be false: None and False.
    • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
    • empty sequences and collections: '', (), [], {}, set(), range(0)

Operation table

Operation Result Notes Full documentation
x + y sum of x and y
x - y difference of x and y
x * y product of x and y
x / y quotient of x and y
x // y floored quotient of x and y (1)
x % y remainder of x / y (2)
-x x negated
+x x unchanged
abs(x) absolute value or magnitude of x abs()
int(x) x converted to integer (3)(6) int()
float(x) x converted to floating point (4)(6) float()
complex(re, im) a complex number with real part re, imaginary part im. im defaults to zero. (6) complex()
c.conjugate() conjugate of the complex number c
divmod(x, y) the pair (x // y, x % y) (2) divmod()
pow(x, y) x to the power y (5) pow()
x ** y x to the power y (5)

Notes:

  1. Also referred to as integer division. The resultant value is a whole integer, though the result’s type is not necessarily int. The result is always rounded towards minus infinity: 1//2 is 0, (-1)//2 is -1, 1//(-2) is -1, and (-1)//(-2) is 0.
  2. Not for complex numbers. Instead convert to floats using abs() if appropriate.
  3. Conversion from floating point to integer may round or truncate as in C; see functions math.floor() and math.ceil() for well-defined conversions.
  4. float also accepts the strings “nan” and “inf” with an optional prefix “+” or “-” for Not a Number (NaN) and positive or negative infinity.
  5. Python defines pow(0, 0) and 0 ** 0 to be 1, as is common for programming languages.
  6. The numeric literals accepted include the digits 0 to 9 or any Unicode equivalent (code points with the Nd property).

++ Python Doc


Strings

  • Ways of defining strings:
    • Single quotes: 'allows embedded "double" quotes'
    • Double quotes: "allows embedded 'single' quotes".
    • Triple quoted: '''Three single quotes''', """Three double quotes""" (This is a multi-line string)

Flags in Strings

Flag Meaning
'#' The value conversion will use the “alternate form” (where defined below).
'0' The conversion will be zero padded for numeric values.
'-' The converted value is left adjusted (overrides the '0' conversion if both are given).
' ' (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion.
'+' A sign character ('+' or '-') will precede the conversion (overrides a “space” flag).

A length modifier (h, l, or L) may be present, but is ignored as it is not necessary for Python – so e.g. %ld is identical to %d.

print('%(language)s has %(number)03d quote types.' %{'language': "Python", "number": 2})
#	Python has 002 quote types.

Conversions in Strings

Conversion Meaning Notes
'd' Signed integer decimal.
'i' Signed integer decimal.
'o' Signed octal value. (1)
'u' Obsolete type – it is identical to 'd'. (6)
'x' Signed hexadecimal (lowercase). (2)
'X' Signed hexadecimal (uppercase). (2)
'e' Floating point exponential format (lowercase). (3)
'E' Floating point exponential format (uppercase). (3)
'f' Floating point decimal format. (3)
'F' Floating point decimal format. (3)
'g' Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. (4)
'G' Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. (4)
'c' Single character (accepts integer or single character string).
'r' String (converts any Python object using repr()). (5)
's' String (converts any Python object using str()). (5)
'a' String (converts any Python object using ascii()). (5)
'%' No argument is converted, results in a '%' character in the result.

Notes:

  1. The alternate form causes a leading octal specifier ('0o') to be inserted before the first digit.

  2. The alternate form causes a leading '0x' or '0X' (depending on whether the 'x' or 'X' format was used) to be inserted before the first digit.

  3. The alternate form causes the result to always contain a decimal point, even if no digits follow it.

    The precision determines the number of digits after the decimal point and defaults to 6.

  4. The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be.

    The precision determines the number of significant digits before and after the decimal point and defaults to 6.

  5. If precision is N, the output is truncated to N characters.

  6. See PEP 237.

++ Python Doc


Number Manipulation and F Strings in Python

Number Manipulation

#	Int
x = 1
y = 35656222554887711
z = -3255522

#	Float
x = -35.59
y = 35e3
z = 12E4
k = -87.7e100

#	Complex
x = 3+5j
y = 5j
z = -5j

x = 1    # Int
y = 2.8  # Float
z = 1j   # Complex

#	Convert from int to float:
a = float(x)

#	Convert from float to int:
b = int(y)

#	Convert from int to complex:
c = complex(x)

print(a)	#	1.0
print(b)	#	2
print(c)	#	(1+0j)
print(type(a))	#	Float
print(type(b))	#	Int
print(type(c))	#	Complex

String Formatting

quantity = 3
itemno = 567
price = 49.95

myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
#	Output: I want 3 pieces of item 567 for 49.95 dollars.

myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
#	Output: I want to pay 49.95 dollars for 3 pieces of item 567.

name = 'Hex'
age = 24
print(f"Hello, My name is {name} and I'm {age} years old.")
#	Output: Hello, My name is Hex and I'm 24 years old.
  • F Strings are the shortcut to String.Format() function.

Control Flow with if / else and Conditional Operators

Conditinal Operators:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

if a > b: print("a is greater than b")

print("A") if a > b else print("B")
print("A") if a > b else print("=") if a == b else print("B")

'''
Output:
a is greater than b
a is greater than b
A
A
'''
  • Multi-line string do not generate code unless they are docstrings. Good for multi-line comments. Source

Logical Operators

Operator Description Example
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

Identity Operators

Operator Description Example
is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y

Membership Operators

Operator Description Example
in Returns True if a sequence with the specified value is present in the object x in y
not in Returns True if a sequence with the specified value is not present in the object x not in y

Bitwise Operators

Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

++ W3


Random Module

import random as rand

rand_var = rand.random()		#	Returns Float
print(rand_var)				#	0.7862125697867911

rand_var = rand.randint(0, 1000)	#	Return Int between
print(rand_var)				#	654

rand_var = rand.randrange(100)		#	Max value is the given argument
print(rand_var)				#	25
  • randint() is an alias for randrange(start, stop+1) .

++ W3


Offset and Appending Items to Lists

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[0])		#	apple
print(thislist[-1])		#	mango
print(thislist[1:4])		#	['banana', 'cherry', 'orange']
print(thislist[:4])		#	['apple', 'banana', 'cherry', 'orange']
print(thislist[2:])		#	['cherry', 'orange', 'kiwi', 'melon', 'mango']

thislist.append(15)
print(thislist)
#	Output: ['apple', 'banana', 'cherry', 'orange', 'kiwi', 'melon', 'mango', 15]

thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)
#	Output: 'apple', 'banana', 'watermelon', 'cherry']

thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
#	Output: ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']

thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)
#	Output: ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya', 'kiwi', 'orange']
  • List items are ordered, changeable, and allow duplicate values.
  • The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.
  • Lists elements can be anything. There is no set data type.
  • List.extend() takes any iterable.

++ W3


Index Errors and Working with Nested Lists

lst = [
	["element", 0, (1+3j)],
	[-12345, 13e10],
	[],
	[-85e-10],
	100000
]
print(lst)
#	Output: [['element', 0, (1+3j)], [-12345, 130000000000.0], [], [-8.5e-09], 100000]

print(lst[2][0])	#	Error. Index out of range.
print(lst[4][0])	#	Error. Index out of range.
print(lst[0][2])	#	(1+3j)
print(lst[1][1])	#	130000000000.0
print(lst[3][0])	#	-8.5e-09
print(lst[4])		#	100000
  • Python does not have built-in support for Arrays, but Lists can be used instead.

Rock Paper Scissors

import random as rand

options = ["rock", "scissors", "paper"]

user_option = input("Roll for it. ")
user_option = user_option.lower()

comp_option = options[ rand.randint(-1,2) ]
print(f"Computer has chosen {comp_option}.")

if user_option == comp_option:
	print("It is a draw!")
elif options[ options.index(user_option) - 1 ] == comp_option:
	print("Computer wins!")
else:
	print("You win!")
  • The string lower() method converts all uppercase characters in a string into lowercase characters and returns it.

For loops with lists and the range() function

fruits = ["apple", "banana", "cherry"]
for x in fruits:
	if x == "banana":
		continue
	if x == "cherry":
		break
	print(x)
else:
	print("We have reached the end.")
#	Output: apple

for x in range(6):
	print(x)
else:
	print("Finally finished!")
"""
Output:
0
1
2
3
4
5
Finally finished!
"""
  • The else block will NOT be executed if the loop is stopped by a break statement.

The FizzBuzz Question

Description of the question: “Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.” Source

for i in range(1, 100):
	x = ""
	if i % 3 == 0:
		x += "Fizz"
	if i % 5 == 0:
		x += "Buzz"
	if i % 3 != 0 and i % 5 != 0:
		x += str(i)
	print(x)


"""
Output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
...
"""

Password Generator

import random as rand
import string as str

accepted_characters = str.ascii_lowercase + str.ascii_uppercase + str.digits

request = input("Add extra fuckery? (y) or (n)")
if (request == "y"):
	accepted_characters += str.punctuation

rand_max = len(accepted_characters)

request = input("Give me the length: ")
request = int(request)

out = ""
for i in list(range(request)):
	out += accepted_characters[ rand.randint(-1, rand_max) ]

print(out)
  • String.punctuation: String of ASCII characters which are considered punctuation characters in the C locale: !"#$%&'()*+,-./:;<=>?@[\]^_``{|}~.

++ Python Docs


Defining and Calling Functions

def my_function(fname):
	print(fname + " and me")
my_function("Linux")
#	Output: Linux and me

#	Arbitrary Arguments
def arb_func(*args):
	print("Fine with " + args[0])	#	Valid
	print("Error on " + args[2])	#	Error
arb_func("Emil", "Tobias")
#	Output: Fine with Emil

#	Keyword Arguments
def kw_func(child3, child2, child1):
	print("The youngest child is " + child3)
kw_func(child1 = "Emil", child2 = "Tobias", child3 = "Linux")
#	Output: The youngest child is Linux

#	Arbitrary Keyword Arguments
def arb_kw_func(**kwargs):
	print("His last name is " + kwargs["lname"])
arb_kw_func(fname = "Tobias", lname = "Refsnes")
#	Output: His last name is Refsnes

#	Arbitrary Keyword Arguments 2
def illust(**kwargs):
    print(kwargs)
	for key, value in kwargs.items():
		print("%s is %s" % (key, value))
illust(this="random", that="valid")
"""
Output:
{'this': 'random', 'that': 'valid'}
this is random
that is valid
"""

#	Anonymous Functions
square = lambda x: x*x
print(square(5))
#	Output: 25
  • Asterisk(*): Used when the number of arguments are unknown. The function will receive a tuple of arguments, and can access the items accordingly.
  • Arbitrary Arguments are often shortened to *args in Python documentations.
  • The phrase Keyword Arguments are often shortened to kwargs in Python documentations.
  • Lambda: Lambda keyword is used to create anonymous functions.

++ W3

++ GfG


While Loops

count = 0
while count < 3:
	count = count + 1	#	There is no ++ operator.
	print("Hello Mortal")
"""
Output:
Hello Mortal
Hello Mortal
Hello Mortal
"""

a = [1, 2, 3, 4]
while a:
	print(a.pop())	#	Removes and returns the last element in list.
"""
Output:
4
3
2
1
"""

count = 0
while count < 5: count += 1; print("This is a one liner!")
"""
Output:
This is a one liner!
This is a one liner!
This is a one liner!
This is a one liner!
This is a one liner!
"""

i = 0
while i < 4:
	i += 1
	print(i)
	break
else:	#	Not executed as there is a break
	print("No Break")
"""
Output:
1
"""
  • The else block will NOT be executed if the loop is stopped by a break statement.

++ W3

++ GfG


Finished up at 17:48 on June 27, 2021.

Jun 28, 2021 - Jul 2, 2021

Days 8-14 of 100 days of code.

  • Function Outputs
  • Caesar Cipher
  • Dictionaries
  • Nesting
  • [Mini Project] Secret Auction
  • [Mini Project] Blackjack
  • Scope
  • [Mini Project] Number Guessing Game
  • [Mini Project] Higher Lower Game

Function Outputs

import time

#	Simple return
def simple(x):
	return "Function returns: '" + x + "'"

print(simple("Sent to function"))
#	Output: Function returns: 'Sent to function'

#	Return multiple
def multi_return():
	str = "Something"
	integer = 6
	return str, integer

print(multi_return())
#	Output: ('Something', 6)

#	Return function (Function factory?)
def by_factor(factor):
	def multiply(number):
		return factor * number
	return multiply

double = by_factor(2)
triple = by_factor(3)

print(double(5))	#	10
print(triple(10))	#	30

def my_timer(func):
	def _timer(*args, **kwargs):
		start = time.time()
		result = func(*args, **kwargs)
		end = time.time()
		print(f"Execution time: {end - start}")
		return result
	return _timer

@my_timer
def delayed_mean(sample):
	time.sleep(1)
	return sum(sample) / len(sample)

print(delayed_mean([10, 2, 4, 7, 9, 3, 9, 8, 6, 7]))
"""
Output:
Execution time: 1.0058274269104004
6.5
"""
  • Multiple values are returned as a tuple.
  • The syntax @my_timer above the header of delayed_mean() is equivalent to the expression delayed_mean = my_timer(delayed_mean).

++ Real Python


Caesar Cipher

Description: “In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius Caesar, who used it in his private correspondence.

The encryption step performed by a Caesar cipher is often incorporated as part of more complex schemes, such as the Vigenère cipher, and still has modern application in the ROT13 system. As with all single-alphabet substitution ciphers, the Caesar cipher is easily broken and in modern practice offers essentially no communications security.” - Wikipedia

import string as str

usable_characters = str.ascii_lowercase + str.ascii_uppercase + str.digits

def encryption(plain, offset):
	crypted = ""
	for c in plain:
		crypted += (usable_characters[ (usable_characters.index(c) - offset) % len(usable_characters) ])
	return crypted

def decryption(crypted, offset):
	plain = ""
	for c in crypted:
		plain += (usable_characters[ (usable_characters.index(c) + offset) % len(usable_characters) ])
	return plain

original = input("Enter the original string: ")
offset = int(input("Enter the offset: "))

crypted = encryption(original, offset)
print(crypted)

original = decryption(crypted, offset)
print(original)

Dictionaries

knights = {"gallahand": "the pure", "robin": "the brave"}

for k, v in knights.items():
	print(k, v)
"""
Output:
gallahand the pure
robin the brave
"""

knights["Hex"] = "the Mighty"

if "Hex" in knights:
	knights.pop("gallahand")
	for k, v in knights.items():
		print(k, v)
"""
Output:
robin the brave
Hex the Mighty
"""
  • The dict() constructor builds dictionaries directly from sequences of key-value pairs.

++ Type Mapping

++ Python Docs

++ W3


Nesting

nest = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j']

print(nest[0])			#	a
print(nest[1])			#	['bb', ['ccc', 'ddd'], 'ee', 'ff']
print(nest[1][1])		#	['ccc', 'ddd']
print(nest[1][1][1])		#	ddd
print('ddd' in nest)		#	False
print('ddd' in nest[1])		#	False
print('ddd' in nest[1][1])	#	True

#	Nested Dictionaries
myfamily = {
  "child1" : {
    "name" : "Emil",
    "year" : 2004
  },
  "child2" : {
    "name" : "Tobias",
    "year" : 2007
  },
  "child3" : {
    "name" : "Linux",
    "year" : 2011
  }
}

for reference, values in myfamily.items():
	print()
	print(reference)
	print("{")
	for key, value in values.items():
		print("	", key, ":", value)
	print("}")
"""
Output:
child1
{
	 name : Emil
	 year : 2004
}

child2
{
	 name : Tobias
	 year : 2007
}

child3
{
	 name : Linux
	 year : 2011
}
"""

++ W3

++ Real Python


Secret Auction

import random as rand

#	Taken from https://jsonplaceholder.typicode.com/posts. Modified.
items = [...]

def bid():
	print()
	alias = input("What is your alias?")
	price = int(input("Enter your bid."))
	return alias, price

for item in items:
	#	Prep
	item["mindBid"] = rand.randint(0, 1000)
	cid, id, name, desc, minBid = item.values()
	highestBidder = "No one"
	highestBid = minBid

	#	Auction
	print(f"{id}. item by {cid} with the minimum bid price of {minBid}.")
	print(name, ":", desc)
	print()
	bidder = True
	while bidder:
		alias, price = bid()
		if price > highestBid:
			highestBid = price
			highestBidder = alias
		print()
		print(f"Highest bid is {highestBid} by {highestBidder}.")
		response = input("Any bidders?('y' or 'n')")
		bidder = True if response == "y" else False

	#	Result
	print(f"{name} goes to {highestBidder} for {highestBid}.")
	print()
	print()

Blackjack

I will do this with a deck class after we go over objects.


Scope

Python resolves names using the so-called LEGB rule, which is named after the Python scope for names. The letters in LEGB stand for Local, Enclosing, Global, and Built-in. Here’s a quick overview of what these terms mean:

  • Local (or function) scope is the code block or body of any Python function or lambda expression. This Python scope contains the names that you define inside the function. These names will only be visible from the code of the function. It’s created at function call, not at function definition, so you’ll have as many different local scopes as function calls. This is true even if you call the same function multiple times, or recursively. Each call will result in a new local scope being created.
  • Enclosing (or nonlocal) scope is a special scope that only exists for nested functions. If the local scope is an inner or nested function, then the enclosing scope is the scope of the outer or enclosing function. This scope contains the names that you define in the enclosing function. The names in the enclosing scope are visible from the code of the inner and enclosing functions.
  • Global (or module) scope is the top-most scope in a Python program, script, or module. This Python scope contains all of the names that you define at the top level of a program or a module. Names in this Python scope are visible from everywhere in your code.
  • Built-in scope is a special Python scope that’s created or loaded whenever you run a script or open an interactive session. This scope contains names such as keywords, functions, exceptions, and other attributes that are built into Python. Names in this Python scope are also available from everywhere in your code. It’s automatically loaded by Python when you run a program or script.

The LEGB rule is a kind of name lookup procedure, which determines the order in which Python looks up names. For example, if you reference a given name, then Python will look that name up sequentially in the local, enclosing, global, and built-in scope. If the name exists, then you’ll get the first occurrence of it. Otherwise, you’ll get an error.

++ Real Python


Number Guessing Game

import random
import math

#	Limits
lower = int(input("Enter Lower bound:- "))
upper = int(input("Enter Upper bound:- "))

#	Prep
generated = random.randint(lower, upper)
expected = math.ceil(math.log(upper - lower + 1, 2))
guesses = 0
guess = lower - 1

#	Game
while generated != guess:
	guess = int(input("Guess a number:- "))
	guesses += 1
	print()
	if generated > guess:
		print(f"Go higher than {guess}.")
	elif generated < guess:
		print(f"Go lower than {guess}.")

#	Result
print(f"Expected guess count was {expected}.")
print(f"You found the number {guess} in {guesses} guesses.")

++ GfG


Higher Lower Game

Description: Ask the question “Which one has more followers?”. Let users choose between two different Instagram accounts. Correct guesses continue the streak, wrong one ends the game.

Ideally this project is done with calls to the Instagram API which is out of scope at this point. This is abandoned for me.


Finished at 16:08 on July 1, 2021.

Jul 2, 2021 - Jun 7, 2021

Day 15-21 of 100 days of code.

  • Looping Techniques
  • Object Oriented Programming
  • [Mini Project] Quiz Project
  • [Mini Project] Blackjack
  • Turtle
  • State and Higher Order Functions
  • [Mini Project] Snake Game

Looping Techniques

# initializing list
questions = ['name', 'colour', 'shape']
answers = ['apple', 'red', 'a circle']

# using zip() to combine two containers and print values
for question, answer in zip(questions, answers):
	print('What is your {0}?  I am {1}.'.format(question, answer))

dic = {"Key1": "Value1", "Key2": "Value2"}

# using items to print the dictionary key-value pair
print("The key value pair using items is : ")
for i, j in dic.items():
	print(i ,j)

kings = {'Akar': 'The Great', 'Chandragupta': 'The Maurya',
		'Modi': 'The Changer'}

# using items to print the dictionary key-value pair
for key, value in kings.items():
	print(key, value)

# initializing list
lis = [1, 3, 5, 6, 2, 1, 3]

# using sorted() to print the list in sorted order
print("The list in sorted order is : ")
for i in sorted(lis):
	print(i, end=" ")

# using sorted() and set() to print the list in sorted order use of set() removes duplicates.
print("The list in sorted order (without duplicates) is : ")
for i in sorted(set(lis)):
	print(i, end=" ")

# using revered() to print the list in reversed order
print("The list in reversed order is : ")
for i in reversed(lis):
	print(i, end=" ")

colors = ['red','green','blue']
for color in enumerate(colors):
	print (color)

"""
Output (All):
What is your name?  I am apple.
What is your colour?  I am red.
What is your shape?  I am a circle.
The key value pair using items is : 
Key1 Value1
Key2 Value2
Akar The Great
Chandragupta The Maurya
Modi The Changer
The list in sorted order is : 
1 1 2 3 3 5 6 
The list in sorted order (without duplicates) is : 
1 2 3 5 6 
The list in reversed order is : 
3 1 2 6 5 3 1 
(0, 'red')
(1, 'green')
(2, 'blue')
"""
  • zip() : Combines two containers.
  • dict.items(): Return a copy of the dictionary’s list of (key, value) pairs.
  • dict.iteritems(): This has been deprecated and the new syntax is iter(dict.items()).
  • set(): Turns collections into sets. A set is a collection which is both unordered and unindexed. Set items are unordered, unchangeable, and do not allow duplicate values.

++ GfG

++ Python Dev

++ W3


Object Oriented Programming

Overview of OOP Terminology

  • Class − A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.
  • Class variable − A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables are not used as frequently as instance variables are.
  • Data member − A class variable or instance variable that holds data associated with a class and its objects.
  • Function overloading − The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects or arguments involved.
  • Instance variable − A variable that is defined inside a method and belongs only to the current instance of a class.
  • Inheritance − The transfer of the characteristics of a class to other classes that are derived from it.
  • Instance − An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle.
  • Instantiation − The creation of an instance of a class.
  • Method − A special kind of function that is defined in a class definition.
  • Object − A unique instance of a data structure that's defined by its class. An object comprises both data members (class variables and instance variables) and methods.
  • Operator overloading − The assignment of more than one function to a particular operator.
class Employee:
	'Common base class for all employees'
	empCount = 0

	def __init__(self, name, salary):
		self.name = name
		self.salary = salary
		Employee.empCount += 1

	def displayCount(self):
		print("Total Employee %d" % Employee.empCount)

	def displayEmployee(self):
		print("Name : ", self.name, ", Salary: ", self.salary)

print("Employee.__doc__:", Employee.__doc__)
print("Employee.__name__:", Employee.__name__)
print("Employee.__module__:", Employee.__module__)
print("Employee.__bases__:", Employee.__bases__)
print("Employee.__dict__:", Employee.__dict__)

"""
Output:
Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: (<class 'object'>,)
Employee.__dict__: {
'__module__': '__main__',
'__doc__': 'Common base class for all employees',
'empCount': 0,
'__init__': <function Employee.__init__ at 0x000001E2396D7DC0>,
'displayCount': <function Employee.displayCount at 0x000001E2396D7E50>, 'displayEmployee': <function Employee.displayEmployee at 0x000001E2396D7EE0>, '__dict__': <attribute '__dict__' of 'Employee' objects>,
'__weakref__': <attribute '__weakref__' of 'Employee' objects>
}
"""

class Point:
	def __init__( self, x=0, y=0):
		self.x = x
		self.y = y
	def __del__(self):
		class_name = self.__class__.__name__
		print(class_name, "destroyed")

pt1 = Point()
pt2 = pt1
pt3 = pt1
print(id(pt1), id(pt2), id(pt3))	#	Prints the ids of the objects
del pt1
del pt2
del pt3

"""
Output:
2071137718672 2071137718672 2071137718672
Point destroyed
"""

Built-In Class Attributes

  • dict − Dictionary containing the class's namespace.
  • doc − Class documentation string or none, if undefined.
  • name − Class name.
  • module − Module name in which the class is defined. This attribute is "main" in interactive mode.
  • bases − A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.

Built-in Functions

  • The getattr(obj, name[, default]) − to access the attribute of object.
  • The hasattr(obj,name) − to check if an attribute exists or not.
  • The setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it would be created.
  • The delattr(obj, name) − to delete an attribute.

Class Relation Functions

  • The issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a subclass of the superclass sup.
  • The isinstance(obj, Class) boolean function returns true if obj is an instance of class Class or is an instance of a subclass of Class
class Parent:	# define parent class
	parentAttr = 100
	def __init__(self):
		print("Calling parent constructor")

	def parentMethod(self):
		print('Calling parent method')

	def setAttr(self, attr):
		Parent.parentAttr = attr

	def getAttr(self):
		print("Parent attribute :", Parent.parentAttr)

class Child(Parent): # define child class
	def __init__(self):
		print("Calling child constructor")

	def childMethod(self):
		print("Calling child method")

c = Child()          # instance of child
c.childMethod()      # child calls its method
c.parentMethod()     # calls parent's method
c.setAttr(200)       # again call parent's method
c.getAttr()          # again call parent's method

"""
Output:
Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200
"""

Base Overloading Methods

Sr.No. Method & Description
1 init ( self [,args...] ) : Constructor (with any optional arguments)
2 del( self ) : Destructor, deletes an object
3 repr( self ) : Evaluable string representation
4 str( self ) : Printable string representation
5 cmp ( self, x ) : Object comparison

Data Hiding

class JustCounter:
	__secretCount = 0
  
	def count(self):
		self.__secretCount += 1
		print(self.__secretCount)

counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount	#	Error.

"""
Output:
1
2
AttributeError: 'JustCounter' object has no attribute '__secretCount'
"""
  • Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName.
  • In this case counter._JustCounter__secretCount would refer to the __secretCount.

++ Tutorials Point

++ Real Python

++ Programiz


Quiz Game

import requests as req

res = req.get("https://opentdb.com/api.php?amount=20&category=9&type=boolean")
data = res.json()["results"]

for entry in data:
	print("Difficulty: ", entry["difficulty"])
	print(entry["question"])
	answer = input("True or False? ")
	if answer == entry["correct_answer"]:
		print("Correct!")
	else:
		print("Correct answer was", entry["correct_answer"])
	print()
  • request library requires pip install request to be run in the environment terminal. Another was is to put it into a requirements.txt file and simply call pip install.
  • Response from the API includes http transaction information. json() turns it into a dict and ["result"] takes the data we actually wanted.

++ Nylas

++ Open Trivia Database / API


Blackjack

#	Deck Class:
import random as rand

class deck:
	cards = [{}]

	def __init__(self):
		for type in ["clubs", "diamonds", "hearts", "spades"]:
			for value in range(2,11):
				self.cards.append({
					"type" : type,
					"name" : str(value),
					"value" : value
				})
			self.cards.append({"type": type, "name": "Ace", "value": 11})
			self.cards.append({"type": type, "name": "King", "value": 10})
			self.cards.append({"type": type, "name": "Queen", "value": 10})
			self.cards.append({"type": type, "name": "Jack", "value": 10})

	def draw(self):
		drawn = self.cards.pop(rand.randrange(0, len(self.cards)))
		print(f"{drawn['name']} of {drawn['type']} has been drawn!")
		return drawn

	def reset(self):
		self.__init__()
#	Main Script:
from Blackjack_Deck import deck

def play_blackjack():
	active_deck = deck()
    computer = active_deck.draw()["value"]
	player = active_deck.draw()["value"]
	print("Computer is at", computer)
	print("You are at", player)
	res = True
	while res and player <= 21:
		res = True if input("Draw another card?(y or n)") == "y" else False
		if res:
			player += active_deck.draw()["value"]
			print("You are at", player)
	if player > 21:
		print("You lost!")
		return
	while player > computer <= 21:
		computer += active_deck.draw()["value"]
		print("Computer is at", computer)
	if computer > 21:
		print("Computer went overboard! You won!")
		return
	else:
		print("You lost!")

if __name__ == "__main__":
	res = True
	while res:
		play_blackjack()
		res = True if input("Play again?(y or n)") == "y" else False
		print()
		print()
		print()

Turtle

import math
import turtle

window = turtle.Screen()
window.title("First Turtle Program")
tur = turtle.Turtle()

tur.begin_fill()
tur.circle(60)
tur.end_fill()

turtle.bgcolor("blue")
turtle.pencolor("purple")
tur.pensize(2)

tur.speed(1)
tur.fillcolor("red")
tur.begin_fill()
tur.forward(128)
tur.right(90)
tur.forward(128)
tur.right(135)
tur.forward(math.sqrt(2) * 128)
tur.end_fill()

tur.speed(10)
tur.fillcolor("purple")
tur.begin_fill()
tur.left(45)
tur.forward(128)
tur.left(90)
tur.forward(128)
tur.home()
tur.end_fill()

tur.right(90)
tur.stamp()
tur.forward(128)
tur.stamp()
tur.right(90)

for i in range(0, 5):
	tur.circle(i * 20)

turtle.done()

Methods

Method Parameter Description
Turtle() None Creates and returns a new turtle object
forward() amount Moves the turtle forward by the specified amount
backward() amount Moves the turtle backward by the specified amount
right() angle Turns the turtle clockwise
left() angle Turns the turtle counter clockwise
penup() None Picks up the turtle’s Pen
pendown() None Puts down the turtle’s Pen
up() None Picks up the turtle’s Pen
down() None Puts down the turtle’s Pen
color() Color name Changes the color of the turtle’s pen
fillcolor() Color name Changes the color of the turtle will use to fill a polygon
heading() None Returns the current heading
position() None Returns the current position
goto() x, y Move the turtle to position x,y
begin_fill() None Remember the starting point for a filled polygon
end_fill() None Close the polygon and fill with the current fill color
dot() None Leave the dot at the current position
stamp() None Leaves an impression of a turtle shape at the current location
shape() shapename Should be ‘arrow’, ‘classic’, ‘turtle’ or ‘circle’

++ Real Python

++ Python Docs

++ GfG


State and Higher Order Functions

State

  • State is a behavioral design pattern that allows an object to change the behavior when its internal state changes. The pattern extracts state-related behaviors into separate state classes and forces the original object to delegate the work to an instance of these classes, instead of acting on its own.
#	State_Classes.py
class ComputerState(object):
	name = "state"
	allowed_states = []

	def switch(self, state):
		""" Switch to new state """
		if state.name in self.allowed_states:
			print('Current:', self, ' => switched to new state', state.name)
			self.__class__ = state
		else:
			print('Current:', self, ' => switching to', state.name, 'not possible.')

	def __str__(self):
		return self.name


class Off(ComputerState):
	name = "off"
	allowed_states = ['on']


class On(ComputerState):
	""" State of being powered on and working """
	name = "on"
	allowed_states = ['off', 'suspend', 'hibernate']


class Suspend(ComputerState):
	""" State of being in suspended mode after switched on """
	name = "suspend"
	allowed_states = ['on']


class Hibernate(ComputerState):
	""" State of being in hibernation after powered on """
	name = "hibernate"
	allowed_states = ['on']


class Computer(object):
	""" A class representing a computer """

	def __init__(self, model='HP'):
		self.model = model
		# State of the computer - default is off.
		self.state = Off()

	def change(self, state):
		""" Change state """
		self.state.switch(state)
      
#	State.py
from State_Classes import *

if __name__ == "__main__":
	comp = Computer()
	comp.change(On)
	comp.change(Off)
	comp.change(On)
	comp.change(Suspend)
	comp.change(Hibernate)
	comp.change(On)
	comp.change(Off)
"""
Output:
Current: off  => switched to new state on
Current: on  => switched to new state off
Current: off  => switched to new state on
Current: on  => switched to new state suspend
Current: suspend  => switching to hibernate not possible.
Current: suspend  => switched to new state on
Current: on  => switched to new state off
"""

Higher Order Functions

  • A function is called Higher Order Function if it contains other functions as a parameter or returns a function as an output i.e, the functions that operate with another function are known as Higher order Functions. It is worth knowing that this higher order function is applicable for functions and methods as well that takes functions as a parameter or returns a function as a result. Python too supports the concepts of higher order functions.

    Properties of higher-order functions:

    • A function is an instance of the Object type.
    • You can store the function in a variable.
    • You can pass the function as a parameter to another function.
    • You can return the function from a function.
    • You can store them in data structures such as hash tables, lists, …
#	Higher Order Functions.py
def shout():
	return "This is returned from a function.".upper()

def whisper():
	return "This is returned from a function.".lower()

def greet(get_str):
	greeting = get_str()
	print(greeting)

greet(shout)
greet(whisper)

"""
Output:
THIS IS RETURNED FROM A FUNCTION.
this is returned from a function.
"""

++ Tutorials Point

++ GfG State

++ GfG Higher Order Functions

++ Composing Programs


Failed to finish in time. Snake Game is missing.

Jun 7, 2021 - Jun 14, 2021

Day 22-29 of 100 days of code.

  • [Mini Project] Pong Game
  • [Mini Project] Turtle Crossing Game
  • Files, Directories and Paths
  • Relative and Absolute File Paths
  • [Mini Project] Mail Merge Challenge
  • Reading CSV Data in Python
  • Pandas Library
  • Data Frames & Series
  • List Comprehension, Dictionary Comprehension
  • Iterate over a Pandas Data Frame
  • [Mini Project] NATO Alphabet Project
  • TKinter
  • [Mini Project] Mile to Kilometers Converter Project
  • Dynamic Typing

[Mini Project] Pong Game

import turtle
import keyboard

from Ball import Ball
from Scoreboard import Scoreboard
from Plate import Plate

if __name__ == "__main__":
	window = turtle.Screen()
	window.title("Pong Game")
	window.bgcolor("black")
	scoreboard = Scoreboard()
	player = Plate(1)
	computer = Plate(-1)	#	No AI for you.
	ball = Ball()
	while True:
		ball.move()
		try:
			if keyboard.is_pressed("w"):
				player.move("w")
			elif keyboard.is_pressed("s"):
				player.move("s")
		except:
			pass
		if abs(ball.xcor() - player.xcor()) < 5 or abs(ball.xcor() - computer.xcor()) < 5:
			ball.collide()
	turtle.done()
  • Other files are in the same directory and can be examined here: Github

[Mini Project] Turtle Crossing Game

import turtle
import keyboard

from Car import Car
from Player import Player

if __name__ == "__main__":
	window = turtle.Screen()
	window.bgcolor("black")
	player = Player()
	player.goto(0, -200)
	player.left(90)
	cars = []
	for i in range(5):
		cars.append([])
		for j in range(5):
			car = Car()
			car.goto(-400 + (j * 200),-100 + (i * 50))
			if i % 2 == 0:
				car.left(180)
			cars[i].append(car)
	while player.ycor() < 200:
		for line in cars:
			for car in line:
				car.move()
		try:
			if keyboard.is_pressed("w"):
				player.move("w")
			elif keyboard.is_pressed("s"):
				player.move("s")
		except:
			pass
	turtle.done()
  • Other files are in the same directory and can be examined here: Github

Files Directories and Paths

There is far too much to unpack here. Also os.path doesn’t make much sense before we go over os library. So here are some notes and main links. Python Docs go in deep.

  • Python lets you use OS-X/Linux style slashes "/" even in Windows. Therefore, you can refer to the file as 'C:/Users/narae/Desktop/alice.txt'. This is the recommended way.
  • If using a backslash, because it is a special character in Python, you must remember to escape every instance: 'C:\\Users\\narae\\Desktop\\alice.txt'
  • Alternatively, you can prefix the entire file name string with the rawstring marker "r": r'C:\Users\narae\Desktop\alice.txt'. That way, everything in the string is interpreted as a literal character, and you don't have to escape every backslash.

++ Python Docs

++ Real Python

++ Notes by Na-Rae Han


Relative and Absolute File Paths

  • CWD = Current Working Directory.

../_images/pathlib-inheritance.png

from pathlib import Path
import os

github = Path("/Github")
me = github / "Codes From Courses" / "Python" / "Session 4" / "Paths.py"
print(me)
print(me.resolve())
print(me.exists())
print(me.is_dir())

print(os.getcwd())
os.chdir(github)
print(os.getcwd())
os.chdir("Codes From Courses/Python/Session 3")
print(os.getcwd())
"""
Output:
\Github\Codes From Courses\Python\Session 4\Paths.py
D:\GitHub\Codes From Courses\Python\Session 4\Paths.py
True
False

D:\GitHub\Codes From Courses\Python\Session 4
D:\Github
D:\Github\Codes From Courses\Python\Session 3
"""

Mail Merge Challenge

template = """
Dear {name}
As you may know, 2010 marks our {year} years of doing business. Over the last decade, AdWorks has grown from a tiny startup into a robust company with over 200 employees throughout the Southeast. Our growth would not have been possible without loyal customers like you. Therefore, we would like to extend to you a {discount}% discount on your next order. It’s our way of saying “thanks" for your continued business. We’ll keep working hard to provide the best possible customer service along with innovative products, just as we’ve always done. Thanks again for choosing AdWorks!
Sincerely,

Liz Doe
President and CEO
"""	#	Taken from https://edu.gcfglobal.org/en/word2010/using-mail-merge/1/

recipients = [
	{
		"name": "Someone",
		"year": 5,
		"discount": 10
	},
	{
		"name": "Some other one",
		"year": 8,
		"discount": 20
	}
]

def	create(info):
	return template.format(name=info["name"], year=info["year"], discount=info["discount"])

if __name__ == "__main__":
	for info in recipients:
		print(create(info))
"""
Output:
Dear Someone
As you may know, 2010 marks our 5 years of doing business. Over the last decade, AdWorks has grown from a tiny startup into a robust company with over 200 employees throughout the Southeast. Our growth would not have been possible without loyal customers like you. Therefore, we would like to extend to you a 10% discount on your next order. It’s our way of saying “thanks" for your continued business. We’ll keep working hard to provide the best possible customer service along with innovative products, just as we’ve always done. Thanks again for choosing AdWorks!
Sincerely,

Liz Doe
President and CEO

Dear Some other one
As you may know, 2010 marks our 8 years of doing business. Over the last decade, AdWorks has grown from a tiny startup into a robust company with over 200 employees throughout the Southeast. Our growth would not have been possible without loyal customers like you. Therefore, we would like to extend to you a 20% discount on your next order. It’s our way of saying “thanks" for your continued business. We’ll keep working hard to provide the best possible customer service along with innovative products, just as we’ve always done. Thanks again for choosing AdWorks!
Sincerely,

Liz Doe
President and CEO
"""

Reading CSV Data in Python

Data.csv

Name Age Profession
Jack 23 Doctor
Miller 22 Engineer
import csv

with open("data.csv", "r") as file:
	data = csv.reader(file, quoting=csv.QUOTE_ALL, skipinitialspace=True)
	for row in data:
		print(row)
"""
Output:
['Name', 'Age', 'Profession']
['Jack', '23', 'Doctor']
['Miller', '22', 'Engineer']
"""

#	Or we can register our own dialect:
with open("data.csv", "r") as file:
	csv.register_dialect('my_dialect', delimiter=',', skipinitialspace=True, quoting=csv.QUOTE_ALL)
	data = csv.reader(file, dialect="my_dialect")
	for row in data:
		print(row)
"""
Output:
['Name', 'Age', 'Profession']
['Jack', '23', 'Doctor']
['Miller', '22', 'Engineer']
"""

#	csv.DictReader
with open("data.csv", "r") as file:
	data = csv.DictReader(file)
	for row in data:
		print(row)
"""
Output:
{'Name': 'Jack', ' Age': ' 23', ' Profession': ' "Doctor"'}
{'Name': 'Miller', ' Age': ' 22', ' Profession': ' "Engineer"'}
"""

#	Sniffer
with open('data.csv', 'r') as file:
	sample = file.read(64)	#	Argument is the number of bytes to return.
	print(csv.Sniffer().has_header(sample))
	deduced_dialect = csv.Sniffer().sniff(sample)

with open('data.csv', 'r') as file:
	reader = csv.reader(file, deduced_dialect)
	for row in reader:
		print(row)
"""
Output:
True
['Name', 'Age', 'Profession']
['Jack', '23', 'Doctor']
['Miller', '22', 'Engineer']
"""
  • Starting from Python 3.8, csv.DictReader() returns a dictionary for each row, and we do not need to use dict() explicitly.

  • The full syntax of the csv.DictReader() class is:

    csv.DictReader(file, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)
  • In Sniffer, has_header(file) function returns True or False based on analyzing whether the sample CSV has the first row as column headers.

  • Sniffer doesn’t catch onto the space after the data entry and before the delimeter.

++ Python Docs

++ Real Python

++ Programiz


Pandas Library

Wikipedia: “pandas is a software library written for the Python programming language for data manipulation and analysis. In particular, it offers data structures and operations for manipulating numerical tables and time series. It is free software released under the three-clause BSD license.[2] The name is derived from the term "panel data", an econometrics term for data sets that include observations over multiple time periods for the same individuals.[3] Its name is a play on the phrase "Python data analysis" itself.[4] Wes McKinney started building what would become pandas at AQR Capital while he was a researcher there from 2007 to 2010.[5]” -Source

++ Pandas Docs

++ Wikipedia

++ Pandas Github Repo


Pandas Data Frame and Series

import pandas as pd

dummy = {
	'cars': ["BMW", "Volvo", "Ford"],
	'passings': [3, 7, 2]
}
dataframe = pd.DataFrame(dummy)
print(dataframe)
"""
Output:
    cars  passings
0    BMW         3
1  Volvo         7
2   Ford         2
"""

dummy = [1, 7, 2]
series = pd.Series(dummy, index = ["x", "y", "z"])
print(series)
"""
Output:
x    1
y    7
z    2
dtype: int64
"""

#	Loc is short for Locate.
print(dataframe.loc[0])
"""
Output:
cars        BMW
passings      3
Name: 0, dtype: object
"""

#	Can take lists as argument.
print(dataframe.loc[range(2)])
"""
Output:
    cars  passings
0    BMW         3
1  Volvo         7
"""

dataframe = pd.read_csv("./CSV/data.csv")
print(dataframe)
"""
Output:
     Name   Age   Profession
0    Jack    23     "Doctor"
1  Miller    22   "Engineer"
"""

print(dataframe.info())
"""
Output:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2 entries, 0 to 1
Data columns (total 3 columns):
 #   Column       Non-Null Count  Dtype 
---  ------       --------------  ----- 
 0   Name         2 non-null      object
 1    Age         2 non-null      int64 
 2    Profession  2 non-null      object
dtypes: int64(1), object(2)
memory usage: 176.0+ bytes
None
"""
  • Pandas use the loc attribute to return one or more specified row(s).
  • When using [], the result is a Pandas DataFrame.
  • pd.read_csv, needs , separated csv files to work properly.
  • pd.read_json exists and does the same for JSON files.

++ W3


List Comprehension and Dictionary Comprehension

#	Dict:
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# Double of each value in the dictionary
double_values = {k: v*2 for (k, v) in dict1.items()}
print(double_values)
#	Output: {'a': 2, 'b': 4, 'c': 6, 'd': 8, 'e': 10}

double_keys = {k*2:v for (k, v) in dict1.items()}
print(double_keys)
#	Output: {'aa': 1, 'bb': 2, 'cc': 3, 'dd': 4, 'ee': 5}

numbers = range(10)
squares = {n: n**2 for n in numbers if n % 2 == 0}	#	Turns into a dict.
print(squares)
#	Output: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

fahrenheit = {'t1': -30, 't2': -20, 't3': -10, 't4': 0}
celsius = list(map(lambda x: (float(5) / 9) * (x - 32), fahrenheit.values()))
celsius_dict = dict(zip(fahrenheit.keys(), celsius))
print(celsius_dict)
#	Output: {'t1': -34.44444444444444, 't2': -28.88888888888889, 't3': -23.333333333333336, 't4': -17.77777777777778}

#	Or:
celsius = {k: (float(5) / 9) * (v - 32) for (k, v) in fahrenheit.items()}
print(celsius_dict)
#	Output: {'t1': -34.44444444444444, 't2': -28.88888888888889, 't3': -23.333333333333336, 't4': -17.77777777777778}

#	Multiple Conditions:
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
dict1_triple_cond = {k: v for (k, v) in dict1.items() if v > 2 if v % 2 == 0 if k != "d"}
print(dict1_triple_cond)
#	Output: {'f': 6}

even_odd = {k: ('even' if v % 2 == 0 else 'odd') for (k, v) in dict1.items()}
print(even_odd)
#	Output: {'a': 'odd', 'b': 'even', 'c': 'odd', 'd': 'even', 'e': 'odd', 'f': 'even'}

#	List:
list1 = [i * i for i in range(1, 11)]
print(list1)
#	Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

#	Using filter function
evennumbers = filter(lambda x: x % 2 == 0, range(1, 11))
#	filter() returns an iterator.
print(list(evennumbers))
#	Output: [2, 4, 6, 8, 10]

list1 = map(lambda x: x * x, range(1, 11))
#Returns an iterator(map object)
print(list(list1))
#	Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

list_nested = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
list_plain = [num_inner for list_inner in list_nested for num_inner in list_inner]
print(list_plain)
#	Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

divisible_by_six = [num for num in range(13) if num % 2 == 0 if num % 3 == 0]
print(divisible_by_six)
#	Output: [0, 6, 12]

l1 = [[num for num in range(10) if num % 2 == 0] for inner_list_index in range(3)]
print(l1)
#	Output:[[0, 2, 4, 6, 8], [0, 2, 4, 6, 8], [0, 2, 4, 6, 8]]

++ Python Docs

++ DataCamp

++ Medium Blog Post

++ Real Python


Iterate over a Pandas Data Frame

import pandas as pd

data = {'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka'],
		'Age': [21, 19, 20, 18],
		'Stream': ['Math', 'Commerce', 'Arts', 'Biology'],
		'Percentage': [88, 92, 95, 70]
}

df = pd.DataFrame(data, columns = ['Name', 'Age', 'Stream', 'Percentage'])
print("Given Dataframe :\n", df)
"""
Output:
Given Dataframe :
         Name  Age    Stream  Percentage
0      Ankit   21      Math          88
1       Amit   19  Commerce          92
2  Aishwarya   20      Arts          95
3   Priyanka   18   Biology          70
"""

print("\nIterating over rows using index attribute :")
for i in df.index:
	print(df['Name'][i], df['Stream'][i])
"""
Output:
Iterating over rows using index attribute :
Ankit Math
Amit Commerce
Aishwarya Arts
Priyanka Biology
"""

print("\nIterating over rows using loc function :")
for i in range(len(df)):
	print(df.loc[i, "Name"], df.loc[i, "Age"])
"""
Output:
Iterating over rows using loc function :
Ankit 21
Amit 19
Aishwarya 20
Priyanka 18
"""

print("\nIterating over rows using iloc function :")
for i in range(len(df)) :
	print(df.iloc[i, 0], df.iloc[i, 2])
"""
Output:
Iterating over rows using iloc function :
Ankit Math
Amit Commerce
Aishwarya Arts
Priyanka Biology
"""

print("\nIterating over rows using iterrows() method :")
for index, row in df.iterrows():
	print(row["Name"], row["Age"])
"""
Output:
Iterating over rows using iterrows() method :
Ankit 21
Amit 19
Aishwarya 20
Priyanka 18
"""

print("\nIterating over rows using itertuples() method :")
for row in df.itertuples(index=True, name='Pandas'):
	print(getattr(row, "Name"), getattr(row, "Percentage"))
"""
Output:
Iterating over rows using itertuples() method :
Ankit 88
Amit 92
Aishwarya 95
Priyanka 70
"""

print("\nIterating over rows using apply function :")
print(df.apply(lambda row: row["Name"] + " " + str(row["Percentage"]), axis=1))

"""
Output:
Iterating over rows using apply function :
0        Ankit 88
1         Amit 92
2    Aishwarya 95
3     Priyanka 70
dtype: object
"""
  • List Comprehension should be preferred over apply or iteritems.
  • vec over vec_numpy. (From Stackoverflow answer)

img

++ GfG

++ Stackoverflow Discussion


NATO Project

import string
import pandas as pd

data = pd.read_csv("nato_phonetic_alphabet.csv")

dict_form = {}
for entry in data.values:
	dict_form[entry[0]] = entry[1]

plain = input("Give me a string: ")

codes = [dict_form[ch.upper()] for ch in plain if ch.upper() in string.ascii_uppercase]
coded = " ".join(codes)
print(coded)

Tkinter

  • Stands for TK Interface.

Widgets

Sr.No. Operator & Description
1 Button - The Button widget is used to display buttons in your application.
2 Canvas - The Canvas widget is used to draw shapes, such as lines, ovals, polygons and rectangles, in your application.
3 Checkbutton - The Checkbutton widget is used to display a number of options as checkboxes. The user can select multiple options at a time.
4 Entry - The Entry widget is used to display a single-line text field for accepting values from a user.
5 Frame - The Frame widget is used as a container widget to organize other widgets.
6 Label - The Label widget is used to provide a single-line caption for other widgets. It can also contain images.
7 Listbox - The Listbox widget is used to provide a list of options to a user.
8 Menubutton - The Menubutton widget is used to display menus in your application.
9 Menu - The Menu widget is used to provide various commands to a user. These commands are contained inside Menubutton.
10 Message - The Message widget is used to display multiline text fields for accepting values from a user.
11 Radiobutton - The Radiobutton widget is used to display a number of options as radio buttons. The user can select only one option at a time.
12 Scale - The Scale widget is used to provide a slider widget.
13 Scrollbar - The Scrollbar widget is used to add scrolling capability to various widgets, such as list boxes.
14 Text - The Text widget is used to display text in multiple lines.
15 Toplevel - The Toplevel widget is used to provide a separate window container.
16 Spinbox - The Spinbox widget is a variant of the standard Tkinter Entry widget, which can be used to select from a fixed number of values.
17 PanedWindow - A PanedWindow is a container widget that may contain any number of panes, arranged horizontally or vertically.
18 LabelFrame - A LabelFrame is a simple container widget. Its primary purpose is to act as a spacer or container for complex window layouts.
19 tkMessageBox - This module is used to display message boxes in your applications.

Standard Attributes

Geometry Management

  • The pack() Method − This geometry manager organizes widgets in blocks before placing them in the parent widget.
  • The grid() Method − This geometry manager organizes widgets in a table-like structure in the parent widget.
  • The place() Method − This geometry manager organizes widgets by placing them in a specific position in the parent widget.
import tkinter

def print_input(event):
	print(entry.get())

def reset(event):
	str_input = entry.get()
	entry.delete(0, tkinter.END)
	entry.insert(0, f"Input taken was: {str_input}")

window = tkinter.Tk()
greeting = tkinter.Label(text="Hello, Tkinter", foreground="white", background="#34A2FE", width=100, height=25)   #   Or just fg= and bg=
greeting.pack()

entry = tkinter.Entry(fg="black", bg="white", width=50)
entry.bind("<Return>", print_input)
entry.pack()

button = tkinter.Button(text="Click me!", width=25, height=5, bg="blue", fg="yellow")
button.bind("<Button>", reset)
button.pack()

window.mainloop()

++ Python Docs Tk

++ Python Docs Tkinter

++ Real Python


[Mini Project] Mile to Kilometers Converter Project

import tkinter

def convert_mile(event):
	miles = int(mile.get())
	kilometer.delete(0, tkinter.END)
	kilometer.insert(0, str(miles * 1.6))

def convert_kilometer(event):
	kilometers = int(kilometer.get())
	mile.delete(0, tkinter.END)
	mile.insert(0, str(kilometers / 1.6))

window = tkinter.Tk()

instrunctions = tkinter.Label(text="Enter a number and press Enter to convert it to the other.")

miles_label = tkinter.Label(text="Mile:")

mile = tkinter.Entry(width=100)
mile.bind("<Return>", convert_mile)

kilometer_label = tkinter.Label(text="Kilometer:")

kilometer = tkinter.Entry(width=100)
kilometer.bind("<Return>", convert_kilometer)

instrunctions.grid(row=0, column=0)
miles_label.grid(row=1, column=0)
mile.grid(row=1, column=1)
kilometer_label.grid(row=2, column=0)
kilometer.grid(row=2, column=1)

window.mainloop()

++ GfG


The End

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment