当前位置: 首页>>代码示例>>Python>>正文


Python input函数代码示例

本文整理汇总了Python中input函数的典型用法代码示例。如果您正苦于以下问题:Python input函数的具体用法?Python input怎么用?Python input使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了input函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self):
        ##analyze frequencies
        piglatinObject = Piglatin.PigLatinTranslate()
        #print(__name__)
        if __name__ == "__main__":
            #print("from commandline")
            piglatinObject.piglatinTranslate(_("hello"))
            print(_("testing with hello == "), piglatintext)

            print(_("sentence translation"))
            piglatinObject.piglatinTranslateSentence(_("i am gowri and you are you"))

            print(_("frequency analysis"))
            print("%s" %(piglatinObject.frquencyAnalysis()))
        elif __name__ == "Piglatin_UI":
            #print("from module - testingPiglatin_commandline being the name of the module in this case")

            #Internationalization
            t = gettext.translation('English', '/locale')
            _ = t.ugettext
            
            texttotranslate = input(_("Enter text - a word: "))
            print("translated = ", piglatinObject.piglatinTranslate(texttotranslate))
            
            sentencetotranslate = input(_("Enter text - a sentence: "))
            print(_("translated text = "), piglatinObject.piglatinTranslateSentence(sentencetotranslate))

            print(_("frequency analysis"))
            print(piglatinObject.frquencyAnalysis())
开发者ID:sahirvsahirv,项目名称:MyRepository,代码行数:29,代码来源:Piglatin_UI_Internationalized.py

示例2: add_entry

def add_entry():
    """Adds an entry to the diary"""
    title_string = "Title (press %s when finished)" % finish_key
    # print(title_string)
    puts(colored.yellow(title_string))
    puts(colored.green("="*len(title_string)))
    title = sys.stdin.read().strip()
    if title:
        entry_string = "\nEnter your entry: (press %s when finished)" % finish_key
        puts(colored.yellow(entry_string))
        puts(colored.green("="*len(entry_string)))
        # reads all the data entered from the user
        data = sys.stdin.read().strip()
        if data:    # if something was actually entered
            puts(colored.yellow(
                "\nEnter comma separated tags(if any!): (press %s when finished) : " % finish_key))
            puts(colored.green("="*(len(title_string)+33)))
            tags = sys.stdin.read().strip()
            tags = processTags(tags)
            puts(colored.green("\n"+"="*len(entry_string)))
            # anything other than 'n'
            if input("\nSave entry (y/n) : ").lower() != 'n':
                DiaryEntry.create(content=data, tags=tags, title=title)
                puts(colored.green("Saved successfully"))
    else:
        puts(
            colored.red("No title entered! Press Enter to return to main menu"))
        input()
        clear()
        return
开发者ID:YixuanFranco,项目名称:tnote,代码行数:30,代码来源:tnote.py

示例3: testcalculator

def testcalculator():
#Simple test average calculator that you can exit by not inputting a number or by typing 0.
    total = 0
    count = 0
    average = 0
    data = 1


    while data != 0:
        try:
            data = int(input("Enter a number or press 0 to quit: "))
            if data == 0:
                break
            else:

                try:
                
                    count += 1
                    number = data
                    total += int(number)
                    average = total / count
                    data = int(input("Enter a number or press 0 to quit: "))
                
                except ValueError:
                    break
        except ValueError:
            break

    print("The sum is {0}. The average is {1}.".format(total, average))
开发者ID:gwoke,项目名称:projects,代码行数:29,代码来源:testcalc.py

示例4: escribir

def escribir():
    print("Has elegido añadir un registro a la agenda")
    nombre = input("Introduce el nombre de contacto: ")
    telefono = input("Introduce su teléfono: ")

    agenda = open("agendatelefonica.csv")
    for n in range(1,40):
        linea = agenda.readline()
        lineapartida = linea.split(",")
##        print(lineapartida[0])
        if lineapartida[0] != "":
            memoria = lineapartida[0]
##    print("El numero máximo es",memoria)
    agenda.close()
    memonum = int(memoria)
    posicion = 0
    posicion = memonum + 1
    postr = str(posicion)
    print("Se ha guardado en la agenda el contacto: ",nombre,"con el número de teléfono",telefono)
    agenda = open("agendatelefonica.csv",'a')
    agenda.write(postr)
    agenda.write(",")
    agenda.write(nombre)
    agenda.write(",")
    agenda.write(telefono)
    agenda.write(",")
    agenda.write("\n")
    agenda.close()
开发者ID:juanmancb90,项目名称:Agenda-Python,代码行数:28,代码来源:modulos.py

示例5: write_func

