text
stringlengths
37
1.41M
n = int(input('Digite um número inteiro: ')) for c in range(1, n + 1): print('{} '.format(c), end=' ') if n % 1 == 0 and n % n == 0: print('{} É um número primo'.format(n)) else: print('{} NÃO É UM NÚMERO PRIMO!'.format(n))
n = str(input('Qual é o nome da sua cidade?: ')).strip().upper() cidade = n.split() print('Sua cidade começa com "Santo"? {}'.format('SANTO' in cidade[0]))
nome = str(input('Digite seu nome completo:')) nome1 = nome.upper() nome2 = nome.lower() nome3 = len(nome.strip()) primeiro = (nome.split()) print(nome1) print(nome2) print(nome3) print(len(primeiro[0]))
from time import sleep import random escolha = ('Pedra', 'Papel', 'Tesoura') pc = random.randint(0, 2) print('Escolha uma opção abaixo para jogar JO KEN PO com o computador, Boa Sorte!') print('''Opções: [0] Pedra [1] Papel [2] Tesoura''') jogador = int(input('Qual você escolhe?')) print('...JO...') sleep(1)...
import random def not_in_row(matrix, row, col): count = 0 for x in matrix[row]: if matrix[row][col] == x: count = count + 1 return count def not_in_column(matrix, row, col): count = 0 for x in range(3): if matrix[x][col] == matrix[row][col]: count = count ...
from collections import OrderedDict class Question: """ Question class for storing all question data""" # constructor def __init__(self, question_id, question_text, topic, time, correct_character, array_choices, num_col): self.question_id = question_id self.question_text = qu...
""" User model to be stored in DB """ ADMIN_KEY = "admin" class User: """ each user has a name, admin bool and a DB provided ID if id is none, then it hasn't been inserted/read from the DB yet """ def __init__(self, name_): self.name = name_ self.admin = False self.todo_items...
#! /usr/bin/env python """ Simple events without metadata are typically used to play sound effects. """ class Event(): def getMetadata(self): pass class DoorOpeningEvent(Event): pass class PlayerFootstepEvent(Event): pass class EndGameEvent(Event): pass class WaspZoomingEvent(Event): ...
import pdb class Amity(object): def __init__(self): self.people = { # "test": 1 # this is only to simulate a full dictionary for testing purposesq } # these are object properties, so they only come into being if the class is instantiated # need them to be class varia...
import unittest #do you need a class here? def test_can_add_people_to_system(): #tests whether you can Fellows and team members to people databases def test_can_add_rooms_to_system(): #tests whether you can add rooms to rooms database def test_can_assign_rooms_purposes(): #tests whether you can assign an...
class Token: def __init__(self, value, type="", body=[], flags=''): self.type = type self.value = value self.flags = flags self.body = body # for user defined words, a list of tokens def __str__(self): return '(Token, {value}, {type})'.format( ...
"""" for loops also have an else clause. The else clause executes after the loop completes normally. This means that the loop did not encounter a break statement. One Common Usage is to check whether loop ends or not. we can check it via flag but for else is preferred way """ fruits = ['Apple', 'banana', 'orange'] for...
"""" In below class, Changing the first name, doesn't reflect the same change in email address. we can bypass this error by adding a new function for email and calling that function but that again breaks code base for already consuming existing email address. Property tags are used to access methods as attributes ""...
import time def calc_square(nums): print("Printing the Sqaures of {} ".format(nums)) print("*"*40) for num in nums: time.sleep(0.2) print("The Square of {} is {}".format(num,num*num)) def calc_cube(nums): print("Printing the cubes of {}".format(nums)) print("*"*40) for num in n...
""" Use *args and **kwargs in the inner wrapper function. then it will accept an arbitrary number of positional and keyword arguments. """ def my_decorator(func): def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper @my_decorator def my_function(*args, **kwargs): if args: pr...
dict = {'a':4,'b':5,'c':1,'d':3,'e':2} print("Sorting Based on keys") print(sorted(dict.items(),key=lambda x: x[0])) print("Sorting Based on values") print(sorted(dict.items(),key=lambda x: x[1]))
from collections import Counter c = Counter('abcdabcdabababababababbababadddddddddddddddddd') print('Printing the elments and their occurances : {}'.format(c)) print("Printing only the elements : {}".format(list(c.elements()))) print("Printing the two most common element based on the occurences : ".format(c.mos...
''' Shared Memory process 1 (Main process) ------> SHARED MEMORY <-------- process 2 (child process (calc_square)) ''' import multiprocessing def calc_square(numbers , result, v): v.value = 5.56 for index,num in enumerate(numbers): result[index] = num*num if __name__ == '__main__': ...
''' Loading xml file. Finding the root of the tree. Iterating over second level of the tree. Printing node tag name, attributes and values. ''' import xml.etree.ElementTree as ET tree = ET.parse('country_data.xml') root = tree.getroot() print('"{}" is the root of the element tree in this xml Doc'.format(root.tag))...
def my_decorator(func): def wrapper(*args): print("In Wrapper Function") #func(*args) return func(*args) return wrapper @my_decorator def add(*args): if args: print("Printing the sum in Normal Function : {}".format(sum(args))) return sum(args) if __name__ == '__main...
''' Lists are a part of the core python lanaguage. Despite their name,Python's lists are implemented as dynamic arrays. behind the scenes. It allows multiple data types is a powerfulr feature but it has downside as well. multiple data types at the same time is generally less tighly packed as a result the whole struct...
""" It uses Map and Reduce algorithm to allocate the wotk between the cpu cores and aggragate the results at the end give back the result """ from multiprocessing import Pool def f(n): return n*n if __name__ == '__main__': p = Pool(processes=5) result = p.map(f,[1,2,3,4,5]) for n in result: ...
import sys import math import time def is_factor(factor, product): if product % factor == 0: return True else: return False def campbell_rating(number): possible_factor = 2 number_factors = 2 while (possible_factor < math.sqrt(number)): if is_factor(possible_factor, numb...
#!/usr/bin/python # usage: python ftp.py filename import os,sys from ftplib import FTP server = 'pantoto.org' # Server name username = 'usrname' # server username passwd = 'passwd' # Password for this user ID filename = sys.argv[1] # This take an argument from commandline ftp = FTP(server) ftp.login(username,pas...
""" a VERY simple tokenizer. Just tokenizes on space and a few common punctiation marks. Works for simple applications and some languagues though. """ def remove_spaces(line): """ Removes double spaces """ line = line.lstrip() result = "" for i, ch in enumerate(line): if i+1 == len(l...
""" """ from abc import ABCMeta, abstractmethod from caysen.kernel import SubSystem, SubSystemError class GameState(metaclass=ABCMeta): """ Represents a single piece of reusable game-specific functionality. Attributes: name (str): A unique name. """ def __init__(self, name): se...
import numpy as np import matplotlib.pyplot as plt import math import cv2 # OpenCV library for computer vision from PIL import Image import pickle from imageio import imread import io import base64 # Auxiliary functions def read_image(path): """ Method to read an image from file to matrix """ ...
#Sets are denoted by curly braces {} #Sets does not allow duplicate values which means it does not displays it s={1,2,3,4,5,1} print(s) print(type(s)) s.update([23,44]) print(s) #print(s[0])#Indexing is not allowed in set type because and also slicing and repetition s.remove(2) print(s) #Frozen set-It does not allow u...
"""Duck typing is not a feature that programming language offers but it comes for free if the programming language is free if it is dynamic """ class Duck: def talk(self): print("quack quack") class human: def talk(self): print("hello") def calltalk(obj): obj.talk() d=Duck() calltalk(d) ...
#THe syntax for lambda expression is #lambda argument_list:expression #Unlike functions lambda will always return a function back """lambda expression are very helpful and can be used in other functions to for eg, filter,map,reduce """ #Calculate cube of a given number def cube(n): return n**3 print(cube(3)) #...
a,b,c=[int(x) for x in input("Enter three numbers").split()] average=(a+b+c)/3 print("average of three numbers is",average)
"""List Comprehensions help us a easy to use syntax for creating one list from other using some logic Syntax for list comprehension is l=[expression for item in itearble if condition] """ #Cubes of numbers from 1 to 10 #This is normal programming """lst=[] for x in range(1,11): lst.append(x**3) print(lst)...
#List starts from index 0 lst=[10,20,"nishant",2,2,1] print(lst) print(lst[3]) #slicing in list print(lst[3:9]) print(len(lst)) #Adding and removings #Append to add elements in a list lst.append("mango") print(lst) #We use remove function when we want to remove by value lst.remove("mango") lst.remove("nishant") print(...
import tkinter as tk def print_txtval(): val_en = en.get() print(val_en) root = tk.Tk() root.title("テキストボックス内容の取得") root.geometry("350x150") lb = tk.Label(text="ラベル") en = tk.Entry() bt = tk.Button(text="ボタン",command=print_txtval) [widget.pack() for widget in (lb,en,bt)] root.mainloop()
import tkinter as tk def print_txval(): val_en = en.get() print(val_en) root = tk.Tk() en = tk.Entry() bt = tk.Button(text="ボタン",command=print_txval) [widget.pack() for widget in (en,bt)] en.focus_set() root.mainloop()
""" Reads a file containing columns of data and creates a dictionary according to header information using the following format: 1. comments start with ``#`` in the **first column** : ``# My Comment`` 2. header information starts with ``#!``, where ``#`` is also in the **first column**. It must precede the data. 3....
""" The plotting module contains functions based on :mod:`matplotlib` and :class:`~LT.datafile`. They provide shortcuts to perform typical plotting tasks in experimental physics. **NOTE:** when you use these functions, enter the show() command to see the result interactively. Example:: >>> import LT.plotting as ...
# In the begining, import several useful modules in python import matplotlib.pyplot as plt import numpy as np # Example 1: simple scatter plot # For start, let's plot a simple line, and customize your figure and axis. x = [0, 1, 2, 3, 4, 5, 6, 7] y = [0, 1, 4, 9,16,25,36,49] z = [0, 1, 2, 3, 4, 5, 6, 7] # hav...
# Based on the wiki page and pseudocode : https://en.wikipedia.org/wiki/A*_search_algorithm and backtracking maze generator import matplotlib as mpl from matplotlib import pyplot import numpy as np import random class Node: def __init__(self,pos_): self.pos=pos_ self.statut='open' self.f=f...
from helpers import alphabet_position, rotate_character # each letter in the keyword is a codenumber for each letter in the message def encrypt(message, keyword): scrambled_text = '' letter_in_keyword = 0 # so I don't have to increment at the same pace as i (i.e. spaces between words) for i in range(len(me...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if(root is None): return 0 ...
""" n = int(input()) # number of values for _ in range(n): ip = int(input()) if ip % 7 == 0: print(ip ** 2) """ n = int(input()) # number of values ip = [] for _ in range(n): ip.append(int(input())) for i in ip: if i % 7 == 0: print(i ** 2)
x = int(input()) y = int(input()) # the variables `x` and `y` are defined, so just print the minimum def min_number(a, b): minumum_ = min(a, b) print(minumum_) min_number(x, y)
#!/usr/bin/env python import numpy as np import sklearn.datasets import matplotlib.pyplot as plt def load_data(n_samples=100, noise=None): np.random.seed(0) return sklearn.datasets.make_moons(n_samples=n_samples, noise=noise) def init_network_weights(network, seed=0): ''' initialize the weights of ...
from collections import Counter def is_anagram(w1, w2): c1 = Counter(w1) c2 = Counter(w2) return c1 == c2 def anagrams(word, words): return [w for w in words if is_anagram(w, word)]
def descending_order(num): return int(''.join(sorted(str(num), reverse=True)))
from string import ascii_lowercase as abc def high(x): def score(word): return sum(abc.find(c) + 1 for c in word) return sorted(x.split(), key=score, reverse=True)[0]
def make_readable(seconds): hours = seconds // 3600 minutes = (seconds - (hours * 3600)) // 60 sec = seconds - (hours * 3600) - (minutes * 60) return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, sec)
def inttohex(value): if value <= 0: return '00' elif value >= 255: return 'FF' s = hex(value)[2:].upper() return s if len(s) > 1 else '0' + s def rgb(r, g, b): return '{}{}{}'.format(inttohex(r), inttohex(g), inttohex(b))
from collections import Counter def is_isogram(string): cnt = Counter(string.lower()) for _, value in cnt.items(): if value > 1: return False return True
def flower(M,k,l): row, col = len(M),len(M[0]) k_row,l_col = row*k, col*l # Membuat matriks baru R berukuran km*kn result = [] for i in range(k_row): result.append([None]*l_col) for i in range(row): for j in range(col): # Memekarkan setiap matrik i,j ke i+k dan ...
import csv test_field_names = ["customer_name", "customer_address", "customer_phone", "courier", "status"] test_list = [] # with open("orders.txt", "r") as file: # for i in file: # dict = eval(str(i)) # test_list.append(dict) # # with open("test.csv", "w") as csv_file: # writer = csv.DictWrite...
def reverse_recursive(self, start): if start is None: return prev = start curr = prev.next if curr is None: # single element return if curr.next is None: # two elements self.head = curr curr.next = prev prev.next = None return s...
# from BinarySearchTree.binary_search_tree import BinarySearchTree # from BinarySearchTree.recursive_inorder_traverse import recursive_inorder def invert_tree(ptr): if ptr is None or (ptr.left is None and ptr.right is None): return ptr.left, ptr.right = ptr.right, ptr.left invert_tree(ptr.left) ...
def reverse_print_recursive(self, start): if start is None: return if start.next is None: print(start.data) return prev = start curr = prev.next if curr.next is None: print(curr.data) print(prev.data) return self.reverse_print_recursive(prev.ne...
## # K Nearest Neighbors (KNN) algorithm # # Author: Fabrício G. M. de Carvalho, Ph.D ## def distance(v1, v2): square_sum = 0 for i in range(len(v1)): square_sum += (v1[i] - v2[i])**2 distance = square_sum**0.5 return distance # simple buble sort algorithm: def bubble_sort(v, key): has_swapped = True wh...
#Assessment on try,except,else & finally: #Prob1: handle exception thrown by type error try: for i in ['a', 'b', 'c']: print(i**2) except TypeError: print('Input given is not integer to get a result') finally: print('Try again!') #Prob2: Print finally 'All done' after handling exception: try: ...
#in python list is array: where we can have all types of data types unlike in Java, C++ #1-D array list= [1,2.5,'Mayuri'] #2-D array list1= [[1,2,3], [4,5,6], [0,9,8]] for row in list1: for column in row: print(column, end=' ') print() print('\n') for row in list1: for column in row: pas...
import tweepy import json import os import pandas as pd from dotenv import load_dotenv load_dotenv() consumer_key = os.getenv("API_KEY") consumer_secret = os.getenv("API_SECRET_KEY") access_token = os.getenv('ACCESS_TOKEN') access_token_secret = os.getenv('ACCESS_TOKEN_SECRET') #Authentication process auth = tweepy.O...
class Graph: def __init__(self): self.relationships = {} def add_vertex(self, vertex): vertices = self.relationships.keys() if vertex in vertices: return False self.relationships[vertex] = [] return True def add_edge(self, begin, end): vertices ...
# classifier.py is a class that is called to deternmine whether two given contours are targets. # it can find the boiler or the gear lift. import math passed = [] values = [] class cClassifier(): def __init__(self): self.gearClassifiers = [matchingRotation, gearAreaRatio, gearBetweenHeightRatio, minAreaD...
# Define a procedure is_palindrome, that takes as input a string, and returns a # Boolean indicating if the input string is a palindrome. # Base Case: '' => True # Recursive Case: if first and last characters don't match => False # if they do match, is the middle a palindrome? # Recursive solution def palindrome_rec...
import random # This will find the max and min values in a single traversal def get_min_max(ints): if len(ints) == 0: return () mi = ints[0] ma = ints[0] # I look for both min and max at the same time for i in range(0, len(ints)): if ints[i] < mi: mi = ints[i] i...
#Lucas Bouchard import pandas as pd import csv import numpy as np from sklearn.linear_model import LinearRegression from sklearn.linear_model import LogisticRegression from sklearn.metrics import r2_score #import matplotlib.pyplot as plt #%matplotlib inline #https://pythonspot.com/linear-regression/ # PROBLEM 1....
import os # file format: # <student id>,<first name>,<last name> def setup(): if not os.path.isdir('data'): os.mkdir('data') else: print("'data' directory already exists.") os.chdir('data') def write_record(file, id, first_name, last_name): file.write(f"{id},{first_name},{last_name}...
import pygame # 初始设置 pygame.init() # 初始化pygame screen = pygame.display.set_mode((800,600)) # 创建一个800*600像素的显示窗口 pygame.display.set_caption("Pygame绘制图形") # 给屏幕窗口添加标题Pygame绘制图形 keep_going = True # 定义了一个布尔类型keep_going控制程序的持续运行 RED = (255,5,0) # 红色,使用RGB颜色,(红色R,绿色G,蓝色B) radius = 80 # 设置了圆的半径,变量radius = 80 # 游戏循环 while k...
#!/usr/bin/python def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the ...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: if not head: return head slow = head quick = head while quick and slow: # 这里因为quicl跳两次,所以要判断quick和qui...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairsRecursive(self, head: ListNode) -> ListNode: """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File:memory.py # @Author: Feng # @Date:2019/9/9 # @Desc: import sys # 该方法用于获取一个对象的字节大小(bytes) # 它只计算直接占用的内存,而不计算对象内所引用对象的内存 a = [1, 2] b = [a, a] def get_size(): print(sys.getsizeof(a)) # 80 print(sys.getsizeof(b)) # 80 def get_obj...
from csv_stuffs import addCSVdata, getRow, getCol, readCSVdata, editCSVdata def tambahitem(role): # menambahkan item ke dalam inventory # KAMUS LOKAL # csv_file, id, nama, desc, jml, rarity, year : string # ALGORITMA # validasi role Admin if (role == "Admin"): id = input("Masukkan ID: ") idnum = "" for...
def ham_dist(a, b): diff_cnt = 0 for i in range(0, len(b), 1): if a[i] != b[i]: diff_cnt += 1 return diff_cnt with open('rosalind_hamm.txt', 'r') as file: a = file.readline() b = file.readline() file.close() print(ham_dist(a, b))
#!/usr/bin/python #Created By: Mandip Sangha #Last Modified: 12/01/2017 #**************************************************************************** #NOTE: #The left and right node comparison for greater than and lesser than is for # number values. Uses of other types of values can cause known results #Duplic...
#!/usr/bin/python #Created By: Mandip Sangha #Last Modified: 12/04/2017 import unittest from dataStructure.queue import * class TestQueue(unittest.TestCase): def setUp(self): self.queue = Queue(3) def test_enqueue(self): self.queue.enqueue(1) self.queue.enqueue(2) self.qu...
from random import randint number = randint(0, 10) guess = int(input("Guess a number from 0 to 10: ")) chances = 6 while(chances > 1): if(guess<number): print("Your number is less than the actual number... try again") guess = int(input("Guess a number from 0 to 10: ")) chances = chances - 1 elif(number<guess):...
list1 = [[10,12,14,16], [18,20,22,24], [26,28,30,32], [34,36,38,40]] list2 = [] list3 = [] print("1행 1열의 데이터 :",list1[0][0]) print("3행 4열의 데이터 :",list1[2][3]) print("행의 갯수 :",len(list1)) print("열의 갯수 :",len(list1[0]))#?? print("3행의 데이터들 :",list1[2]) print("2열의 데이터들 :",list1[1][1]) for i in r...
import random # random 모듈을 가져옴 count = 0 while True: count += 1 num = random.randint(1, 20) if num % 5 == 0 : print("끝낼께용!!") break elif num % 2 == 0 : print("다시 할께용!!") continue else : for i in range(num) : print("#", end="") print() ...
student = 1 while student <= 5: print(student, "번 학생의 성적을 처리한다.") student += 1 print("수행종료") for student in range(1, 6) : print(student, "번 학생의 성적을 처리한다.") print("수행종료")
def add(num1, num2) : return num1 + num2 r1 = add(10, 20) v1 = 100; v2 = 200 r2 = add(v1, v2) print(r1) print(r2) print(bool(add(1000, 2000))) print(1+add(1000, 2000)) print(2+add(1000, 2000)) print(3+add(1000, 2000)) r3 = add(1000, 2000) print(1+r3) print(2+r3) print(3+r3)
import random a = set() b = set() anum = 0 bnum = 0 while len(a) < 10 or len(b) <10: if len(a) < 10: anum = random.randint(1, 20) a.add(anum) if len(b) < 10: bnum = random.randint(1, 20) b.add(bnum) print("집합1 :",a) print("집합2 :",b) print("두 집합에 모두 있는 데이터 :",a & b) print("집합1 또는...
def sumALL(*p): count=0 ans=0 for i in p: if type(i) == int: count+=1 ans+=i else: pass if len(p)==0 or count ==0 : ans = None return ans print(sumALL(1,2,3)) print(sumALL(3,'a', '*')) print(sumALL()) print(sumALL('a','b', True))
listnum = [10,5,7,21,4,8,18] num = listnum[0] for i in listnum: if num >= i: num = i print("최솟값 : ",num)
class Member: def __init__(self): self.name = None self.account = None self.passwd = None self.birthyear = None s1 = Member() s2 = Member() s3 = Member() s1.name = "kim" s1.account = "abc" s1.passwd = "ABC" s1.birthyear = 1996 s2.name = "lee" s2.account = "def" s2.passwd = "DEF" ...
import random score = random.randint(0,100) if 90 <= score <= 100: grade = 'A' elif 80 <= score <=89: grade = 'B' elif 70 <= score <= 79: grade = 'C' elif 60 <= score <= 69: grade = 'D' else : grade = 'F' print(score,"점은", grade,"등급입니다.")
INCH = 2.54 def calcsum(n): sum = 0 for num in range(n + 1): sum += num return sum
cnt = 0 try: f = open("yesterday.txt", "rt", encoding="UTF-8") except FileNotFoundError : print("파일을 읽을 수 없어요") else: for tmp in f: tmp = tmp.lower() cnt += tmp.count('yesterday') print(f"Number of a Word 'Yesterday' {cnt}") finally: print("수행완료!!")
list1 = [[10,20,30,40,50],[5,10,15],[11,22,33,44],[9,8,7,6,5,4,3,2,13]] for i in range(len(list1)): sum = 0 for d in list1[i]: sum += d print(i+1,"행의 합은 ",sum," 입니다.")
listnum = [10,5,7,21,4,8,18] result = listnum[0] for x in range(1,len(listnum)): samp = listnum[x] if result < samp: result = samp print("최댓값:",result)
money = 6500 if money >= 20000: print("탕수육을 먹는다") elif money >= 10000: print("쟁반 짜장을 먹는다") elif money >= 6000: print("짬뽕을 먹는다") elif money >= 4000: print("짜장면을 먹는다") else: print("단무지를 먹는다") print("뭐든 맛있다!!")
list = [ [10, 12, 14, 16], [18, 20, 22, 24],[26, 28, 30, 32],[34,36,38,40]] print("1행 1열의 데이터 :",list[0][0]) print("3행 4열의 데이터 :",list[2][3]) print("행의 갯수 :",len(list)) print("열의 갯수 :",len(list[0])) print("3행의 데이터들 :",list[2][0],list[2][1],list[2][2],list[2][3]) print("2열의 데이터들 :",list[0][1],list[1][1],list[2][1],li...
import random grade = random.randint(1, 6) if 1 <= grade and grade <= 3: print("grade",grade, "학년은 저학년 입니다.") else : print("grade",grade, "학년은 고학년 입니다.")
import random set1 = set() set2 = set() while len(set1)<=10: num = random.randint(1, 20) set1.add(num) while len(set2)<=10: num = random.randint(1, 20) set2.add(num) print("집합 1:", set1) print("집합 2:", set2) print("두 집합에 모두 있는 데이터 :", set1 & set2) print("집합1 또는 집합2 에 있는 데이터:", set1|set2) print("집합1에...
import random # random 모듈을 가져옴 dice_num = random.randint(1, 6) print("추출된 주사위 값 :", dice_num) while dice_num > 4 : print("ㅋㅋ") print("종료!!")
def print_triangle(num): if num >= 1 and num <= 10: for num in range(num,0,-1): print("@" * num) else: pass print_triangle(5)
dictionary = {} print("요소 추가 이전:", dictionary) dictionary["name"] = "새로운 이름" dictionary["head"] = "새로운 정신" dictionary["body"] = "새로운 몸" print("요소 추가 이후:", dictionary) dictionary = { "name": "7D 건조 망고", "type": "당절임" } print("요소 제거 이전:", dictionary) del dictionary["name"] del dictionary["type"] print(...
def isType(p) : if type(p) == int : result = "정수를 전달했네요" elif type(p) == float : result = "실수를 전달했네요" elif type(p) == str : result = "문자열을 전달했네요" elif type(p) == bool : result = "논리값을 전달했네요" else : result = "몰라용^^" return result print(isType(100)) print(i...
sum = 0 for num in range(1, 101): sum += num print ("1부터 100까지 더한 값 =",sum) sum = 0 for num in range(2, 101, 2): sum += num print ("1부터 100까지 값들 중에서 짝수만 더한 값 =",sum)
#!/usr/local/bin/python3.8 import datetime import student class ClassScheduler(object): '''Creates and updates a list of student objects and their class schedule. ''' def __init__(self): self.students = {} self.next_available_id = 1 def _update_next_available_id(self): ''...
# Exercise 1 def right_triangle_generator(): max_triangle_size = int(input('Enter max triangle size: ')) for c in range(1, max_triangle_size): for b in range(1, c): for a in range(1, b): if a * a + b * b == c * c: print('{}, {}, {}'.format(a, b, c)) if...
#! /usr/bin/python3.5 import datetime import calendar import constants CURRENT_YEAR = datetime.datetime.today().year CURRENT_MONTH = datetime.datetime.today().month CURRENT_DAY = datetime.datetime.today().day def is_valid_year(year): '''Checks if a given integer represents a valid year. Args: year ...