text
stringlengths
37
1.41M
print('This is a good day to learn python') print('python is fun') print('Python strings are easy') print('Python strings use quotes') print('You can add' + 'strings to eachother') name = input('Please enter your name here') greeting = 'oh hellow, ' print(name +' '+ greeting) age = 24 Greeting = 'Hello' print(type...
#Q.1- Write a Python program to read last n lines of a file c = -1 f=open('new 1.txt','r') content=f.readlines() n=int(input("enter the number of line: ")) while c >= -n: print(content[c],end="") c= c - 1 f.close() #file=new 1.txt Hello world! Hello python! Hello java! Hello html! Hello keshav Hello yash Hello vibho...
percentage_score=107 if((percentage_score>=80)and(percentage_score<=100)): print("A") elif((percentage_score>=73)and(percentage_score<=79)): print("B") elif((percentage_score>=65)and(percentage_score<=72)): print("C") elif((percentage_score>=0)and(percentage_score<=64)): print("D") else: print("Z")
""" 6. set 자료형 """ # 초기화 방법 data = set([1, 1, 2, 3, 4, 4, 5]) print(data) # {1, 2, 3, 4, 5} data = {1, 1, 2, 3, 4, 4, 5} print(data) # {1, 2, 3, 4, 5} # 집합 자료형의 연산 a = set([1, 2, 3, 4, 5]) b = set([3, 4, 5, 6, 7]) print(a | b) # 합집합. {1, 2, 3, 4, 5, 6, 7} print(a & b) # 교집합. ...
''' Draw the double pendulum ''' from __future__ import division from draw import Point, Draw from calc import DoublePendulum import pygame as pg import math fps = 60 red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) dark_blue = (0, 0, 128) white = (255, 255, 255) black = (0, 0, 0) pink = (255, 200, 200) grey...
#Obtenga la resta de todos los elementos de una lista from functools import reduce lista = [12,14,7,21,49,23,45,46,574,32,54] restador = lambda acumulado = 0, elemento = 0: acumulado - elemento restados = reduce (restador, lista) print (restados) # Dada una lista de palabras devolver una frase from functools import re...
#Implemente um algoritmo que leia um número inteiro, em seguida calcule o fatorial deste número e apresente para o usuários. #Ex: n = 4 #O Fatorial de 4 é 24 #primeira opcao de resolucao n= 4 for i in range (2,n): n = n*i print(n) #segunda opcao de resolucao fatorial= 1 n= 4 for i in range (n): fatorial= fatoria...
from PIL import Image from PIL import ImageDraw im = Image.open("wire/wire.png") result = Image.new("RGB", (100, 100), "white") drawer = ImageDraw.Draw(result) im_size = im.size im_x = im_size[0] im_y = im_size[1] result_size = result.size result_x = result_size[0] result_y = result_size[1] count = 0 x = 0 y = 0 le...
from PIL import Image from PIL import ImageDraw im = Image.open("cave/cave.jpg") size = im.size width = size[0] height = size[1] odd_and_even = Image.new("RGB", [width, height], (0xff, 0xff, 0xff)) drawer = ImageDraw.Draw(odd_and_even) for x in range(0, width, 2): for y in range(0, height, 2): drawer.poi...
""" 6666 6 66666 6 6 66666 """ n=int(input("enter the odd number:")) k=n//2+1 for i in range(1,n+1): for j in range(1,n+1): if i==1 or j==1 or i==n or i==k: print("6",end="") elif j==n and i>k : print("6",end="") else: print(" ",end="") ...
class Node(): def __init__(self,val): self.data=val self.add=None class ll(): def __init__(self): self.head=None self.last=None def insert(self,val): nn=Node(val) if self.head==None: self.head=nn self.last=nn else: ...
import turtle import pandas screen = turtle.Screen() screen.title("U.S. States Game") image = "blank_states_img.gif" screen.addshape(image) turtle.shape(image) menu_title = "Guess the State" correct_answer_count = 0 data_frame = pandas.read_csv("50_states.csv") all_states = data_frame["state"].to_list() guessed_stat...
""" You are given an array of integers. Return the length of the longest consecutive elements sequence in the array. Example: Input: [100, 4, 200, 1, 3, 2] Output: 4 """ class Solution(object): def longest_consecutive(self, nums): max_len = 0 bounds = dict() for num in nums: if num in bounds: ...
HOUR_TO_MINUTES = 60 sleep_count, alarm_hours, alarm_minutes, alarm_cycle = map(int, input().split()) convert_alarm_minutes = alarm_hours * HOUR_TO_MINUTES convert_alarm_minutes += alarm_minutes convert_alarm_minutes += alarm_cycle * (sleep_count - 1) wakeup_hour = convert_alarm_minutes // HOUR_TO_MINUTES wakeup_min...
# -*- coding: utf-8 -*- """ Created on Sat Dec 14 12:04:21 2019 @author: Nithin_Gowrav """ from pydub import AudioSegment import os #Convert mp3 files in a directory to wav files mp3_dir="G:/audio_source/mp3_source/" wav_dir="G:/audio_source/wav_source/" mp3_list=os.listdir(mp3_dir) for i in mp3_...
def get_int(message, new_line=True): """# Forces Integer Input --- Forces an integer input. Input the question to ask the user, returns the inputted integer. You may also specify whether the input should be typed on a different line or not using new_line. Default is `True`.""" if new_line: ...
"""Contains classes pertaining to acme products. Robert Davis 2021/09/03""" from random import randint class Product: """A class used for storing data about products.""" def __init__(self, name, price=10, weight=20, flammability=0.5): """Initiates the product class""" self.name = name ...
"""Generates random products to test the acme classes. Robert Davis 2021/09/03""" from random import randint from acme import Product ADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved'] NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???'] def generate_products(numProducts=30): """...
from math import * import numpy as np from scipy.integrate import odeint from scipy.optimize import newton import matplotlib.pyplot as plt import matplotlib.animation as animation print("Ten program wizualizuje ruch punktu materialnego w rzucie ukośnym przy oporze powietrza") m = float(input("Podaj masę ciała\n m[kg]...
import sys class Elem(): def __init__(self, nome, ante = None, prox = None): self.nome = nome self.ante = None self.prox = None class ListaDuplEncad(): cabeca = None cauda = None def add(self, elem): novo_elem = Elem(elem) # Se a lista estiver vazia i...
from functools import reduce from math import sqrt, ceil from exceptions import * def square_sum(*args): if args: for arg in args: if isinstance(arg, float): raise FloatError('Sorry! Floats are not permissioned.') try: squres = [sqrt(num) for num in args] ...
import random def coinFlip(): numFlips = input("Number of flips: ") flips = [random.randint(0,1) for i in range(numFlips)] result = [] for num in flips: if num == 0: result.append("Heads") elif num == 1: result.append("Tails") print result coinFlip()
""" Implement next permutation, which arranges numbers into the lexicographically next greater permutation of numbers. If such an arrangement is not possible, it must rearrange it as the lowest possible order. """ def permute(nums: list[int]) -> None: m = len(nums) output = [] def backtrack(first = 0): ...
num1 = 10 num2 = 2 #Mayor que resultado = num1 > num2 print(resultado) #Menor que resultado = num1 < num2 print(resultado) #Mayor o igual que resultado = num1 >= num2 print(resultado) #Menor o igual que resultado = num1 <= num2 print(resultado) #Diferente resultado = num1 != num2 print(resultado) #Igual resultado...
num1 = int(input("Numero 1: ")) num2 = int(input("Numero 2: ")) num3 = int(input("Numero 3: ")) if num1 >= num2 and num1 >= num3: print(f"El primer numero {num1} es el mayor de todos") elif num2 >= num1 and num2 >= num3: print(f"El segundo numero {num2} es el mayor de todos") elif num3 >= num1 and num2 >= ...
nombre = "Der" edad = 20 print("Hola", nombre, "tienes", edad, "años") print("Hola {} tienes {} años".format(nombre, edad)) print(f"Hola {nombre} tienes {edad} años")
a = int(input("Variable a: ")) b = int(input("Variable b: ")) # Metodo con lo de Java aux = a a = b b = aux print(f"La variable a es {a} y la variable b es {b} y aux es {aux}") # Metodo Pro con algoritmo de Python a, b = b, a print(f"La variable a es {a} y la variable b es {b}")
# This is an ATM machine print(25 * '=') print('Welcome to the Bank ATM!') print(25 * '=') options = ['deposit', 'withdraw', 'balance', 'exit'] dic_bank_accounts = {'vasil': {'1230': 2000}, 'georgi': {'3210': 1000}, 'ivan': {'0000': 1200}, 'petur': {'54...
l=int(input("Enter length for rectangle: ")) b=int(input("Enter breadth for rectangle: ")) ans=l*b print(ans) #parameter ans2= 2*l + 2*b print(ans2) r=int(input("Enter value for radius: ")) pi=3.14 ans= pi*r**2 print(ans) #parameter ans2= 2*pi*r print(ans2)
def median_of_medians(A, i): #divide A into sublists of len 5 sublists = [A[j:j+5] for j in range(0, len(A), 5)] medians = [sorted(sublist)[len(sublist)//2] for sublist in sublists] if len(medians) <= 5: pivot = sorted(medians)[len(medians)//2] else: #the pivot is the median of the medians pivot ...
from flask import Flask app = Flask(__name__) # taking the name of the module. # route is a decorator which tells the application URL should call the # associated function. # @app.route(rule, options) @app.route('/') def hello_world(): return "Hello World" @app.route('/hello/<name>') def test_name(name): re...
#just printing a welcome to the user print("Welcome To Leo's Bill Tip/Split Calculator") #just a line break from the welcome message print("\n") #Asking the user to enter the amount on the bill by making a variable and making sure the input will be a float total_bill = float(input("What is the total bill?:$ ")) #Asking...
import os from random import shuffle class DataSplitter: """ This class is tasked with splitting all of our data into positive vs. negative examples as well as splitting into training, validation, and test data. ASSUMPTIONS: 1. We already have the VOCdevkit downloaded 2. The image data...
import os import cv2 import numpy as np from PIL import Image from zipfile import ZipFile def load_image(imfile): """This function reads an input image from file Args: imfile (str): path to an image Returns: 2D or 3D numpy array of image values """ im = cv2.imread(imfile) ret...
from string import punctuation import re import nltk from nltk.tokenize import TweetTokenizer class NLTools(): def __init__(self): #lista donde se almacenan todas las palabras tokenizadas self.tokens = [] #lista donde se almacenan listas de tokens correspondientes a ca...
# Python program to implement client side of chat room. import socket import select import os from time import sleep from _thread import * import sys server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) IP_address = input("IP:") Port = int(input("Port:")) server.connect((IP_address, Port)) def send_mess...
#!/usr/bin/env python # -*- coding: utf-8 -*- import re def timeToFloat (a):#перевод из часы:минуты в десятичное time1= re.sub(',' , '.' , a) time= re.split(':|-',a) # for i in time: # if re.search('\D',i)>=0: # return -1 try: if len(time)==4: hours = float (time[0]) minut...
from random import randint from brain_games.cli import get_user_name, get_user_answer ROUNDS = 3 def greet(): print('Welcome to the Brain Games!') def generate_random_number(start=0, end=100): return randint(start, end) def welcome(): user = get_user_name() print("Hello, {}!".format(user)) re...
import random potential_words = ["modulus", "algorithm", "list", "variable", "condition"] word = random.choice(potential_words) print(word) # Make it a list of letters for someone to guess Number_of_spaces = ["_"]*len(word)# TIP: the number of letters should match the word guesses = 10 maxfails = 6 fails = ...
def pos_neg(a, b, negative): if negative is True: if abs(a) != a and abs(b) != b: return True else: if abs(a) != a and abs(b) == b or abs(a) == a and abs(b) != b: return True return False
def front3(s): if len(s) >= 3: return 3 * s[:3] else: return s * 3
from PIL import Image import numpy as np import random """input the image""" k1 = Image.open("C:/Users/USER/Desktop/Image_and_ImageData/key1.png") k2 = Image.open("C:/Users/USER/Desktop/Image_and_ImageData/key2.png") k3 = Image.open("C:/Users/USER/Desktop/Image_and_ImageData/I.png") E = Image.open("C:/Users/USER...
import math ang = float(input('Insira quanto vale o angulo: ')) seno = math.sin(math.radians(ang)) cos = math.cos(math.radians(ang)) tan = math.tan(math.radians(ang)) print('O seno do angulo {} é {:.2f}'.format(ang, seno)) print('O cosseno do angulo {} é {:.2f}'.format(ang, cos)) print('A tangente do angulo {} é {:.2f}...
# Mr Watson # guessNum.py import random # Create your own custom guessing game using for loops and while loops # Be creative! randomNumber = random.randint(1, 101); print(randomNumber)
def line(): print('\n---------------\n') #create a dictionary with integers as keys colorInt = {1: 'Red', 2: 'Orange', 3:'Yellow'} #create a dictionary colorString with strings as keys colorString = {'R': 'Red', 'O': 'Orange', 'Y': 'Yellow'} print('print colorInt') for key, value in colorInt.items(): print(...
class Athlete: def __init__(self, a_name, a_dob=None, a_times=[]): self.name = a_name self.dob = a_dob self.times = a_times def top3(self): return sorted(set([t for t in self.times]))[0:3] sarah = Athlete('Sarah Sweeney', '2017-02-22', ['2:28','1:56','2:22','2:28',...
# coding: utf-8 # In[1]: import csv import sys # In[9]: # read pharmacy file into data structure def read_pharma_file(infile): pharm = {} with open(infile, "r") as f: #with open("../input/data_trunc.txt", "r") as f: my_data = csv.DictReader(f) for line in my_data: drug = ...
age=input('Сколько Вам лет? ') def kind_of_activity(age): age=int(age) if age <= 6: print('Пора на горшок и спать') elif age <= 18: print('Неси дневник учителю!') elif age <= 24: print('Пиши курсовую, сессия на носу') elif age <= 65: print('А завтра снова на работу.'...
from typing import List class Solution: def exist(self, board: List[List[str]], word: str) -> bool: self.x = len(board) self.y = len(board[0]) for i in range(self.x): for j in range(self.y): if self.dfs(board, word, i, j): return True ...
# -*- coding:utf-8 -*- class Solution: # s 源字符串 def replaceSpace(self, s): # write code here length = len(s) new_s = [] for i in range(length): if s[i] == ' ': new_s.append('%20') else: new_s.append(s[i]) return ''.j...
# Definition for singly-linked list. from typing import List class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: return self.merge(lists, 0, len(lists) - 1) def merge(self, lists: List[Lis...
__author__ = 'Philipp Bobek' __copyright__ = 'Copyright (C) 2015 Philipp Bobek' __license__ = 'Public Domain' __version__ = '1.0' import os class Solver: SOLUTION_FOUND = 'Solution found' NO_SOLUTION = 'No solution' verbose = True file = None def __init__(self, is_verbose=True, output_file=Non...
import math class Encoder(): """Encode file.""" def __init__(self): # How many characters / values will load at a time self.buffer_read = 500 def code(self, arquivo, tipo, result_path,golomb_divisor = 0): """Encode the file with the given type.""" self.buffer_escrita = '' ...
groceries = ["apples", "bananas", "bread", "milk", "cheese" ] print (len(groceries)) print (groceries [4]) print ("bread" in groceries) for item in groceries: print (item) for num in range(len(groceries)): print (groceries[num]) groceries.append("meat") print (groceries)
class Condition(): STATES = ( 'Address', 'Protocol', 'Ports', 'Shell', 'Privilege', 'Binaries', 'CWD', 'Misudo', ) def __init__(self): """ Condition is used to validate whether a state can satisfy a specific goal. ...
from board import Board from player import Player class Game: board = Board() players = [Player(), Player()] chosenCards = [] def play(self): self.board.draw() isPlaying = True currPlayer = 0 self.board.draw() while isPlaying: score = self.player...
import re from ...errors.validation_error import ValidationError class EmailValidator: def __init__(self, field, allow_empty=False, trim=True, message='must be a valid email'): self.field = field self.trim = trim self.message = message self.allow_empty = allow_empty def __call...
#%% # import packages import altair as alt import pandas as pd import numpy as np #%% # from json url to pandas dataframe url = "https://github.com/byuidatascience/data4missing/raw/master/data-raw/flights_missing/flights_missing.json" flights = pd.read_json(url) # GRAND QUESTION 1 #%% # What data are we dealing with...
from collections import Counter words = ['look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', 'under'] words_counts = Counter(words) top_three = words_counts.most_common(3) prin...
# -*- coding: utf-8 -*- """ Created on Sun Apr 29 23:06:19 2018 @author: Diana Narváez """ import math# Biblioteca para operaciones matemáticas #Ingreso de datos print("**********Cálculo del volumen de una esfera**********") R=float(input("Ingrese el valor radio en centimetros\n")) #Funcion que calcula el volumen de...
# -*- coding: utf-8 -*- """ Created on Sun Apr 29 15:06:08 2018 "Calculo de el volumen de un cono truncado" @author: José Cortez """ import math# Biblioteca para operaciones matemáticas #Ingreso de datos print("**********Cálculo del área de un Cono Truncado**********") R=float(input("Ingrese el valor del mayor radio ...
'''An Integer I is called a factorial number if it is the factorial of a positive integer. The First few Factorial Numbers are 1,2,6,24 (0! =1 1!=1 2! =2 3!= 6). Given a number I, Write a Program that prints all factorial numbers less than or equal to I.''' def factorial(n): #function that perform...
from enum import Enum odd_primitives = {str: "string", int: "integer", float: "float", bool: "boolean"} class odd(Enum): SHALLOW = "shallow" DEEP = "deep" LIST = "list" DICT = "dict" EMPTY = "empty"
# python object programming, regular method, static method and class method class Employee: numOfEmployee = 0 raiseRate = 0.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@email.com' E...
import random import time import sys class Ability: ''' ability class ''' def __init__(self, name, attack_strength): self.name = name self.attack_strength = attack_strength def attack(self): min_attack = self.attack_strength // 2 max_attack = self.attack_strength ...
#!/usr/bin/env python ############################################################################# # Filename : Thermometer.py # Description : A DIY Thermometer # Author : Jerry Lee and Justin Le # modification: 06/01/2018 ######################################################################## import RPi.GPIO...
# Problem: https://leetcode.com/problems/merge-intervals/ """ Note: sorting is important. Sorting ensures we only have to update previous interval's end as start will be always lower. """ from typing import List class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: out = [] ...
''' 1. Capture smallest string and longest string 2. Iterate over smallest string: 2.a. return the sub-string till there is a match with longest string 3. By default smallest string is longest common prefix so return that ''' def longestCommonPrefix(strs) -> str: if not strs: return '' # since list of string wil...
# Problem: https://leetcode.com/problems/sqrtx/ """ - since 1 <= x <= x^2 for all x > 0 - we are going to search for a number that which sqaure is just right a bit larger than x e.g. 8 1 2 3 4 5 6 7 8 ^ ^ 1 2 3 4 5 6 7 8 ^ ^ 1 2 3 4 5 6 7 8 ^ ^ 1 2 3 4 ...
# Problem: https://leetcode.com/problems/largest-rectangle-in-histogram/ # CHECK ALSO maximal_rectangle_stack class Solution: def largestRectangleArea(self, height): height.append(0) # appending 0 at the end of height list for our convenience stack = [-1] # initialize stack with -1 so it picks up ...
x=int( input("Indique su peso en kg: ") ) y=float( input("Indique su altura en metros: ") ) print("Su imc es", x/y)
import math def hello(): print ('Варіант 27, програма для обчислення y в залежності від значення х') print('Чумак С.І., група КМ-12') def read_x(): x=float(input('Введіть значення х=')) return x def calculate_y(x): if x<-1.5 : y=math.pi*math.sin(x) else : if x>=2.5 : ...
"""Check HTTPS connection""" from urllib.parse import urlparse import requests from clint.textui import indent, colored, puts from helpers import get_domain def check(urls): """Check the urls for access through https""" for url in set(map(get_domain, urls)): puts(colored.white('Checking https for: ',...
def evaluar(nom, ape): if int(len(nom))<10 and int(len(ape))<10: print ("Nombre y apellido correctos") else: print("Nombre y/olargoooooo apellido muy largos") nombre="" apellido="" nombre = str(input("Por favor introduzca nombre=")) apellido= str(input("Por favor introduzca apellido=")) evaluar(nombre,ap...
lista = [1, 2, 3, 5, 6, 7, 8] pares = [] impares = [] for i in lista: if i % 2 == 0: pares.append(i) else: impares.append(i) print("los pares " + str(pares)) print("los impares " + str(impares))
what = input('Что делаем?? (+, -, %, /, *)\n') number = int(input('Первое число ')) number1 = int(input('Второе число ')) if what == '+': res = number + number1 elif what == '-': res = number - number1 elif what == '*': res = number * number1 elif what == '%': res = number % number1 elif what == '/': ...
""" Chloe Harrison """ MIN_LENGTH = 5 password = input("Enter password: ") while len(password) < MIN_LENGTH: print("Needs 5 characters") password = input("Enter password: ") print("*" * len(password))
#Created by Shikha Singh import cv2 #Creating a function to generate live sketch of the object detected by webcam def sketch(img): #The 'if' statement is used to check that frames are passed correctly if img is not None: print("image is present") print(len(img.shape)) #conver...
#7 columns of 6 rows, #starts in bottom left corner. #not successultt stopping the other player when they have a column of 3 and you have col of 2 """ chunking makes moves for any player maybe do by dictionary with board val and number of, then length to see how many tyoes there are if len 2 and one is -1, add the m...
# returns index of number just lesser/equal than num def binarySearchCeilIndex(arr, start, end, num): print(start, end) if end == start: if arr[start] >= num: return start elif arr[start] < num: return min(start + 1, len(arr) - 1) else: mid = (start + end)//2 ...
def quick_select(arr, k): if(len(arr)<=1): return arr[0] pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] l = len(left) m = len(middle) r = len(right) if(l>=k): return quick_select(left, k) elif (l+m)>=k: return...
from PIL import Image, ImageFilter # basic pillow img processing img = Image.open("./pokedex/bulbasaur.jpg") # filtered = img.filter(ImageFilter.BLUR) # BLUR, SHARPEN, SMOOTH etc more in docs. # filtered = img.convert("L") # converted into a grayscale - "L" mode here, mode avaible - in docs. # filtered.save("./pokede...
print("enter 5 numbers") numbers = [input('number 1:'),input('number 2:'),input('number 3:'),input('number 4:'),input('number 5:')] print("the smallest number is {}".format(min(numbers))) print("the largest number is {}".format(max(numbers))) print("the first number is {}".format(numbers[0])) print("the last number i...
""" CP1404/CP5632 Practical File renaming and os examples """ import os, shutil __author__ = 'Lindsay Ward' print("Current directory is", os.getcwd()) # change to desired directory os.chdir('Lyrics/Christmas') # print a list of all files (test) # print(os.listdir('.')) # make a new directory os.mkdir('temp') # loo...
for i in range(1, 13): print("No. {0} squared is {1} and cubed is {2}" .format(i, i ** 2, i ** 3)) print() for i in range(1, 15): print("No. {0:2} squared is {1:3} and cubed is {2:3}" .format(i, i ** 2, i ** 3)) print() for i in range(1, 13): print("No, {0:2} squared is {1:<3} and cubed {2:<4}" .format(...
import random class Guesser(): def __init__(self): self.list_word =["house", "table", "rock", "guesser"] self.word = random.choice(self.list_word) self.display = "" self.first_hint = "" self.fails = 0 def get_hint(self): self.display = '_' * len(self.word) ...
# 交换变量简易的方法 a, b = 1, 2 print(f"a:{a}b:{b}") a, b = b, a print(f"a:{a}b:{b}") # 引用 在python中,值都是靠引用来传递来的,引用可以当做实参传递 # id()返回变量在内存中的十进制的地址 用于判断两个变量是同一个值的引用 a = 1 b = a print("%d\n%d" % (id(a), id(b))) """ 可变类型:列表 字典 集合 不可变类型:整形 浮点型 字符串 元组 """
# lambda[匿名函数]表达式:如果一个函数有一个返回值,并且只有一句代码,可以使用lambda简化 """ 语法: lambda 参数列表 : 表达式 lambda表达式的参数可有可无,函数的参数在表达式中完全适用 lambda表达式能接受任何形式的参数,但是只能返回一个值 """ def fn1(): return 200 fn2 = lambda: 100 print(fn2) # 直接打印表达式,返回内存地址 print(fn2()) # lambda 参数:返回值兼表达式 fn3 = lambda a, b: a + b print(fn3(2, 114)) # lambda 参数可以使用默认参数 ...
# 递归 # 需求N以内的数字累加和1+2+3...+N def user_add(num): if num == 1: return 1 return num + user_add(num - 1) print(user_add(3))
import random """ 列表一个列表存储最好是相同类型 """ list1 = ["replace", "split", "join", "strip", "just"] str1 = "replace split join strip just" """ len(名)返回长度[公共操作] index和count用法基本一致 """ print(len(list1)) """ 判断指定数据是否在某个列表序列中[公共操作] in not in print("split" in list1) print("split" in str1) str = input("请输入要查找的字符串") if str in list1:...
import random """ 循环 """ i = 0 while i < 5: print("好吧(╯▽╰)", end="") i += 1 print("结束") i = 1 Sum = 0 while i <= 100: if i % 2 == 0: Sum += i print(i, end=" ") i += 1 print(f"\n{Sum}") # 满足一定条件退出循环 # break--直接退出循环 continue--退出本次循环,执行下一次循环 i = 1 while i < 100: if i == random.randint(...
print "programa para guardar el menu del restaurante" seguir = True menu = {} while seguir: plato = raw_input("Escribe aqui el nombre del plato: ") precio = raw_input("Escribe aqui el precio del plato: ") menu [plato] = precio nuevo_plato = raw_input("desea escribir otro plato, responda con ( s o n ): ...
#import the csv file and read it import os import csv import math csvpath = os.path.join('PyBank','Resources','Python_PyBank_Resources_budget_data.csv') total_months = 0 total_p_l = 0 change_list = [] previous_row = 0 change = 0 month_money_list = [] with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, ...
from tkinter import * root = Tk() root.geometry("500x50") root.title("Testing Entry") def printMessage(event): global e i = e.get() print(i) e.delete(0,END) frame = Frame(root) Label(frame,text="Enter Value: ").pack(side="left") e = Entry(frame) e.pack(side="left") printButton = Button(frame,te...
banks = [] for i in range(3): bank = [] for j in range(10): bank.append([j,0,0]) banks.append(bank) def deposit(bank,accno,v): bank = banks[bank] acc = bank[accno] if v > 0: acc[1] += v acc[2] = v def withdraw(bank,accno,v): bank = banks[bank] acc = bank[accno]...
from flask import Flask, request app = Flask(__name__) @app.route('/', methods=['POST', 'GET']) def hello(): if request.method == "GET": return ''' <form action="/" method="POST"> <label>Message: </label> <input type="text" name="msg"> ...
print("Welcome") print("Enter value for i") ##string input i = input() print("The Value entered is",i) print("Enter value for j") j = input() print("The Value entered is",j) z = i + j print("The Sum is",z) a = int(input("Enter value of a")) ##integer input print('The value entered for a is',a) b = int(input("En...
#Learning if statements. #if-else flag = False print("Entering Program1") if flag : #<--- if expression: print("Inside If") else: #<---clause print("Inside Else") #<---suite print("Leaving program1") #if-elif-else i = 20 print("Entering Program2") if i == 1 : print(...
# Stage 2 print("Welcome to Closure") # Container / Environment def f1(a,b): print("Entering f1") print("a = ",a) print("b = ",b) # f2 is not visible outside def f2(c,d): #nested/local functn print("Entering f2") print("c = ",c) print("d = ",d) print("Leavin...
i=3 j=6 if i>=3 and j<13 : print('&&&') j=31 if j <25: print('@@@') elif j >20 : if i <=3: print('^^^') else : print('###') else : print('$$$')