Python is an interpreted, high-level,
general-purpose programming language.
//as you can also see to your right --------------------->
but also note interpreted, not compiled.
Python is a high-level, interpreted, general-purpose programming language.
Its design philosophy emphasizes code readability with the use of significant
indentation. Python is dynamically-typed and garbage-collected.
Python is an interpreted high-level general-purpose programming language. Its design philosophy emphasizes code readability with its use of significant indentation. Its language constructs as well as its object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects.
print("Hello! This is Python! This is an amazing software for you to code on!")
print("Don't worry! You'll be good soon!")
print("For more info, visit https://python.org")
'''Python is an interpreted, high-level and general-purpose programming
language.Python's design philosophy emphasizes code readability with its
notable use of significant whitespace. '''
#Examples
print("Hello World")
repeat = 5
for i in range(repeat):
print("This is the %i iteration" % i)
#2nd variation - print("This is the " + i + "iteration")
#3rd variation - print(f"This is the {i!r} iteration")
#4th variation - print(("This is the {} iteration).format(i))
import random #In order to use the random functions
class Person:
def __init__(self, name, age, height):
self.name = str(name)
self.age = int(age)
self.height = str(height)
person1 = Person("Name", random.randint(1, 100), str(random.randint(0, 7)) + "'" + str(random.randint(0, 11)) + '"')
print(f"Your name is {person1.name} and you are {person1.age} years old. You are also {person1.height}.")
Python is an interpreted, high-level and general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant whitespace.
#1) To type a string using the keyboard module:
#pip install keyboard
import keyboard
string = "This is what I typed"
keyboard.write(string)
#2) To check if an object is of the type 'str' (to check if the object is a string):
if type(object) == str:
#3) To print a string:
string = "This is displayed in your Big Black Console"
print(string)
Python is an interpreted, high-level, general-purpose programming language.
Created by Guido van Rossum and first released in 1991, Python's design
philosophy emphasizes code readability with its notable use of significant
whitespace.
n = int(input('Type a number, and its factorial will be printed: '))
if n < 0:
raise ValueError('You must enter a non negative integer')
fact = 1
for i in range(2, n + 1):
fact *= i
print(fact)
Congratulations My friend!!!
You are going to take your first step into the world of PYTHON!!!
LEARN - DEVELOP - IMPLEMENT - and CHANGE THE WORLD!!! (for the better)
// for 2 strings s1 and s2 to be anagrams
// both conditions should be True
// 1 their length is same or
len(s1)==len(s2)
// 2 rearranging chars alphabetically make them equal or
sorted(s1)==sorted(s2)
print(" Welcome to the 100 game
")
print("To start the game you have to enter a number between 1 to 10")
print("To end the game you have to reach the number 100")
print("First one reach 100 win
")
print("Good luck
")
nums = 0
# Display numbers
def display_state():
global nums
print("100/",nums)
# Get number the player wants to play
def get_input(player):
valid = False
while not valid: # Repeat until a valid move is entered
message = player + " player please enter the number between 1 and 10: "
move = input(message) # Get move as string
if move.isdigit(): # If move is a number
move = int(move) # can take 1-10 number only
if move in range(1, 11) and nums + move <= 100:
valid = True
return move
# Update numbers after the move
def update_state(nums_taken):
global nums
nums += nums_taken
# Check if he/she is taking the last move and loses
def is_win():
global nums
if nums > 99:
return True
# define the 100 game
def play__100_game():
display_state()
while (True): # Repeat till one of them loses
first = get_input("First")
update_state(first)
display_state() # Display new numbers
if (is_win()):
print("First player won")
break
second = get_input("Second")
update_state(second)
display_state()
if (is_win()):
print("Second player won")
break
play__100_game()
// if you want to take single int input
a=int(input())
// if you want n elements of array a as input from console/user
a = list(map(int,input().strip().split()))
# u can also covert it to set,tuple etc
# ex. set(map(int, input().strip().split()))
NOTE: suppose if you want a list with duplicates removed
list(set(map(int, input().strip().split())))
also note map is a method and is not hashmap which is actually disct in python.
and ommitting .strip() in 2nd argument of map func might also work.
# more explaination of above:
https://www.quora.com/What-does-the-following-line-mean-in-Python-list-map-int-input-strip-split-I
"""
A Bare Bones Slack API
Illustrates basic usage of FastAPI.
"""
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel
from typing import List
class Message(BaseModel):
"""Message class defined in Pydantic."""
channel: str
author: str
text: str
# Instantiate the FastAPI
app = FastAPI()
# In a real app, we would have a database.
# But, let's keep it super simple for now!
channel_list = ["general", "dev", "marketing"]
message_map = {}
for channel in channel_list:
message_map[channel] = []
@app.get("/status")
def get_status():
"""Get status of messaging server."""
return ({"status": "running"})
@app.get("/channels", response_model=List[str])
def get_channels():
"""Get all channels in list form."""
return channel_list
@app.get("/messages/{channel}", response_model=List[Message])
def get_messages(channel: str):
"""Get all messages for the specified channel."""
return message_map.get(channel)
@app.post("/post_message", status_code=status.HTTP_201_CREATED)
def post_message(message: Message):
"""Post a new message to the specified channel."""
channel = message.channel
if channel in channel_list:
message_map[channel].append(message)
return message
else:
raise HTTPException(status_code=404, detail="channel not found")
# Python program to illustrate
# selection statement
num1 = 34
if(num1>12):
print("Num1 is good")
elif(num1>35):
print("Num2 is not gooooo....")
else:
print("Num2 is great")
so basically its like this
//when object is created
a=A()
//this init is called
//similarly say
class A:
def __len__(self):
print("dd")
a=A()
len(a)
//prints dd basically python knows that magic method __len__ is to be called for len(a)
def isYearLeap(year): # Leap year formula
if year % 4 == 0 and year % 100 != 0 :
return True
elif year % 400 == 0 :
return True
else :
return False
testData = [1900, 2000, 2016, 1987] # Test Data as reference
testResults = [False, True, True, False]
for i in range(len(testData)):
yr = testData[i]
print(yr,"->",end="")
result = isYearLeap(yr)
if result == testResults[i]:
print("OK")
else:
print("Failed")
def daysInMonth(year, month): # Finding out days in months in common & leap year
days = 0
mo31 = [1,3,7,5,8,10,12]
if year % 4 == 0 :
days = 1
if year % 100 == 0 :
days = 0
if year % 400 == 0 :
days = 1
if month == 2 :
return 28 + days
if month in mo31 :
return 31
return 30
testYears = [1900, 2000, 2016, 1987] # Test Data as reference
testMonths = [2, 2, 1, 11]
testResults = [28, 29, 31, 30]
for i in range(len(testYears)):
yr = testYears[i]
mo = testMonths[i]
print(yr, mo, "->", end="")
result = daysInMonth(yr, mo)
if result == testResults[i]:
print("OK")
else:
print("Failed")
def dayOfYear(year, month, day):
doy = ["Sat","Sun","Mon","Tue","Wed","Thu","Fri"] # Days of week
monthvalue = [1,4,4,0,2,5,0,3,6,1,4,6] # Months value zellers rule
century = [1700,1800,1900,2000] # Zellers rule
value = [4,2,0,6] # Zellers rule
rem = 0 # Remainder Variable
r = [] # Empty List to compare remainder and to a doy
y = str(year) # Converting year into string
y = int(y[2:4]) # Taking last two digits of string & if used return the function ends
y = int(year) # here returning last two digits
m = int(month)
d = int(day)
mo = [] # Empty list for comparing month with monthly values
dd = 0
if dd == 0 :
for i in range(len(monthvalue)) :
mo.append(i) # Creating mo list
if m in mo:
mo[i] == monthvalue[i]
dd = y // 4 + d + m
if m >= 2 :
dd -= 1
dd += y
for i in range(len(value)) :
if y in century :
y = century[i] == value[i]
dd += y
rem = dd % 7
for i in range(len(doy)) :
r.append(i) # Creating r list
if rem in r :
rem = r[i] == doy[i]
print(rem)
print(dayOfYear(2000, 12, 31)) # Giving output False "
None
""" Quickstart script for InstaPy usage """
# imports
from instapy import InstaPy
from instapy import smart_run
# login credentials
insta_username = 'moniqueteixeirapersonal' # <- enter username here
insta_password = 'dr4z9ycp' # <- enter password here
# get an InstaPy session!
# set headless_browser=True to run InstaPy in the background
session = InstaPy(username=insta_username,
password=insta_password,
headless_browser=False)
with smart_run(session):
""" Activity flow """
# general settings
session.set_relationship_bounds(enabled=True,
delimit_by_numbers=True,
max_followers=4590,
min_followers=45,
min_following=77)
session.set_dont_include(["friend1", "friend2", "friend3"])
session.set_dont_like(["pizza", "#store"])
# activity
session.like_by_tags(["natgeo"], amount=10)
Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation. Python is dynamically-typed and garbage-collected. It supports multiple programming paradigms, including structured, object-oriented and functional programming.
//File & Code Templates
// Settings/Preferences | Editor | File and Code Templates
//https://confluence.jetbrains.com/display/PhpStorm/File+Templates+in+PhpStorm
//The one with PHP File Header is located on "Includes" tab.
//But you can edit default "PHP File" template and have your header comment defined right there if you wish.
//WRITE
/**
* Created by PhpStorm.
* Filename: ${FILE_NAME}
* Project Name: ${PROJECT_NAME}
* User: ${USER}
* Date: ${DAY}/${MONTH}/${YEAR}
* Time: ${TIME}
*/
Python is a High level and multi-purpose Programming language. It is commonly
used in data science ,AI(Artificial intelligence) and ML(Machine Learning).
If you are a beginer in programming it is mostly prefered because its
code is very simple and somehow similar to English Language.Even master level
people use python. Encourage you to learn it.
import re
def logs():
logs = []
w = '(?P<host>(?:d+.){3}d+)s+(?:S+)s+(?P<user_name>S+)s+[(?P<time>[-+ws:/]+)]s+"(?P<request>.+?.+?)"'
with open("assets/logdata.txt", "r") as f:
logdata = f.read()
for m in re.finditer(w, logdata):
logs.append(m.groupdict())
return logs
#dimension of the wall in feet including length and width
lenght=13
width=18
input=("lenght and width")
input=("paint volume2.58 gallon")
print('totalwall350')
#counting occurence of a substring in another string (overlapping/non overlapping)
s = input('enter the main string: ')# e.g. 'bobazcbobobegbobobgbobobhaklpbobawanbobobobob'
p=input('enter the substring: ')# e.g. 'bob'
counter=0
c=0
for i in range(len(s)-len(p)+1):
for j in range(len(p)):
if s[i+j]==p[j]:
if c<len(p):
c=c+1
if c==len(p):
counter+=1
c=0
break
continue
else:
break
print('number of occurences of the substring in the main string is: ',counter)