def write_func():            ###Get input from user and append to table file
    
    dbase = []

    dealer = raw_input("Dealer:  ")
    hirer = raw_input("Hirer's Name:  ")
    ###     acNum to test for duplicate number
    acNum = raw_input("Loan Number:   ")
    with open('/Users/Michael/Documents/GitHub/Int-Projection/projection.csv', 'r') as compare:
        reader = csv.reader(compare)
        for row in reader:
            if str(row) == str(acNum):
                acNum = raw_input("Duplicate Loan No! Recheck and try again!")
                    
    details = raw_input("Loan Details:  ")
    agg_date = str(raw_input("Agreement Date (yyyymmdd):"))
    ###     While loop to ensure correct date format for ease of processing
    while len(agg_date) != 8:
        agg_date = str(raw_input("Invalid Date Format! Try again (yyyymmdd):"))
        
    format_date = agg_date[6:8] + '-' + agg_date[4:6] + '-' + agg_date[0:4]  #format for human eye
    amount = input("Loan Amount:   ")
    interest = input("Loan Interest:  %")
    tenure = input("No of Months: ")


    dbase = [dealer, acNum, hirer, details, amount, interest, format_date, tenure]

    with open('/Users/Michael/Documents/GitHub/Int-Projection/projection.csv', 'a') as b:
        writer = csv.writer(b)
        writer.writerow(dbase)
开发者ID:tatsuyuki,项目名称:Int-Projection,代码行数:31,代码来源:projection.py

示例6: get_input

def get_input(choices: List[Tuple]):
    all_tiles = set()
    all_commands = set()
    all_lines = set()
    for command, lines, tiles in choices:
        all_lines |= set(lines)
        all_commands.add(command)
        all_tiles |= set(tiles)
        # tile_list = ', '.join([f'{t.var} ({t.id})' for t in tiles])
        #
        # print(f"{command} ({command.id})")
        #       f"    lines: {str(lines)[1:-1]}\n"
        #       f"    tiles: {tile_list}")

    print(str(all_lines)[1:-1])
    print(', '.join([f"{c[0]} ({c[0].id})" for c in choices]))
    print(', '.join([f'{t.var} ({t.id})' for t in all_tiles]))

    while True:
        line = int(input('line: '))
        cmd_id = int(input('command: '))
        tile_id = int(input('tile: '))

        try:
            command = [c for c in all_commands if c.id == cmd_id][0]
            tile = [t for t in all_tiles if t.id == tile_id][0]
            break
        except (IndexError, ValueError):
            pass

    return line, command, tile
开发者ID:ffaristocrat,项目名称:coding,代码行数:31,代码来源:main.py

示例7: display

def display(spectrum):
	template = np.ones(len(spectrum))

	#Get the plot ready and label the axes
	pyp.plot(spectrum)
	max_range = int(math.ceil(np.amax(spectrum) / standard_deviation))
	for i in range(0, max_range):
		pyp.plot(template * (mean + i * standard_deviation))
	pyp.xlabel('Units?')
	pyp.ylabel('Amps Squared')    
	pyp.title('Mean Normalized Power Spectrum')
	if 'V' in Options:
		pyp.show()
	if 'v' in Options:
		tokens = sys.argv[-1].split('.')
		filename = tokens[0] + ".png"
		input = ''
		if os.path.isfile(filename):
			input = input("Error: Plot file already exists! Overwrite? (y/n)\n")
			while input != 'y' and input != 'n':
				input = input("Please enter either \'y\' or \'n\'.\n")
			if input == 'y':
				pyp.savefig(filename) 
			else:
				print("Plot not written.")
		else:
			pyp.savefig(filename) 
开发者ID:seadsystem,项目名称:Backend,代码行数:27,代码来源:Analysis3.py

示例8: imc_creds

def imc_creds():
    ''' This function prompts user for IMC server information and credentuials and stores
    values in url and auth global variables'''
    global url, auth, r
    imc_protocol = input(
        "What protocol would you like to use to connect to the IMC server: \n Press 1 for HTTP: \n Press 2 for HTTPS:")
    if imc_protocol == "1":
        h_url = 'http://'
    else:
        h_url = 'https://'
    imc_server = input("What is the ip address of the IMC server?")
    imc_port = input("What is the port number of the IMC server?")
    imc_user = input("What is the username of the IMC eAPI user?")
    imc_pw = input('''What is the password of the IMC eAPI user?''')
    url = h_url + imc_server + ":" + imc_port
    auth = requests.auth.HTTPDigestAuth(imc_user, imc_pw)
    test_url = '/imcrs'
    f_url = url + test_url
    try:
        r = requests.get(f_url, auth=auth, headers=headers)
    # checks for requests exceptions
    except requests.exceptions.RequestException as e:
        print("Error:\n" + str(e))
        print("\n\nThe IMC server address is invalid. Please try again\n\n")
        imc_creds()
    if r.status_code != 200:  # checks for valid IMC credentials
        print("Error: \n You're credentials are invalid. Please try again\n\n")
        imc_creds()
    else:
        print("You've successfully access the IMC eAPI")
开发者ID:xod442,项目名称:HP-IMC-eAPI-Projects,代码行数:30,代码来源:1+HP+IMC+Create+Operators.py

示例9: kullanici_adini_guncelle

def kullanici_adini_guncelle():
    """Kullanıcıdan isim alıp ayarlara yazdırmaya gönderir"""
    veri = ayar_oku()
    veri["son_kullanan"] = input("Kullanıcı Adınız: ")
    while not veri["son_kullanan"] or len(veri["son_kullanan"]) > 9:
        veri["son_kullanan"] = input("1 ile 9 karakter uzunluğunda yazın: ")
    ayar_yaz(veri)
