text
stringlengths
37
1.41M
words =[] with open('filtered_words.txt','r+',encoding='utf8') as f: for i in f.readlines(): if i[-1]=='\n': i = i[:-1] words.append(i) input_key = input('请输入词') if input_key in words: print('Freedom') else: print('Human Rights')
# /usr/local/bin/python # encoding definition """coding=utf-8""" # import packages from colorama import Fore, Back, Style # area function definition def getArea(userLength, userHeight): return userLength * userHeight # perimeter function definition def getPerimeter(userLength, userHeight): return (userLen...
import tkinter import os import urllib.request mainWindow = None packer = [] #An option class which contains a box which text can be put in and the label to describe the box class Option: def __init__(self, label, box): self.label = label self.box = box #Sets the window in which the ...
# -*- coding: utf-8 -*- import sqlite3 def insert_data(values): with sqlite3.connect("database.db") as db: cursor = db.cursor() sql = "INSERT INTO Product (Name, Price) VALUES (?,?)" cursor.execute(sql,values) db.commit() if __name__ == "__main__": product = ("American...
#Create an empty set s = set() #Add elements to the set s.add(1) s.add(2) s.add(3) s.add(4) s.add(3) #print out the set print(s) #Remove element in a set s.remove(2) #Print after deleting an element print(s) #Print how many elements are there in a set print(f"The set has {len(s)} elements")
import sympy as sym import matplotlib.pyplot as plt a=[] b=[] c=[] i=-20 def f(x): return x**2-5*x-6 for i in range (-20,21): x=i f1 = 2*x - 5 tol = x y = x - (f(x)/f1) count = 0 #print(i) while(abs(tol)>10**(-5)): y = x - (f(x)/f1) #print(y) tol = y - x ...
f = open("./3-input.txt", "r") lines = f.readlines() wire_1 = lines[0].split(",") wire_2 = lines[1].split(",") # wire_1 = "R8,U5,L5,D3".split(",") # wire_2 = "U7,R6,D4,L4".split(",") def manhattan_distance(x, y): return sum(abs(a-b) for a, b in zip(x, y)) path = {} last_coordinate = [0, 0] steps_offset = 0 fo...
name = "Asen Chekov" hi = "Hello, there!" # function definition def backwards(string): return string[::-1] # string slicing # [start:stop:step] print(name[::-1] + " " + hi) print(backwards(name)) print(backwards(hi)) print(hi*3) print(bool("False")) # for loop for number in range(-10,10): print(number)
def add(a, b): print "ADDING %d + %d" % (a, b) return a + b def subtract(a, b): print "SUBTRACTING %d - %d" % (a, b) return a - b def multiply(a, b): print "MULTIPLYING %d * %d" % (a, b) return a * b def divide(a, b): print "DIVIDING %d / %d" % (a, b) return a / b print "Let's do some math with just functi...
from sys import argv from os.path import exists script, from_file, to_file = argv print "Copying from %s to %s" % (from_file, to_file) # We could do these two on one line, how? # in_file = open(from_file) indata = open(from_file).read() print "The input file is %d bytes long" % len(indata) print "Does the output f...
age = int(raw_input("How old are you? ")) height = raw_input("How tall are you? ") weight = raw_input("How much do you weigh? ") print "So, you're %i years old, %s tall and %s heavy." % ( age, height, weight) # study drills: look up pydoc, what is it? # pydoc is a way to look at documentation for python as well as d...
import argparse import nltk import os class Parse: """A parser that processes sentences acccording to the rules of a specified grammar.""" def parse(self, grammarFilePath, sentenceFilePath): """Parses the sentences found in sentenceFilePath using the grammar found in grammarFilePath.""" #...
from MyCNN import * import data_loader import torch import torch.nn as nn import torch.utils.data as Data import torchvision import torchvision.transforms as transforms import numpy as np import matplotlib.pyplot as plt # mean and std of cifar10 in 3 channels cifar10_mean = (0.49, 0.48, 0.45) cifar10_std = (0.25, 0...
# coding=utf-8 class MoneyBox: def __init__(self, capacity): # конструктор с аргументом – вместимость копилки self.capacity = capacity self.current_v = 0 def can_add(self, v): # True, если можно добавить v монет, False иначе return self.current_v + v <= self.capacity ...
class Solution: # @param n, an integer # @return an integer def climbStairs(self, n): if(n<3): return n; a=1; b=2; for i in range(n-2): a,b=b,a+b; return b; s=Solution(); print s.climbStairs(3); print s.climbStairs(4); print s.climbStairs(5);
import COMMON class Solution: # @param head, a ListNode # @return a ListNode def insertionSortList(self, head): if(head==None): return None; result=head; p1=head; while(True): # from start to p1 ,it's a sorted List p2=p1.next; if(p2==None): break; if(p2.val>=p1.val): p1=p2; continu...
class Solution: # @return a boolean def isValid(self, s): array=[]; for c in s: if(c=="(" or c=="{" or c=="["): array.append(c); elif (array==[]): return False; else: first=array.pop(); if(first=="(" and c==")"): continue; if(first=="{" and c=="}"): continue; if(first==...
class Solution: # if we have a array like # 4 5 6 7 3 9 8 2 1 # we need to swap 3 and 8, # then reverse the 9 3 2 1 def find_next(self,prev): n=len(prev); result=prev[:]; pos=n-2; while(pos>=0): if(prev[pos]>prev[pos+1]): pos-=1; else: # pos now point to the first place to swap secon...
from tkinter import * import tkinter.messagebox # person class variable used to store information on all person objects class Person: def __init__(self): self.f_name = "fname" self.l_name = "lname" self.age = 0 self.gender = "male" self.ethnicity = "black" ...
import sqlite3 class SQL: """ sql class containing all methods, which connects the project to database """ @staticmethod def sql_connection(database="database"): """ create database connection """ return sqlite3.connect(database) @staticmethod def execute_query(query, params=""): ...
# ''' # Basic hash table key/value pair # ''' class Pair: def __init__(self, key, value): self.key = key self.value = value # ''' # Basic hash table # Fill this in. All storage values should be initialized to None # Done # ''' class BasicHashTable: def __init__(self, capacity): sel...
# Maze Program Written by Michael Toth setMediaPath('/Users/toth/Documents/Github/turtlemaze') import time import random class Maze(object): """ Solves a maze with a turtle in JES """ def __init__(self): """ Initializer, sets image """ self.image = makePicture('maze.jpg') self.w = makeWorld(getWidth(se...
from datetime import datetime, date, time, timedelta def str_to_date(date, format="%Y-%m-%d"): if type(date) == str: date = datetime.strptime(date, format) return date def str_to_time(time, format="%H:%M:%S"): if type(time) == str: time = datetime.strptime(time, format).time()...
lucky_num = 28 count = 0 #for循环列表 magicians=['alice','david','carolina'] for magician in magicians: print('%s that was a great trick!'%magician.title()) while count<3: in_num = int(input("input your guess num:")) if in_num==lucky_num: print("bingo!") break elif in_num > lucky_num: ...
#!/usr/bin/env python # HW04_ch08_ex04 # The following functions are all intended to check whether a string contains # any lowercase letters, but at least some of them are wrong. For each # function, describe (is the docstring) what the function actually does. # You can assume that the parameter is a string. # Do not...
from turtle import Screen from paddle import Paddle from ball import Ball from scoreboard import Scoreboard import time screen = Screen() screen.bgcolor("black") screen.setup(width=800, height=600) screen.title("Pong") # Used to turn off animation # You need manually update any changes required on the scree...
""" HTML on Popups - Simple Note that if you want to have stylized text (bold, different fonts, etc) in the popup window you can use HTML. """ import folium import pandas data = pandas.read_csv("volcanoes.txt") latitude = list(data["Latitude"]) longitude = list(data["Longitude"]) elevation = list(data[...
"""Plain English start define function to calculate what percentage of grades lie above the average initialize counter and percentage create a loop that iterates through the Final.txt file add 1 to counter that tracks how many grades exist above the average value of the grades divide the count of gr...
from bs4 import BeautifulSoup import ssl #import urllib2 import os import json import requests import urllib import urllib.request from urllib.request import urlopen class DownloadImagesService(object): """ This class provides a functionality to download images from google search based on a query string ...
''' leetcode - 62 - unique paths - https://leetcode.com/problems/unique-paths/ time complexity - O(2^N*2) approach - recursive approach ''' class Solution(object): def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ i=0 j=0 ret...
# 문제 : # 생일을 입력하면 태어난 연도의 띠를 리턴해주는 함수 # # 힌트: # 1980년도는 원숭이 띠입니다. # 쥐 – 소 – 호랑이 – 토끼 – 용 – 뱀 – 말 – 양 – 원숭이 – 닭 – 개 – 돼지 띠 = ['쥐', '소', '호랑이', '토끼', '용', '뱀', '말', '양', '원숭이', '닭', '개', '돼지'] def zodiac_sign(birthday): year = birthday.split('-')[0] return f'{year}는 {띠[(int(year)+8) % 12]}의 해입니다.' # # ani...
def phonenumber_to_region(phone): phone_numbers = {"02": "서울", "051": "부산", "053": "대구", "032" : "인천", "062": "광주", "042": "대전", "052": "울산", "044": "세종", "031": "경기", "033": "강원", "043": "충북", "041": "충남", "063": "전북", "061": "전남", "054": "경북", "055":...
# -*- coding: utf-8 -*- """ Created on Wed Sep 2 09:25:22 2020 @author: Amarnadh """ x=[False,False,False,False] print("all=",all(x)) #if any one value is false, then it retursn false print("any=",any(x)) #if any one value is true, then it retursn true print("ASCII char is ",chr(65)) #returns character of ASCII val...
# -*- coding: utf-8 -*- """ Created on Tue Aug 25 00:22:04 2020 @author: Amarnadh """ x=[10,20,30,40,50] print("x=",x) y=x y+=[60,70] #in list this expression acts like a reference to list 'x' print("x=",x) y=y+[80,90]#in this case, it doesnt acts lika a reference to the list 'x' print("x=",x) print("y=",y) a=3 a+=1...
import timeit from time import sleep # def maopao_sort(alist): # """mao pao pai xv""" # for cm in range(len(alist)-1,0,-1): # for cn in range(cm): # if alist[cn]>alist[cn+1]: # temp = alist[cn+1] # alist[cn+1] = alist[cn] # alist[cn] =...
# -*- coding: utf-8 -*- # python栈的实现 class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(sel...
from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense # Initialise the CNN classifier = Sequential() # 1. Add Convolution layer - this describes the feature maps, args = no. of features, rows, columns c...
import datetime from calendar import monthrange #******************************************************************* # Extract something bounded by <string></string> # tag is not decorated with "<" or ">" or "/" # The opening tag is assumed to be of the form "<tag...>" (where "..." is random stuff) # The closing tag ...
from Tkinter import * #from Tkinter import messagebox top = Tk() top.geometry("{0}x{1}+0+0".format(top.winfo_screenwidth(), top.winfo_screenheight())) t1 = Button(top, text = "", bg = "Yellow") t1.place(x = 50, y = 50) top.mainloop()
# loop # for loop # find the min # place in the front integerList = [9,4,18,3,8,66,9,11] def insert(list,src,dest): # src: the index of which to be inserted # dest: the index of where to insert in a = list[src] for i in range(src-1,dest-1,-1): list[i+1] = list[i] list[dest] = a return...
""" This program help work with some kind of JSON data sample and collate out the needed set of key->values into a specified file format to save into. """ import json from random import randint def collate_json_values_to_file(): with open('file.json', 'r') as o: file_object = json.load(o) ...
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> word = 'banana' >>> count = 0 >>> for letter in word: if letter == 'a': count = count + 1 >>> print(count) 3 >>> word = 'banana' >>> prin...
from math import exp, pi, sqrt def get_criteria_dict_and_criteria_count(csv_data): """ Analyse data in file and delete all non-usable stuff :param csv_data: :return: count of criterias in dict and dict of criterias """ criteria_dict = {} criteria_count = 0 for key in csv_data: ...
def checkConsecutivePowers(num): sum = 0 numList=list(str(num)) # разбиваем число for power,val in enumerate(numList): # присваем каждому числу индекс sum+=pow(int(val),power+1) # находим сумму if sum==num: # проверяем return True else: return False def sum_dig_pow(a, b): # range(a, b + 1) will be studied b...
# Your parking gargage class should have the following methods: # - takeTicket # - This should decrease the amount of tickets available by 1 # - This should decrease the amount of parkingSpaces available by 1 # - payForParking # - Display an input that waits for an amount from the user and store it in a variable # - If...
#Generate a hailstone sequence number = int(input("Enter a positive integer:")) count = 0 print("Starting with number:", number) print("Sequence is: ", end=' ') while number > 1: #stops the sequence when we hit 1 if number%2: #don't be fooled by the 2, this means the number is odd! number = number * 3 + ...
import math #let's start with defining the function that asks for input def get_vertex(): x = float(input(" Please enter x: ")) y = float(input(" Please enter y: ")) return x,y #for get_triangle we simply need to call get_vertex three times and adding a print to differentiate each one def get_triangle...
def reverse(string): string = string[::-1] return string s =input("enter a string") print(reverse(s))
''' programa que tenha uma tupla unica com nomes de produtos e seus respectivos preços na sequencia mostre uma listagem de preços organizando dados em forma tabular. ''' listagem = ('Tenis',1.355, 'Camisa',245.25, 'Calca',600.12, 'Bermuda',52.15, 'Cinto',182.00, 'Meias',250.00, 'Jaqueta',1.255) print('-'*4...
#matriz matriz = [[1,2,3],[4,5,6],[7,8,9]] for x in matriz: print(x,end='') print('\n') # ------------- matriz[0][0] = 'X' matriz[1][1] = 'X' matriz[2][2] = 'X' matriz[0][1] = 0 matriz[0][2] = 0 matriz[1][0] = 0 matriz[1][2] = 0 matriz[2][0] = 0 matriz[2][1] = 0 print('-'*20) for y in range(len(matriz)): ...
''' http://www1.caixa.gov.br/loterias/loterias/lotofacil/lotofacil_pesquisa_new.asp Obtem dados da web <img src="/dolar_hoje/img/icon-moeda-2.png" alt="Dólar Comercial" title="Dólar Comercial"> <input type="text" value="3,81" class="text-verde" id="comercial" calc="sim"> https://www.melhorcambio.com/dolar-hoje ''' impo...
# teste laço While '''n = 1 cont = 0 while n != 0: n = int(input('Valor: ')) if n != 0: cont += 1 print('FIM!', cont)''' # leia a idade e o sexo de pessoas: - qts pessoas com mais de 18 anos - # qts homens foram cadastrados - qts mulheres tem menos de 20 anos cont = 1 idade = 0 contFinal = 0 nome = ' ...
# # # valores = [] for cont in range(0,4): valores.append(int(input('Valor: '))) for i,v in enumerate(valores): print(f'o valor {v} esta no indice {i}.') print('OK!')
__author__ = 'abdullahabdullah' # --- Dictionaries --- adres = {'Abdullah': 'yenisehir','Feride':'Uskudar'} print(adres) adresi = adres['Abdullah'] print(adresi) print('Adresi : {}'.format(adresi)) #degisiklik adres['Abdullah'] = 'Kadikoy' print(adres) # ekleme adres['Ali'] = 'Uskudar' print(adres) # silme del a...
import sys #Get string from input and encode to hex html_string = (input()).encode('utf-8').hex() #returns utf-8 encoded byte size def utf8len(s): return len(s.encode('utf-8')) split_list = [] temp = '' #Iterate over every character until a 80 byte data slice is made for char in html_string: if utf8len(tem...
#!/usr/bin/python3 """ script that takes in the name of a state as an argument and lists all cities of that state, using the database hbtn_0e_4_usa """ if __name__ == "__main__": from sys import argv import MySQLdb usr = argv[1] pswd = argv[2] database = argv[3] cityName = argv[4] dbConne...
#!/usr/bin/python3 def search_replace(my_list, search, replace): return ([replace if ele is search else ele for ele in my_list])
#!/usr/bin/python3 def text_indentation(text): ''' This is the 5-text_indentation module This function that prints a text with 2 new lines after each of those characters: ., ? and : There should be no space at the beginning or at the end of each printed line text must be a string, otherwise...
#!/usr/bin/python3 def say_my_name(first_name, last_name=""): """ This is the say_my_name module This is a function that prints My name is {first_name} {last_name} """ if (isinstance(first_name, str) is False or first_name is None): raise TypeError("first_name must be a string") if (isin...
class Solution(object): def findDuplicates(self, nums): """ :type nums: List[int] :rtype: List[int] """ for i in range(len(nums)): while nums[i] != (i + 1) and nums[nums[i] - 1] != nums[i]: value = nums[i] - 1 nums[i], nums[value] =...
import random class Solution(object): def __init__(self, nums): """ :type nums: List[int] :type numsSize: int """ self.d = nums def pick(self, target): """ :type target: int :rtype: int """ answer = [] for i, v in...
num = int(input()) total = 0 for x in range(1, 11): if x == len(str(num)): total += (num - 10**(x - 1) + 1) * x elif x < len(str(num)): total += (9 * 10**(x - 1)) * x else: break print(total)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None cache = {} class Solution(object): def rob(self, root): """ :type root: TreeNode :rtype: int """ return ...
""" @author: Brando Sánchez BR7 @Version: 12/03/19 INSTITUTO POLITÉCNICO NACIONAL ESCUELA SUPERIOR DE CÓMPUTO CRYPTOGRAPHY """ def main(): base = 50321 exp = 60749 modN = 77851 result = squareAndMultiply(base, exp, modN) print(str(base) + " to " + str(exp) + " mod " + str(modN) + " is " + str(result)) de...
temp = list() # lista temporária, usada pra guardar input do usuário par = list() impar = list() lista = par,impar # movendo listas par e impar para Lista for i in range(0,7): # Entrada do usuário temp.append(int(input('Insira um número: '))) for i in temp: # Validação de par/impar if i % 2 == 0: list...
import json from pprint import pprint with open('swjson.json') as data_file: data = json.load(data_file) contador=0 print("Ahora listará las naves que aparezcan en el episodio que quieras") episodio=input("Introduzca el número del episodio: ") listapelis=[] for pelicula in data ["results"]: for titulo in pel...
import json, time from pprint import pprint with open('ej3.json') as data_file: data = json.load(data_file) nombremun=input("Introduzca un municipio: ") for provincia in data["lista"]["provincia"]: nombreprov=provincia["nombre"]["__cdata"] if type(provincia["localidades"]["localidad"])==list: for municipi...
import json from pprint import pprint with open('books.json') as data_file: data = json.load(data_file) cadena=input("Introduzca la cadena por la que quiere buscar el titulo: ") for libro in data['bookstore']['book']: if libro["title"]["__text"].startswith(cadena): print("Titulo:",libro["title"]["__text"],...
#! python3 """ A function that takes a string and does the same thing as the strip() string method. If no other arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string. Otherwise, the characters specified in the second argument to the func...
#! python3 """ a program that opens all .txt files in a folder and searches for any line that matches a user-supplied regular expression. The results should be printed to the screen. """ import os, re print("Whats is the path of the folder?") path = r"{}".format(input()) print("What is the regex pattern?") pattern = r...
""" Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only u...
""" Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. (Note: If implementing in Java, please use a character array so that you can perform this operation i...
list = [1,2,4,6,8] target = 9 for i,j in enumerate(list): if target - j in list: print(i) for i in range(len(list)): for j in range(len(list)): if list[i] + list[j] == target: print(i,j)
import os #EMPIEZA LA CLASE class Libro: titulo = '' autor = '' #1º METODO PARA GUARDAR def guardar(self): self.titulo = input("Indica el título de un libro: ") self.autor = input("Indica el autor: ") f = open("text.txt", "r") lectura=f.read() resu...
import random import math def isCoPrime(i,z): if(math.gcd(i,z)==1 and i!=z): return True return False def isPrime(x): if x >= 2: for y in range(2, x): if not (x % y): return False else: return False return True primes = [i for i in range(1,1000) if isPrime(i)] p = random.choice(primes) q= random.cho...
#Algorithm to win is n n e e s s #https://github.com/liljag/tileTraveller #import os, sys x, y = 1, 1 #print("You can travel: (N)orth.") N = True S = False E = False W = False win = False while(win == False): string = '' if(N == True): string = string+ '(N)orth' if(E==True): string = string + ' or (E)ast' if...
from tkinter import * win = Tk() win.title("CALCULATOR") equation = StringVar() expression = "" def input_number(number, equation): global expression expression = expression + str(number) equation.set(expression) def clear_input_field(equation): global expression expression = "" equation.set(...
import os import sys import logging from Calculator import Calculator logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO")) log = logging.getLogger("S_Expr : ") # Validate the list of keywords # For now add and multiply are allowed ones # We evaluate the first sub-word of the sent partial expression and vali...
# Import library functions of 'pygame' import pygame # Initialize pygame pygame.init() # constants BLACK = (0, 0, 0) WHITE = (255, 255, 255) BLUE = (0, 0, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) PI = 3.141592653 # screen size size = (400, 500) screen = pygame.display.set_mode(size) pygam...
def checkAnagram(str1, str2): letras_str1 = list(str1) letras_str2 = list(str2) letras_str1.sort() letras_str2.sort() i = 0 for letra in letras_str1: if letra is not letras_str2[i]: return False i = i + 1 return True print('Ingresar primer palabra: ') str1=input(...
""" To be safe, the CPU also needs to know the highest value held in any register during this process so that it can decide how much memory to allocate to these operations. For example, in the above instructions, the highest value ever held was 10 (in register c after the third instruction was evaluated). """ from coll...
""" In the example above, there were 2 groups: one consisting of programs 0,2,3,4,5,6, and the other consisting solely of program 1. How many groups are there in total? """ from collections import namedtuple, deque import fileinput inputs = [ "0 <-> 2", "1 <-> 1", "2 <-> 0, 3, 4", "3 <-> 2, 4", "...
""" How many programs are in the group that contains program ID 0? """ from collections import namedtuple, deque import fileinput # inputs = [ # "0 <-> 2", # "1 <-> 1", # "2 <-> 0, 3, 4", # "3 <-> 2, 4", # "4 <-> 2, 3, 6", # "5 <-> 6", # "6 <-> 4, 5", # ] inputs = fileinput.input() Progr...
# -*- coding: utf-8 -*- TEMPERATURA_CRITICA = 60 class Temperatura(Exception): def __init__(self, temperatura): self._temperatura = temperatura def __str__(self): return "Se ha alcanzado la temperatura crítica: {}. Todos muertos!!!".format(self._temperatura) def preparar_materia...
''' Expresiones regulares libreria re ''' # [ ] = delimits a group of characters, any of which are a match # [0-9] = matches characters between zero and nine # [^0-9] = matches any characters except zero through nine # [0-9]* = matches number of Gmes (zero or more repeGGons) # . = matches any character exce...
#!/usr/bin/env python3 def main(txtFile): f = open(txtFile, 'r') txtlist = f.read().split() try: numbers = [int(x) for x in txtlist] except: print("Error converting list to ints") return -1 for i in range(len(numbers)-1): ans = 2020 - numbers[i] for j in rang...
from itertools import product from collections import namedtuple class atom(namedtuple('atom',['num','bval'])): """ Represents an integer with an associated boolean value """ def __str__(self): return '{}{}'.format('' if self.bval else '~', self.num) def __repr__(self): return '({},{})...
#assert.py #此示例assert用法 def get_age(): a = int(input("请输入年龄: ")) assert 0 <= a <= 140, '年龄不在合法范围内' return a try: age = get_age() except AssertionError as e: print("错误原因是:", e) age = 0 print("年龄是:", age)
#21_try_except_as.py #此示例示意try-except语句的用法 def div_apple(n): print('%d个苹果您想分给几个人?' % n) s = input('请输入人数: ') #<<=可能触发ValueError错误异常 cnt = int(s) #<<==可能触发ZeroDivisionError错误异常 result = n/cnt print("每个人分了",result, '个评估') #以下是调用者 #用try-except语句捕获并处理ValueError类型的错误 try: print("开始分平台...
#练习: # 修改前的Student 类, # 1) 为该类添加初始化方法,实现在创建对象时自动设置 '姓名', '年龄', '成绩' 属性 # 2) 添加set_score方法能为对象修改成绩信息 # 3) 添加show_info方法打印学生对象的信息 class Student: def __init__(self, name, age=0, score=0): '''初始化方法用来给学生对象添加'姓名'和'年龄'属性''' # 此处自己实现 self.name = name self.age = age self.score...
#方法1 #def mymax(a, b): # s = max(a, b) # return s #方法2 #def mymax(a, b): # if a> b: # return a # else: # return b #方法3 def mymax(a, b): if a > b: return a return b print(mymax(100, 200)
class Mylist(list): def insert_head(self, value): '''将value值插入到列表前面去 ''' self.insert(0, value) L = Mylist(range(1,5)) print(L) #[1, 2, 3, 4] L.insert_head(0) print(L) #[0, 1, 2, 3, 4] L.append(5) print(L) #[0,1,2,3,4,5]
#raise.py #此示例用raise语句来发出异常通知 #供try-except语句来捕获 def make_except(): print("开始....") raise ZeroDivisionError #手动发生一个错误通知 print("结束....") #try语句解决上述问题 try: make_except() print("make_except调用完毕!") except ZeroDivisionError: print("出现了被零除的错误,已处理并转为正常状态") ###########################################...
#联系:输入三行文字,让这些文字一次以20字符的宽度右对齐输出 #如: #请输入第一行:hello world #请输入第二行:abcd #请输入第三行:a #输出结果: # hello world # abcd # a #之后,思考: #能否以最长字符串的长度进行右对齐显示(左侧填充空格) s1 =input("请输入第一行: ") s2 =input("请输入第二行: ") s3 =input("请输入第三行: ") print('---以下是所有字符串占20个字符串宽度') print('%20s' % s1) print('%20s'...
#写程序,用while循环计算 # 1 + 2 + 3 + 4 + ...+ 99 + 100的和 i = 1 s = 0 #此变量保存所有数的和 while i <= 100: s += i #把当前的i值累加到s i += 1 else: print() print("1+2+3+...+99+100的和是:", s)
#instance_method.py #此实例示意如何用实例方法(method)来描述Dog类的行为 class Dog: def eat(self, food): '''此方法用来描述小狗吃东西的行为''' print("小狗正在吃:", food) def sleep(self, hour): print("小狗睡了",hour,"小时") def play(self, obj): print("小狗正在玩", obj) #创建一个Dog的类的实例: dog1 = Dog() dog1.eat('狗粮') #self-dog...
#练习 : # 1. 写一个函数 mysum(), 可以传入两个实参或三个实参. # 1) 如果传入两个实参,则返回两个实参的和 # 2) 如果传入三个实参,则返回前两个实参的和对第三个实参求余的结果 # print(mysum(1, 100)) # 101 # print(mysum(2, 10, 7)) # 5 返回:(2+10) % 5 #方法1 #def mysum(a, b, c=1): # if c !=1 : # return (a + b) % c # return (a + b) #print(mysum(1, 100)) #print(mysu...
#输入一个字符串,判断这个字符串有几个空格‘ ’ #(要求不允许使用s.count方法),建议使用for语句实现 s = input("输入一段字符串: ") count = 0 #此变量替代,用来记录空格的个数 for ch in s: if ch == ' ': count +=1 print("空格的个数是",cou...
# 打印如下宽度的正方形: # 1 2 3 4 # 2 3 4 5 # 3 4 5 6 # 4 5 6 7 n = int(input("请输入: ")) for y in range(1, n + 1): for x in range(y, y + n): print("%2d" % x, end = " ") print()
#This is a simple snake game made using Python 3 #By Aaron Avers #Inspired by @TokyoEdTech's Python Game Programming Tutorial: Snake Game import time import turtle import random delay = 0.2 #Score score = 0 high_score = 0 #Create screen screen = turtle.Screen() screen.title("Snake Game by UnderratedRon") screen.bg...