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")
#declaring different type of variables in python
variable1 ="value"# string
variable2 =1000000# integer
variable3 =10000.0# real/float
variable4 =True# boolean: True or False
'''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. '''#Examplesprint("Hello World")
repeat =5for i inrange(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 functionsclassPerson: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}.")
from _future_ import print_function
import matplotlib.pyplot as plt
import os
import sys
import re
import gc
# Selection of features following "Writing mathematical expresion"tutorial
mathtext_tiles ={0:"Header demo"1:"Subscripts and superscripts"2:"Fraction ,bionomals and stacked numbers"3:"radicals"4:"Fonts"5:"Accents"6:"Greek Herbew"7:"Delimeters, functions and symbols"}
n_lines =len(mathtext_titles)
Python is an interpreted, high-level and general-purpose programming language. Created by Guido van Rossum and first released in1991, 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 keyboardimport 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):iftype(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 in1991, 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 =1for i inrange(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)
#pip install danielutilsfrom danielutils import validate
@validate(str)deff1(name):pass@validate([int,float])deff2(number):pass@validate([str,lambda s:len(s)<10,"short_string must be shorter than 10 letters"])deff3(short_string):pass#will raise error because duplicate function name in same context@validate([[int,float],lambda age: age >0,"age must be bigger then 0"])deff3(age):pass@validate(None,int,int,None)deff5(skip, dont_skip, dont_skip2, skip2):pass
//for2 strings s1 and s2 to be anagrams
// both conditions should be True//1 their length is same orlen(s1)==len(s2)//2 rearranging chars alphabetically make them equal orsorted(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 numbersdefdisplay_state():global nums
print("100/",nums)# Get number the player wants to playdefget_input(player):
valid =Falsewhilenot 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 stringif move.isdigit():# If move is a number
move =int(move)# can take 1-10 number onlyif move inrange(1,11)and nums + move <=100:
valid =Truereturn move
# Update numbers after the movedefupdate_state(nums_taken):global nums
nums += nums_taken
# Check if he/she is taking the last move and losesdefis_win():global nums
if nums >99:returnTrue# define the 100 gamedefplay__100_game():
display_state()while(True):# Repeat till one of them loses
first = get_input("First")
update_state(first)
display_state()# Display new numbersif(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 intinput
a=int(input())//if you want n elements of array a asinputfrom 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 listwith duplicates removed
list(set(map(int,input().strip().split())))
also note mapis a method andisnot 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
classMessage(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")defget_status():"""Get status of messaging server."""return({"status":"running"})@app.get("/channels", response_model=List[str])defget_channels():"""Get all channels in list form."""return channel_list
@app.get("/messages/{channel}", response_model=List[Message])defget_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)defpost_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 =34if(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 objectis created
a=A()//this init is called
//similarly say
classA:def__len__(self):print("dd")
a=A()len(a)//prints dd basically python knows that magic method __len__ is to be called forlen(a)
defisYearLeap(year):# Leap year formulaif year %4==0and year %100!=0:returnTrueelif year %400==0:returnTrueelse:returnFalse
testData =[1900,2000,2016,1987]# Test Data as reference
testResults =[False,True,True,False]for i inrange(len(testData)):
yr = testData[i]print(yr,"->",end="")
result = isYearLeap(yr)if result == testResults[i]:print("OK")else:print("Failed")defdaysInMonth(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 =1if year %100==0:
days =0if year %400==0:
days =1if month ==2:return28+ days
if month in mo31 :return31return30
testYears =[1900,2000,2016,1987]# Test Data as reference
testMonths =[2,2,1,11]
testResults =[28,29,31,30]for i inrange(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")defdayOfYear(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 =0if dd ==0:for i inrange(len(monthvalue)):
mo.append(i)# Creating mo listif m in mo:
mo[i]== monthvalue[i]
dd = y //4+ d + m
if m >=2:
dd -=1
dd += y
for i inrange(len(value)):if y in century :
y = century[i]== value[i]
dd += y
rem = dd %7for i inrange(len(doy)):
r.append(i)# Creating r listif rem in r :
rem = r[i]== doy[i]print(rem)print(dayOfYear(2000,12,31))# Giving output False "None
""" Quickstart script for InstaPy usage """# importsfrom 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
deflogs():
logs =[]
w ='(?P<host>(?:d+.){3}d+)s+(?:S+)s+(?P<user_name>S+)s+[(?P<time>[-+ws:/]+)]s+"(?P<request>.+?.+?)"'withopen("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=18input=("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=0for i inrange(len(s)-len(p)+1):for j inrange(len(p)):if s[i+j]==p[j]:if c<len(p):
c=c+1if c==len(p):
counter+=1
c=0breakcontinueelse:breakprint('number of occurences of the substring in the main string is: ',counter)