开发者ID:enkorkmaz,项目名称:PythonDersleri,代码行数:7,代码来源:ders2.py

示例10: mentre3

def mentre3(): #Definim la funcio mentre3, que es una funcio secundaria de mentre
    suma = 0 #La variable "suma" tindra aquest valor"
    n = input("Sumarem tots els nombres que introduiu fins que poseu 999: ") #Definim la variable "n" com un input. Sera interpretat com un nombre.
    while n != 999: #Mentre es compleixi aquesta condicio
            suma = suma + n #La variable suma augmentara en funcio de "n"
            n = input("Fins que no introdueixis 999 seguirem sumant nombres: ") #Tornem a definir la variable "n" com un input. Sera interpretat com un nombre.
    print "\nLa suma dels nombres es: ", suma #Quan les condicions del while no es compleixin, imprimirem el resultat
开发者ID:fitigf15,项目名称:PYTHON-VICTOR,代码行数:7,代码来源:exercici4.py

示例11: vending_machine

def vending_machine():
    deposit = 0 
    #get the cost of the item(s) purchased
    cost = eval(input('Enter the cost (in cents):\n'))
    #ask for money to pay when cost is greater than 0 and ask for more deposit when not enough
    while deposit < cost:
        deposit += eval(input('Deposit a coin or note (in cents):\n'))
    change = deposit - cost
    #Give change when due
    if change > 0:
        print('Your change is:')
        
        for i in (100, 25, 10, 5, 1):
            #check decreasingly if one of the possible coin is part of the change
            if change >= i:
                #specify for change more than or equal to $1 as in dollar               
                if i == 100:
                    print(change//i, ' x ', '$1',sep = '')
                else:
                    print(change//i, ' x ', i,'c',sep = '')
                change -= (change//i)*i
                #check until chanege is 0 then break loop
                if change == 0:
                    break
            else:
                continue
开发者ID:MrHamdulay,项目名称:csc3-capstone,代码行数:26,代码来源:question2.py

示例12: main

def main():
	board = chess.Board()
	move_selector = MoveSelector(MAX_ITER_MTD, MAX_DEPTH, config.MAX_SCORE)

	color_choice = input("Do you want to play as black or white? [W/B]: ")
	while color_choice is not "W" and color_choice is not "B":
		color_choice = input("Invalid choice, please enter W for white or B for black: ")

	print(pp_board(board))

	if color_choice == "W":
		while True:
			if board.is_game_over():
				break

			handle_human_move(board)

			if board.is_game_over():
				break

			handle_ai_move(board, move_selector)
	else:
		while True:
			if board.is_game_over():
				break

			handle_ai_move(board, move_selector)

			if board.is_game_over():
				break

			handle_human_move(board)

	print(board.result())
开发者ID:JHurricane96,项目名称:chessai,代码行数:34,代码来源:main.py

示例13: main

def main():
    T = int(input())
    
    for _ in range(T):
        n = int(input())
        side_lengths = list(map(int, input().split()))
        print('Yes' if is_valid(side_lengths) else 'No')
开发者ID:charles-wangkai,项目名称:hackerrank,代码行数:7,代码来源:piling-up.py

示例14: main

def main():
    n = int(input())
    xs = [int(i) for i in input().strip().split()]
    assert len(xs) == n

    result = solve(xs)
    print(result)
开发者ID:yamaton,项目名称:codeforces,代码行数:7,代码来源:586A-Alena's_Schedule.py

示例15: playPerformance

def playPerformance(selection, performance, expression, segmentation, name='ExpressivePerformance'):
    # Store?
    # Play again?
    # View first x notes?
    while True:
        choice = util.menu('What do you want to do?', ['Play performance', 'Store expression', 'Store midi', 'View first notes of performance', 'Plot performance', 'Save plot', 'View segmentation', 'Make segmentation audible', 'Quit'])
        if choice == 0:
            seq = Sequencer()
            seq.play(performance)
        elif choice == 1:
            n = input("Enter a name for saving this performance. [{0}]\n".format(name))
            if not n == '': name = n
            tools.savePerformance(selection, expression, name)
        elif choice == 2:
            n = input("Enter a name for saving this performance. [{0}.mid]\n".format(name))
            if not n == '': name = n
            performance.exportMidi('output/{0}.mid'.format(name))
        elif choice == 3:
            for note in performance[:30]:
                print(note)
        elif choice == 4: # Plot
            visualize(segmentation, expression)
        elif choice == 5: # Save plot
            n = input("Enter a name for saving this performance. [{0}.mid]\n".format(name))
            if not n == '': name = n
            visualize(segmentation, expression, store=name)
        elif choice == 6: # View segments
            pass
        elif choice == 7: # Play segments
            pass
        elif choice == 8: # Quit
            break
开发者ID:bjvanderweij,项目名称:expressivity,代码行数:32,代码来源:performancerenderer.py


注:本文中的input函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。