text
stringlengths
37
1.41M
#Name:Alex Pierce #bumper.py #Purpose:Create program that creates two circles of different color #and chooses inital random directions for them to move. #Inputs:No user inputs #Outputs:Two circles of different colors bouncing around window changing #color and direction after collision with one another or wall. fr...
print('---- exercise 1 ----', '\n') # 1. Define the id of next variables: int_a = 55 str_b = 'cursor' set_c = {1, 2, 3} lst_d = [1, 2, 3] dict_e = {'a': 1, 'b': 2, 'c': 3} print(id(int_a)) print(id(str_b)) print(id(set_c)) print(id(lst_d)) print(id(dict_e)) # ---------------------------------- print('\n', '---- ex...
import sqlite3 def create_table(conn): """Create table.""" cur = conn.cursor() try: sql = ("CREATE TABLE movies (" "imdb_id VARCHAR(10) NOT NULL, " "title VARCHAR(40) NOT NULL, " "year int NOT NULL, " "rating DOUBLE NOT NULL, " ...
# https://www.codewars.com/kata/55f8a9c06c018a0d6e000132/train/python def validate_pin(pin): if len(str(pin)) == 4 or len(str(pin)) == 6: # check length for 4 or 6 for i in pin: # char iterator if i not in "0123456789": # checking if a char not in "0123456789" return False # if ...
import sys import csv from cs50 import SQL # if input error of argv exit program (expect 2) if len(sys.argv) != 2: print("Usage: python import.py data.csv") sys.exit() # in order to execute sql code db = SQL("sqlite:///students.db") # opening csv file given file = open(sys.argv[1], "r") # clearing database...
import sys # getting text text = input("Text: ") # setting counters (word is 1 for last {can improve}) ltrs = 0 words = 1 sntcs = 0 point = ['.', '!', '?'] # iterating through text to count lt/ w/ s for i in text: if i.isalpha(): ltrs = ltrs + 1 elif i == ' ': words = words + 1 elif i in...
#!/usr/bin/python3 """Rotate 2D Matrix""" def rotate_2d_matrix(matrix): """2D matrix, rotate it 90 degrees clockwise""" for col in zip(*matrix): matrix.append(list(reversed(col))) matrix.pop(0)
def fibonacci(n): if(type(n) != int): return 'not an integer' return sum_series(n, 0, 1) def lucas(n): if(type(n) != int): return 'not an integer' return sum_series(n, 2, 1) # if (n == 0): # return 2 # elif (n == 1): # return n # return lucas(n-1) + lucas(n-2) def sum_series(n,b=0,c=1): ...
mot=str(print("Pour sortir de la boucle suivante, il suffira d'entrer le mot \"fin.\n\n")) while mot != "fin" : mot=input("Rentrez un mot (sans accent) : ") mot_min=mot.lower() liste_voyelles=["a","e","i","o","u","y"] nb_voyelles = 0 for lettre in mot_min : if lettr...
n=int(input('entrer un nombre')) for a in range(1,n+1): sa=0 for i in range(1,a): if a%i==0: sa=sa+i if sa==a: print(a)
def get_data(filename): with open('./' + filename, 'rt') as f: data = [int(line) for line in f.read().splitlines()] data.sort() return data #part 1 def count_diffs(data): jolt = 0 differences = {1:0, 2:0, 3:1} for n in data: diff = n - jolt jolt = n if diff <...
#!/usr/bin/env python #coding: *-* utf8 *-* import socket import re import urllib2 # use socket lib to get hostname or host IP address def get_remote_machine_info(): remote_host = raw_input("Please input Your site name: ") try: print "IP address: %s" % socket.gethostbyname(remote_host) return s...
''' Created on 2014-01-26 @author: Jonathan ''' class Length(object): def __init__(self, ft , in_): self.ft = ft self.in_ = in_ self.flag = False def __add__(self, length2): if type(length2) == Length: return self.__add__(length2.ft * 12 + length2....
# "paraparaparadise"と"paragraph"に含まれる文字bi-gramの集合を,それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.さらに,'se'というbi-gramがXおよびYに含まれるかどうかを調べよ. def n_gram(target, n) -> list: """creates n_gram Parameters ---------- target : str or list of str sentenst or list of words n : int Returns ------- lis...
#!/usr/bin/env python3 import socket, sys # create a tcp socket def create_tcp_socket(): print('Creating socket') try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except(socket.error, msg): print(f'Failed to create socket.') print('Error: {msg}') sys.exit() pri...
# -*- coding: utf-8 -*- """ Created on Tue Apr 21 20:50:25 2020 @author: Carlos Luco """ import platform import os import time def limpiar_pantalla(): time.sleep(10) print("\n" * 20) numero = 0 print("Programa Adivino de números entre 1 y 30") print("Escoja en su mente un núumero entre 1 y 30\n\n") limpiar_...
class Human: def __init__(self, name, last_name): self.name = name self.last_name = last_name def sayHello(self): print(f'Hello, my name is {self.name}') human1 = Human("John", "Doe") human2 = Human("Sidney", "Hill") human1.name = 'Johny' human1.sayHello()
def to_jaden_case(string): newArray = [] array = [1, 2, 3, 4] for x in array: newArray.append(x) newArray = [x for x in array] return ' '.join([x.capitalize() for x in string.split(' ')])
def multiply(a,b): result = a * b print(f'Полу1чилось: {result}') def count_middle_of(array): sum = 0 for item in array: sum = sum + item sred = sum / len(array) print(sred) array = [1, 4, 2, 4] count_middle_of(ray)ar
# Manually Consuming an Iterator with open('msg.txt') as f: try: while True: line = next(f) print(line,end='') except StopIteration: pass with open('msg.txt') as f: while True: line = next(f,None) if line is None: break print(line...
class Solution: def twoSum(self, nums, target): s = [] #declaring an empty list that will have indices for i in range(0,len(nums)): #iterating through the list, choosing pivot j = i+1 #incrementing the pivot and storing it in j for j in rang...
#ENTRY IS ALWAYS IN FORM OF STRING num1=input("Enter a number:") num2=input("Enter a number:") add=float(num1)+float(num2)#TYPE CASTING if float(num1)>=float(num2): diff=float(num1)-float(num2) else: diff=float(num2)-float(num1) mult=float(num1)*float(num2) div=float(num1)/float(num2) rem=float(num1)%float(num2...
distances = [int(i) for i in input().split()] cars = [int(i) for i in input().split()] bill = 0 for i, _ in enumerate(cars): av_cars = cars[i] / distances[i] if av_cars <= 30: bill += 1 elif 31 <= av_cars <= 60: bill += 1.5 elif 61 <= av_cars <= 120: bill += 3 elif av_cars ...
#Application TODO : Ajouter une tâche / Supprimer une tâche / Evaluer la charge de travail TacheTab = [] AjouterTache = "1" SupprimerTache = "2" ListerTache = "3" i = 0 n = 0 Tache = 0 while True: SaisieUser = input("Que voulez-vous faire ? Ajouter : 1, Supprimer : 2, Lister : 3 une(des) tâche(s) : ") print(Sa...
a = int(input()) b = int(input()) i = 0 if b >= a: for x in range(a,b+1): while i < 10: i+=1 print(f"{x} x {i} = {x*i}") i = 0 print('----------') else: print('Nenhuma tabuada no intervalo!')
x = 0; total = 0; x = float(input()) vicCoin = 0 while x != -1.0: vicCoin += x total = vicCoin * 2.5 x = float(input()) print(f'VC$ {vicCoin:.2f}') print(f'R$ {total:.2f}')
x = int(input()) y = int(input()) cont = 0 for i in range(x,y+1): if i>1: for z in range(2,i): if(i % z) == 0: break else: cont+=1 print(i) print(f'primos: {cont}')
def misterio(x,v,n): i = 0 while i < n and v[i] != x: i += 1 if i < n: return i else: return -1 a = ['b','x','d','v','e','r','e','p'] r1 = misterio('e',a,8) r2 = misterio('z',a,8) r3 = misterio('v',a,3) print(f'{r1}, {r2}, {r3}')
''' dentro de um arquivo de texto com o py de maneira automatica w -> Escrever a -> Alterar r -> Ler \n -> pula linha ''' #declara um nome para o arquivo, se existir ele vai trabalhar em cima daquele arquivo, senão ele cria um novo (dentro da pasta que o arquivo principal esta) #cria uma variavel e usa a função...
#Usuario digit o ano atual e de nascimento #variavel = dado que o usuario digitar nome = input() print(nome) #escreve a mensagem para o usuario nome = input("Digite seu nome") print(nome.title()) # digitar numero idade = int(input("Digite sua idade")) print(idade)
#criar lista grande x = [] for i in range (1, 1001): x.append(i) print(x) #ou der uma maneira mais facil y = list(range (1, 1001)) print(y) #precisa verificar a lista antes de remover um numero, para não dar erro z = [1, 2, 3, 4, 5] print(z) a = int(input('Digite um numero para apagar da lista')) if a...
# -*- coding: utf-8 -*- """ Created on Wed Oct 04 16:00:43 2017 @author: mmakwana """ def total_combo(money,final_amount): ''' money = list of denomation of moeny final_amount = final_amount to get the total combination ''' # Generate a blank array combination = [0 for i in xrange...
# -*- coding: utf-8 -*- """ Created on Thu Oct 12 21:46:45 2017 @author: mmakwana """ def gen_square_chain(num): def make_num(num): return (reduce(lambda x,y: x+y, map(lambda x: int(x)**2, str(num)))) if num == 1:return 1 elif num == 89: return 89 else: return gen_square_chain(make_num(nu...
from trader import Trader import numpy as np from utils import draw_from_uniform class Technical(Trader): """Represents heterogeneous type of traders in the artificial financial market model""" def __init__(self, unique_id, model_reference): """Generate a trader with specific type """ ...
#!/usr/bin/env python def Function(x, y, z=20): return (x + y + z); print "Sum: {}".format(Function(1, 5, 10)) print "Sum: {}".format(Function(x=1, y=5)) print "Sum: {}".format(Function(1, y=5, z=20)) print "Sum: {}".format(Function('I', 'am', 'Groot')) print "Sum: {}".format(Function([1], [5], [100]))
'''keep only the name of the file''' import os p = 'C:/Users/user/Desktop/test/dipole_value_from_vmd' #for every file in the 'p' path for r, d, f in os.walk(p): for file in f: if file.endswith(".txt"): #take only the name of the file, not the whole path (e.g. file.txt) base = os.pat...
datos = [] #creamos una lista vacia with open("ASCII.txt", encoding="utf8") as fname: lineas = fname.readlines() #cada linea es un elemento de la lista for linea in lineas: # bucle para quitar el espacio leido de la lista datos.append(linea.strip('\n')) #una vez limpio lo agrgamos a la lista datos #print (datos)...
from enum import Enum from string import ascii_uppercase import copy import itertools # used to determine the status of the box class Status(Enum): miss = -3 hit = -2 empty = 0 ship = -1 # used in conjunction with setting ship for easy readabilty class ShipAlignment(Enum): leftToRigh...
a=[1,2,1,4,7,2,4,6,4,8,9] b=[] for i in(a): if(i not in b): b.append(i) print b
# from tkinter import Tk,Label,mainloop # root = Tk() # myLabel = Label(root, text="Game of Life") # create label widget # myLabel.pack() # Shove label into the screen # height = 25 # width = 25 # for i in range(height): #Rows # for j in range(width): #Columns # b = Entry(root) # b.grid(row=i, ...
import random import os import time as t def calculate(op1, op2, operator): if operator == '+': return op1 + op2 elif operator == '-': return op1 - op2 elif operator == '*': return op1 * op2 else: return op1 % op2 class Game: number_of_questions = 0 correct_an...
polls = [] # As the name suggests, this program counts the votes and displays the name of the winner number = int(input('Enter the number of polls taken : ')) print('Please enter the polls under : ') for i in range(number): temp = input('Vote given to : ') polls.append(temp) votes = [] candidates = [] max_can...
# Lesson #1. Home work # Task #1. Print a poem print("How the sunshine gladdens the human heart—") print("How the sound of the falling rain") print("Will cause the tender tears to start,") print("And free the soul from pain.") print("J. W. Hammond, 'Oprimist'") # Task #2. # city_name1 = "Roseville" # city_name2 = "A...
# Homework # 8. Function print("--- Task #1.") # 1. Define the function which takes input number and returns the sign of the integer to its opposite. num = int(input("Enter any number: ")) def opposite(num): return num * -1 print(opposite(num)) print("\n --- Task #2.") # Task 2. Define the function 'angles_of_...
# Lesson #9. Lists (Arrays) # List is equivalent to arrays arr = [6, 1, -9, 4, 3] print(type(arr)) # -> returns class 'lists' print(arr) # outputs the list print(len(arr)) # returns the list's len (0...n) print(arr[0]) # returns first item -> 6 print(arr[-1]) # returns last item -> 3 print(arr[0 : -1]) # returns the ...
from abc import abstractmethod class AbstractUtility: def __init__(self, algorithm_ratio=1, budget_ratio=1): self.algorithm_ratio = algorithm_ratio self.budget_ratio = budget_ratio @abstractmethod def calculate_algorithms_utility(self, player_value_for_products: dict, product_turn_bought...
#This project will explore loading a table with rows and columns. #An idea I have had is to take a bunch of words of equal length and #put them into a table letter by letter. dLW = ["embezzlement","jeopardizing","journalizing","quixotically","maximization","extravaganza", "objectifying","unpublicized","exemplifying",...
def index_vowels(text): """ String -> Dictionary Take a string and associate each letter to its pos >>> index_vowels('') {} >>> index_vowels('Hello') {'e': 1, 'o': 4} """ d = {} f_text = text.casefold() for i, c in enumerate(f_text): if f_text[i] == 'a' or f_text[i] ...
import random """ 1. Each of BigDog, SmallDog, HouseCat and StrayCat will all have a “speak” method and a “description” attribute. The BigDog and SmallDog will both have a “sit” method. The HouseCat will have a “purr” method. a. You should use inheritance whenever possible to reduce duplication of code. """ cl...
import sqlite3 as lite import os # This file isn't ever used when the program is running, it just shows how I made my database. def CreateTable(): # Connect to the database and create a cursor for that connection. db = lite.connect('words.db') cursor = db.cursor() # Drop the words table, then create...
def banana_dict(num): count = 1 banana = 'banana' a_dict = {} while count <= num: b = (banana * count) a_dict[b] = count count += 1 return a_dict banana_dict(4)
import requests, json from datetime import datetime as dt # Reference for Accuweather API Documentation # https://developer.accuweather.com/apis # Store your apikey for AccuWeather in a file for security apiKey = open('apikey.txt','r').read() # Search for a location. We need the location key to search for weather re...
# -*- coding: utf-8 -*- """ Created on Thu Nov 26 19:02:06 2020 @author: uha18 """ ''' 2 Points Implement a function flatten1 that, when applied to a list of lists, returns a list of all elements of the embedded lists, preserving their order: >>> flatten1([[1,2,3], [4,5,6], [7], [], [8, 9]]): [1,2,3,...
# File Input/Output in Python import os def getDesktopPath(filename = ""): # next line is odd, but works in Windows/Mac/Linux homepath = os.getenv('USERPROFILE') or os.getenv('HOME') return homepath + os.sep + "Desktop" + os.sep + filename def fileExists(filename): return os.path.exists(fil...
#!/usr/bin/env python # coding: utf-8 from tkinter import * import pandas as pd import numpy as np import os import tkinter.font as tkFont from PIL import ImageTk, Image #get current working directory working_directory = os.getcwd() #import the pandas dataframe df = pd.read_csv(working_directory + '/images/recipe2.c...
# Напишите программу, которая считывает с клавиатуры два числа aa и bb, считает и выводит на консоль среднее арифметическое всех чисел из отрезка [a; b][a;b], которые кратны числу 33. # В приведенном ниже примере среднее арифметическое считается для чисел на отрезке [-5; 12][−5;12]. Всего чисел, делящихся на 33, на эт...
# Напишите программу, которая считывает список чисел lstlst из первой строки и число xx из второй строки, которая выводит все позиции, на которых встречается число xx в переданном списке lstlst. # Позиции нумеруются с нуля, если число xx не встречается в списке, вывести строку "Отсутствует" (без кавычек, с большой бук...
# Напишите программу, на вход которой подается одна строка с целыми числами. Программа должна вывести сумму этих чисел. # Используйте метод split строки. #first numbers = input().split() s = 0 for i in numbers: s += int(i) print(s)
# Имеется программа, код которой указан ниже. # Укажите, какие значения будут содержать списки в помеченных участках: # a = [1, 2, 3] # b = a # # значения списка b? # a[1] = 10 # # значения списка b? # b[0] = 20 # # значения списка a? # a = [5, 6] # # значения списка b? # Запишите значения списков в одну строку, ра...
# quiz_review # 표준 입력으로 문자열 여러 개와 숫자(실수) 여러 개가 두 줄로 입력됩니다. 입력된 첫 번째 줄은 키, 두 번째 줄은 값으로 하여 딕셔너리를 생성한 뒤 딕셔너리를 출력하는 프로그램을 만드세요. input().split()의 결과를 변수 한 개에 저장하면 리스트로 저장됩니다. a = input().split() b = list(map(float, input().split())) c = dict(zip(a[:], b[:])) print(c)
#slicing a = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] print(a[0:4]) # 인덱스 0부터 3까지 잘라서 새 리스트를 만듦 print(a[0:11]) print(a[1:1]) # 인덱스 1부터 0까지 잘라서 새 리스트를 만듦 print(a[1:2]) # 인덱스 1부터 1까지 잘라서 새 리스트를 만듦 print(a[4:7]) # 인덱스 4부터 6까지 요소 3개를 가져옴 #negative_slice print(a[4:-1]) #인덱스 증가폭 print(a[2:8:3]) # 인덱스 2부터 3씩 증가시키면서 인덱스 7까...
# formatting formatting = 'I am %s.' % 'james' print(formatting) name = 'Jacob' formatting2 = 'I am %s.' % name print(formatting2) # formatting_integer formatting3 = 'I am %d years old.' % 20 print(formatting3) # formatting_float formatting4 = 'I am %.2fyears old.' % 29.9 print(formatting4) # formatting_str ...
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> import turtle as t >>> >>> t.shape('turtle') >>> for i in range(4): t.forward(100) t.rt(100) >>> ================================ RESTART: Sh...
# 요소의 합계 구하기 a = [10, 10, 10, 10, 10] x = 0 for i in a: x += i print(x) # 파이썬 내장 함수 이용 print(sum(a))
#문자열 사용하기 hello = 'hello, world!' hello2 = "hello, world!" hello3 = '''hello, world!''' hello4 = """hello, world!""" print(hello, hello2, hello3, hello4, sep='\n') #문자열 규칙 #문자열 안에 (작은따옴표)를 넣고싶다면 (큰따옴표)로 묶기 string1 = "'Hello, Python'" print(string1) string2 = '"Hello, Python"' print(string2) single_quote = '''"안녕하세요...
#구구단 출력하기 #표준 입력으로 정수가 입력됩니다. 입력된 정수의 구구단을 출력하는 프로그램을 만드세요(input에서 안내 문자열은 출력하지 않아야 합니다). 출력 형식은 숫자 * 숫자 = 숫자처럼 만들고 숫자와 *, = 사이는 공백을 한 칸 띄웁니다. # 포매팅 이용 dan = int(input()) for x in range(1, 10): print('{} * {} = {}'.format(dan, x, dan*x)) # 정석 풀이 dan = int(input()) for i in range(1, 10): print(dan, '*', i, '...
print("Welcome to the Band Name Generator!") city_name = input("What city did you grow up in?\n") pet_name = input("What is the name of your pet?\n") print("Your band name is " + city_name + " "+ pet_name)
import sqlite3 from tkinter import * from datetime import datetime def register(): ext=Tk() ext.title("SIGN UP") l5=Label(ext,text="REGISTRATION",fg="yellow",bg="black") l5.grid(row=0,column=0,padx=130,pady=40) l6=Label(ext,text="Name") l6.grid(row=2,column=0) l7=La...
n=int(input()) list1=list(map(int,input().split())) even=0 odd=0 i=0 while i<n: if list1[i]%2==0: even+=1 else: odd+=1 i+=1 if even>odd: print("READY FOR BATTLE") else: print("NOT READY")
def sort_me(remaining_list): if len(remaining_list) == 0: return None if len(remaining_list) == 1: return remaining_list lowest = remaining_list[0] indexed_at = 0 for index, number in enumerate(remaining_list): if number < lowest: lowest = number index...
mensaje='cántaros vacíos' codificado=[] for i in mensaje: codificado.append(ord(i))#el método chr() es el inverso de ord() print ('la letra {} tiene un unicode de: {}'.format(i,ord(i))) print ('{}: unicode de cada letra del menaje anterior = {}'.format(mensaje,codificado))
# -*- coding: utf-8 -*- """ Created on Sun Jan 19 09:13:49 2020 @author: Aspire """ import random x=[] y=[] for z in range(0,20): x.append(random.randrange(0, 15)) for z in range(0,20): y.append(random.randrange(0, 15)) print (x) print (y)
# Uses python3 from sys import stdin def fibonacci_sum_squares_naive(n): x = [] x.insert(0, 0) x.insert(1, 1) sum = 1 n=n%60 for i in range(2, n + 2): x.insert(i, (x[i - 1] + x[i - 2]) % 10) sum = x[n]*x[n+1] if n==0: return 0 else: return sum%10 if __name...
# python3 import sys from collections import namedtuple Answer = namedtuple('Answer', 'p q len') def PolyHash(sa, m): hash_value = 0 for i in reversed(range(len(sa) )): hash_value = (hash_value * 263 + ord(sa[i])) % m return hash_value def hashdict(sb, l1, m): D = {} subs = sb[len(sb) - l...
# Uses python3 import sys def get_majority_element(a): counts = dict() for i in a: counts[i] = counts.get(i,0) + 1 # print(counts) if counts[i] > n/2: return 1 return 0 if __name__ == '__main__': n = int(input()) a = list(map(int, input().split())) print(get_...
data=[2,3,5,7,4,9,6] # def even(self): # for i in data: # if i%2==0: # print(i) # even(data) even=list(filter(lambda n : n%2 == 0, data)) print(even)
#Dynamic type System here if you passed the int value then it performs the aaddition operation ,if yoy passed string value then it performed string concatenation operation def add1(a,b): return a+b
#map function in python #map function returns a result in list format def addition(a): return a*a; numbers=(1,2,3) list1=map(addition,numbers) print(list(list1)) #map with lambda function lambada1=lambda x:x * x list2=map(lambada1,numbers) print(list(list2))
#list #list is sequence of object #list is mutable c=["1","2","3","4","5","6"] print("list element are :",c) print("4th element of list is :",c[4-1]) c.append(7) print("After Appending element list element are :",c) print("separte each char of the string godigital",list("godigital"))
#Relational Operator Operation ==,<,>,<=,>= #equality g=20 print(g==20) #inequality print(g!=20) if g<30: print("g value is less than 30")
#while loop while True: n=input("enter number") if int(n)%7==0: break print(n)
#for loop #it visit every element in set of elements #it iterate and visit to every element def for_loop(): c=["1","2","3","4","5","6"] print("list out all values of list using for loop\n") for list1 in c: print(list1) dict={'Name':'Tushar','email':'patiltushar9820@gmail.com'} print...
import pathlib from src import file class Merger: """ Класс Merger осуществляет сортировку входящих файлов и передает данные для записи в исходящий файл """ def __init__(self, checker, comparator, output_file: str, input_files: list) -> None: """ Инициализирует экз...
# -*- coding: utf-8 -*- """ Created on Tue Jan 19 18:19:58 2021 @author: etzellux """ liste = [] while True: print("Entry:",end="") text = input("") if text.lower() == "quit": break elif text.isalpha() and text != "quit": print("Geçersiz giriş") break else: l...
# CircuitPlaygroundExpress_NeoPixel import time import board import neopixel pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=.2) pixels.fill((0, 0, 0)) pixels.show() def simpleCircle(wait): RED = 0x100000 # (0x10, 0, 0) also works YELLOW = (0x10, 0x10, 0) GREEN = (0, 0x10, 0) ...
class Test(object): """docstring for Test""" def __init__(self): self.__num=100#属性私有化 @property#通过装饰器使用 property 方法 def num(self): return self._num @num.setter def num(self,num): self._num =num #num=property(set_num,get_num)#对外提供方便的访问方法 #通过对属性的私有化并对外提供访问方法可以保证外部合理访问对象属性 t=Test() t.num=200 print(t.num) ""...
from threading import Thread,Lock import time #互斥锁的写法 """ lock = Lock() num = 0 def demo1(): global num for x in range(1000000): lock.acquire() num=num+1 lock.release() print(num) def demo2(): global num for x in range(1000000): lock.acquire() num=num+1 lock.release() print(num) thread1 = Thread(targe...
#服务器的编写 from socket import* from threading import Thread #创建套节字 用于链接 tcp_sever_socket = socket(AF_INET,SOCK_STREAM) #绑定地址 tcp_sever_socket.bind(('',8879)) #设定为被动监听模式 tcp_sever_socket.listen(11) #得到客户端的套节字,等待客户端链接 用于传输数据的套节字 def recvdate(socket,address): while True: recvdate=client_socket.recv(1024) if len(recvdat...
skaicius1= int(input("Iveskite 1 skaiciu : ")) skaicius2= int(input("Iveskite 2 skaiciu : ")) veiksmas = input("Iveskite matematini veiksmas : + , - , / ,* .") if veiksmas == "+": print(f"Sudetis {skaicius1+skaicius2}") elif veiksmas == "-": print(f"Skirtumas {skaicius1 -skaicius2}") elif veiksmas == "/": ...
import datetime class Darbuotojas: def __init__(self,vardas,valandos_ikainis,dirba_nuo): self.vardas = vardas self.valandos_ikainis = valandos_ikainis self.laikas_now = datetime.datetime.today() self.dirba_nuo = datetime.datetime.strptime(dirba_nuo,"%Y,%m,%d,%H,%M,%S") prin...
a = int(input("Iveskite A : ")) b = int(input("Iveskite B : ")) if a<b: print("A mazesnis uz B") elif a==b: print("A == B") else: print("A didesnis uz B")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 5 14:48:05 2019 @author: davidhagan Some stuff on Strings str """ this = '|'.join(['dave','ami','thatcher','Shanika']) departure, separator, arrival = "London:Edinboro".partition(':') departure, _, arrival = "London:Edinboro".partition(':') t...
n = int(input("Start from: ")) m = int(input("End on: ")) for i in range(n, m + 1): print(i)
height = int(input("Height? ")) width = int(input("Width? ")) for i in range(0, height): if i == 0 or i == height - 1: print('*' * width) else: for j in range(0, width): if j == 0 or j == width - 1: print('*', end='') else: print(' ', end=...
# initialize variables plaintext = '' key = -1 # get plaintext and cipher value from user while plaintext == '': plaintext = input("Please enter your text: ") while key < 0: key = int(input("Please enter a non-negative integer key: ")) # prepare output line print("ciphertext: ", end='') # iterate through pla...
matrix1 = [[1, 3, 1], [2, 4]] matrix2 = [[5, 2, 5], [1, 0]] result = [] for i in range(0, len(matrix1)): result.append([]) for j in range(0, len(matrix1[i])): result[i].append(matrix1[i][j] + matrix2[i][j]) print(result)
def file_reader(file): with open(file, 'r') as file_handle: contents = file_handle.read() return(contents) if __name__ == "__main__": file_name = input("Please enter a file name: ") print(file_reader(file_name))
def file_writer(file): with open(file, 'a') as file_handle: new_content = input("What would you like added to the file? ") file_handle.write(new_content + '\n') if __name__ == "__main__": file_name = input("Please enter a file name: ") file_writer(file_name)
original_string = input("Give me a string in all lowercase! ") print(original_string.upper())
##Welcome message --> game begin print 'Welcome to my game. This game is sweet.' ##ask the player for his name player_name = raw_input('What\'s is your name: ') ## check/ask for player name and display it if player_name == '': print'\n' print 'You entered an empty string!' else: print 'Your name is {}'.format(pl...