Exemple #1
0
def cook_pizza():
    print('__name__ in cook_pizza function: ' + __name__)
    pizza.make_pizza()
    print('Turn oven on.')
    print('Place in oven.')
    print('Cook.')
    print('Remove and eat to your heart\'s desire.')
Exemple #2
0
def make_pizza(*toppings):
    # the * tells python to make an empty tuple called toppings and then pack whatever values it receives into this tuple
    """Summarize the pizza we are about to make, adding as many toppings as we'd like"""
    print("n\Making a pizza with the following toppings:")
    for topping in toppings:
        print(f" - {topping}")
    
    make_pizza('pepperoni')
    make_pizza('onions', 'mushrooms', 'olives')
Exemple #3
0
def import_module():
    # 导入整个模块
    pizza.make_pizza('A')  # ('A',)
    pizza.make_pizza('C', 'D', "E")  # ('C', 'D', 'E')

    # 导入特定的函数
    print("\n")
    function_2()  # function_2
    function_3()  # function_3

    # 使用as 给函数指定别名
    print("\n")
    f4()  # function_4

    # 使用as给模块指定别名
    print("\n")
    p.make_pizza('A')  # ('A',)
    p.make_pizza('C', 'D', "E")  # ('C', 'D', 'E')

    # 导入模块中的所有函数
    print("\n")
    function_1()  # function_1
Exemple #4
0
#Learn how to import and to use modules
#Importing the whole modules
import pizza

pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(20, 'mushroom')

#Importing special functions
from pizza import make_pizza
make_pizza(21, 'Eggs', 'Cheese', 'Masala')
make_pizza(21, 'Mushrooms', 'Special mint leaves')

#Use a give a function alies name
from pizza import make_pizza as limbo
limbo(48, 'Macoroni', 'Masala')

#Using as to give a module alias name
import pizza as k
k.make_pizza(10, 'Mushroom')

#Importing all functions in a modules
from pizza import *
pizza.make_pizza(15, 'Fungus')
#!/usr/bin/env python 
# -*- coding:utf-8 -*-
"""
#导入模块方法①
import pizza

pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushroom', 'green peppers', 'extra cheese')

# 导入模块方法②
from pizza import make_pizza

make_pizza(16, 'pepperoni')"""

# 使用as给函数指定别名
from pizza import make_pizza as mp

mp(16, 'pepperoni')

# 使用as给模块指定别名
import pizza as p

p.make_pizza(16, 'pepperoni')

# 导入模块中的所有函数
from pizza import *

make_pizza(16, 'pepperoni')

Exemple #6
0
import pizza
pizza.make_pizza(22,'cc')
pizza.make_pizza(12,'aa','dd','ee')
from pizza import make_pizza

make_pizza(16, "pepperoni")
make_pizza(22, "mushrooms", "green peppers", "extra cheese")
Exemple #8
0
# coding=utf-8
"""
作者:郭伟伟
简介:函数---导入创建的pizza模块,再调用make_pizza()
日期:2019-12-05
"""

import pizza

pizza.make_pizza(89, "pepperoni")


Exemple #9
0
# Imports all functions in the module
# import pizza
# You would then do pizza.make_pizza(16, 'extra cheese')

# Import specific functions
from pizza import make_pizza

make_pizza(16, 'mushrooms', 'extra cheese')

# Alias. Can do 'import pizza as p'
# then p.make_pizza(...)

Exemple #10
0
import pizza
pizza.make_pizza(16,'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# Copyright(C) 2018 刘珅珅
# Environment: python 3.6.4
# Date: 2018.4.8
# 导入函数模块
import pizza
import pizza as pa  # 给导入的模块指定别名

# 调用模块的函数
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers')

pa.make_pizza(15, 'green peppers')
Exemple #12
0
# [**param_names]
def set_hobbies(name, **hobbies):
    my_hobbies = {}
    my_hobbies['name'] = name
    for key, value in hobbies.items():
        my_hobbies[key] = value
    return my_hobbies

print(set_hobbies(name="Guibs", hobby_1='Swift', hobby_2='Python'))


# 注意: 在 import 时, 若不使用系统中的解释器, 而是用自己创建的, 则报错
# 导入存储在模块中的函数
# 导入整个模块
import pizza
pizza.make_pizza(12, 'mushrooms', 'extra cheese')

# 使用 as 给模块指定别名
import pizza as p
p.make_pizza(12, 'mushrooms', 'lots of cheese')

# 导入特定的函数
# from module_name import function_name_0, function_name_1, ...
# 这种语法可以无需使用 .
from pizza import make_pizza
make_pizza(12, 'mushrooms', 'more cheese')

# 使用 as 给函数指定别名
from pizza import make_pizza as buy_pizza
buy_pizza(12, 'mushrooms', 'a lot of cheese')
import pizza as p

p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'pieczarki', 'zielona papryka', 'podwójny ser')
Exemple #14
0
from pizza import make_pizza

make_pizza(10,'pepperoni')
Exemple #15
0
import pizza
# import the entire function
pizza.make_pizza(15, 'mushrooms', 'green peppers', 'extra cheese')

# import sepcific functions
from pizza import make_pizza
make_pizza(20, 'tuna fish', 'mushrooms', 'potato', 'tomato')

# as the alias  
from pizza import make_pizza as mp
mp(25, 'tuna fish', 'potato', 'tomato')

# import all functions in the module 
from pizza import *
make_pizza(25, 'tuna fish', 'tomato', 'cheese')

# tips
# function names should be specified
# functions should contain annotations and document strings 
# all imports should be at the beginning
# ......
Exemple #16
0
#-*-coding:utf-8-*-
# from pizza import make_pizza as mp
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms','green peppers','extra cheese')
Exemple #17
0
import pizza

pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'peppers', 'chocolate')
Exemple #18
0
# ~ def cars(brand,types,**car_info):
	# ~ vehicle={}
	# ~ vehicle['牌子']=brand
	# ~ vehicle['型号']=types
	# ~ for key,value in car_info.items():
		# ~ vehicle[key]=value
	# ~ return vehicle
# ~ che=cars('aima','diandongche',daiyan="zhoujielun",yanse="wucaibanlan")
# ~ print(che)

#8-15实现的功能是导入8.4.1的函数

#8-16
#导入模块
import pizza
pizza.make_pizza(16,'naiyou')

#模块中导入函数
from pizza import make_pizza
make_pizza(16,'naiyou')

#模块中导入函数并修改函数名
from pizza import make_pizza as mp
mp(16,'naiyou')

#导入模块并修改模块名
import pizza as p
p.make_pizza(16,'naiyou')

#导入模块中所有函数
from pizza import *
Exemple #19
0
"""
Created on Sun Apr  2 21:49:16 2017

@author: Leszek
"""
# Nadawanie stylu funkcjom:
# - dla wartosci parametrow domyslnych oraz słow kluczowych
# bez spacji po obu stronach znaku =
# - w każdej funkcji zwięzły komentarz wyjasniający jej przeznaczenie
# - dla długiej listy parametrow powdwojne wcięcia w nowym wierszu
# - polecenia import powinny znajdować się na początku pliku

# Import całego modułu
import pizza

pizza.make_pizza(40, 'pepperoni')
pizza.make_pizza(30, 'pieczarki', 'zielona papryka', 'podwojny ser')

# Import okreslonych funkcji z modułu
from pizza import make_pizza

pizza.make_pizza(24, 'grzyby', 'ser')
# ponieważ w poleceniu import jest wskazana funkcja nie ma potrzeby
#wywoływać nazwy modułu
make_pizza(33, 'pomidory', 'kiełbasa')

# Użycie słowa kluczowego "as" w celu zdefiniowania aliasu funkcji
from pizza import make_pizza as mp

mp(30, 'pepperoni')
mp(45, 'pomidor', 'cebula', 'szynka')
Exemple #20
0
#! python3
# -*- coding:utf-8 -*-
# @Time    : 2017/06/03 14:49
# @Author  : Hython.com
# @File    : making_pizzas.py
# @IDE     : PyCharm
import pizza
pizza.make_pizza(16, 'prpperoni')
pizza.make_pizza(12, 'mushrooms', 'green pepers', 'extrs cheese')

Exemple #21
0
import pizza


def greet_user(first_name, second_name):
    name = {'first name': first_name, 'second name': second_name}
    return name


pizza.make_pizza(12, 'haha', 'heheh')
name = greet_user('fang', 'wentao')
print(name)
Exemple #22
0
# importando modulos / 
# Podemos ultilizar um alias nas chamadas  
# import pizza as p =  importo o mudulo todo
# from pizza import make_pizza as mp =  importo apenas a função especifica
# import pizza * =  desse modo ele importa tds as funçoes do modulo especificado


# fazendo import do modulo pizza.py que tem uma função make_pizza
'''
import pizza

pizza.make_pizza(16, 'extracheesse')
pizza.make_pizza(8, 'calabreza', 'olive', 'onion')
'''

# importando funções especificas / importando apenas funções que eu queira de outro modulo

from pizza import make_pizza

make_pizza(10, 'mussarela')



import pizza

pizza.make_pizza(12, 'pepperoni')
pizza.make_pizza(14, 'mushrooms', 'sausage', 'pepperoni')
##Storing your functions in modules:
##importing an entire module:
#(important) A module is a file ending in .py that contains the code you
#want to import into your program.

#Ok just created a new file called pizza.py (let's see if this works without)
#configuring my work directory).
import pizza

pizza.make_pizza(16, "pepperoni")  #Wow this actually worked.
pizza.make_pizza(12, "mushroom", "green peppers", "extra cheese")

##importing specific functions:
from CCpython_ch8_exer4 import car

toyota = car("toyota", "mr2", "white", year=1989, vin=222930384)
print(toyota)  #this import statement worked just fine, but the only
#problem is that the print() statements were imported into the session as
#well.

from pizza import make_pizza

make_pizza(16, "pepperoni")
#this function call seems to work just fine. Will need to
#keep an eye on this.

##Using as to give a function an alias:
from pizza import make_pizza as mp

mp(26, "pepperoni")
mp(12, "mushroom", "cheese", "goat cheese")
Exemple #25
0
import pizza
# importing the pizza module withon the same directory 
# pizza contains the function make_pizza
# importing the entire pizza module 

pizza.make_pizza(16,'peperoni','sausage','cheese','bacon')
pizza.make_pizza(12,'cheese','ham','pineapple')
Exemple #26
0
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 23 13:18:03 2020

@author: jwitherspoon
"""

import pizza

pizza.make_pizza(16, 'anchovies', 'mushrooms', 'sausage', 'green peppers',
                 'extra cheese')
pizza.make_pizza(12, 'cheese', 'alfredo sauce', 'chicken')
Exemple #27
0
# -*- coding: utf-8 -*-

from pizza import make_pizza  # импортирование функции из модуля

# при вызове функции указывается только её название
make_pizza(16, 'pepperoni')
make_pizza(12, 'сыр', 'грибы')
Exemple #28
0
import pizza

pizza.make_pizza(16, 'pepperoni') #syntax = module_name.function_name()
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

# This syntax will import a specific function from a module:
# from module_name import function_name

from pizza import make_pizza

# Since the function was explicity imported, it can be called by name as usual.
make_pizza(13, 'twizzlers')

# This will import the function with an alias:

from pizza import make_pizza as mp

mp(40, 'brussel sprouts')

# Can also be done with modules:

import pizza as p

p.make_pizza(4, 'nanites')

# This syntax will import all functions in a module:
# Not recommended, best to import the desired function(s), or import the entire module.
from pizza import *

make_pizza(7, 'sausage')
import pizza

pizza.make_pizza(16, 'ペパロニ')
pizza.make_pizza(12, 'マッシュルーム', 'ピーマン', 'エクストラチーズ')
Exemple #30
0
def describe_pet(pet_name, animal_type = 'dog'):

describe_pet(pet_name = 'henley')

# because positional, keyword, and default values can all be used together, you'll often have several equivalent ways to call a function

# return values
"""a function doesn't always have to display its output directly, and instead can return a value or set of values
the value the function returns is called a return value. The return statement takes a value inside a funct
and sends it back to the line that called the function. Return values allow you to move much of your program's 
grunt work into functions"""
#returning a simple value
def get_formatted_name(first_name, last_name):
    """return a full name, neatly formatted."""
    full_name = f"{first_name} {last_name}"
    return full_name.title()

musician = get_formatted_name('maynard', 'keenan')
print(musician)

# making an argument optional
def get_formatted_name(first_name, last_name, middle_name=''):   # this makes the middle name optional
    """return a full name, neatly formatted."""
    if middle_name:
        full_name = f"{first_name} {middle_name} {last_name}"
    else:
        full_name = f"{first_name} {last_name}"
    return full_name.title()

musician = get_formatted_name('maynard', 'keenan', 'james')
print(musician)
# the optional value is listed last, and uses an empty string as a default value 

# returning a dict
def build_person(first_name, last_name):
    """Return a dict of info about a person"""
    person = {'first': first_name, 'last': last_name}
    return person

streamer = build_person('doctor', 'disrespect')
print(streamer)

# returning a more complex dict
def build_person(first_name, last_name, age=None):
    """Return a dict of info about a person"""
    person = {'first': first_name, 'last': last_name}
    if age:
        person['age'] = age
    return person

streamer = build_person('doctor', 'disrespect', age=38)
print(streamer)

# using a function with a while loop
def get_formatted_name(first_name, last_name):
    """Return a full name, neatly formatted."""
    full_name = f"{first_name} {last_name}"
    return full_name.title()

while True:
    print("\nPlease tell me your name:")
    print("(enter 'q' at any time to quit)")
    
    f_name = input("First name: ")
    if f_name == 'q':
        break
    
    l_name = input("Last name: ")
    if l_name == 'q':
        break
    
    formatted_name = get_formatted_name(f_name, l_name)
    print(f"\nHello, {formatted_name}!")
    
# city names
def get_city_country(city, country):
    """Returns the name of a city and its country"""
    city_country_pair = f"{city}, {country}"
    return city_country_pair.title()

while True:
    print("\nPlease type the name of the city and the country of interest:")
    print("\nenter 'q' at any time to quit)")
    
    city_name = input("City name: ")
    if city_name == 'q':
        break
    
    country_name = input("Country name: ")
    if country_name == 'q':
        break
    
    city_country= get_city_country(city_name, country_name)
    print(f"\nThe city-country pair is {city_country}")
    
# make album
def make_album(artist_name, album_name, tracks = None):
    """builds a dict describing a music album with artist name and album name, optional track number"""
    album = {'artist': artist_name.title(), 'album': album_name.title()}
    if tracks:
        album['tracks'] = tracks
    return album
    
album1 = make_album("tool", "lateralus", 14)
print(album1)

def make_album2(artist_name, album_name, tracks = None):
    """builds a dict describing a music album with artist name and album name, optional track number
    uses a while loop and user input"""
    album = 
    
    
# passing a list into a function #########################################
def greet_users(names):
    """print a simple greeting to each user in the list."""
    for name in names:
        message = f"Hello, {name.title()}!"
        print(message)
        
usernames = ['trap', 'mega', 'hoang', 'vince']
greet_users(usernames)

# modifying a list in a function ############################################
#start with some designs that need to be 3D-printed
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []

# simulate each design until none are left
# move each design to completed_models after printing
while unprinted_designs:
    current_design = unprinted_designs.pop()
    print(f"Printing model: {current_design}")
    completed_models.append(current_design)
    
# display all completed models
print("\nThe following models have been printed: ")
for completed_model in completed_models:
    print(completed_model)

# function version
def print_models(unprinted_designs, completed_models):
    """
    simulate printing each design, until none are left.
    move each design to completed_models after printing.
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print(f"Printing model: {current_design}")
        completed_models.append(current_design)
        
def show_completed_models(completed_models):
    """show all the models that were printed"""
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)
        
unprinted_designs = ['phone case', 'travis scott jordans', 'earthbound original']
completed_models = []

print_models(unprinted_designs, completed_models)  #print_models(unprinted_designs[:], completed_models) if you want a copy
show_completed_models(completed_models)

#note that if you want to prevent a function from modifying a list, use the slice notation [:]
"""function_name(list_name[:])""" # this is the syntax
# the slice notation makes a copy of the list to send to the function, so it doesn't modify it
##########################

# passing an arbitrary number of arguments: useful when you don't know ahead of time how many arguments a function needs to accept
def make_pizza(*toppings):
    # the * tells python to make an empty tuple called toppings and then pack whatever values it receives into this tuple
    """Summarize the pizza we are about to make, adding as many toppings as we'd like"""
    print("n\Making a pizza with the following toppings:")
    for topping in toppings:
        print(f" - {topping}")
    
    make_pizza('pepperoni')
    make_pizza('onions', 'mushrooms', 'olives')
    
# mixed positional and arbitrary arguments
# this is if you want to accept several different kinds of arguments
def make_pizza2(size, *toppings):
    print(f"\nMaking a {size}-inch pizza with the following toppings:")
    for topping in toppings:
        print(f" -{topping}")
        
    make_pizza2(16, 'pizza')
    
# using arbitrary keyword arguments
# the following always takes a first and last name, but it accepts an arbitrary number of keyword arguments too
def build_profile(first, last, **user_info):
    user_info['first_name'] = first
    user_info['last_name'] = last
    return user_info

user_profile = build_profile('david', 'mega',
                             location = 'fishtown',
                             field = 'data science')

print(user_profile)
# basically the ** builds out an empty dictionary called 'user_info'
# it will then fill this dict with the first + last name, and anything else you add
# all you need is the first + last name, which we add to the dict since we'll always need them

################################################exercises
def sandwich_builder(*ingredients):
    """makes a sandwich with as many ingredients as you want"""
    print("\nCreating a sandwich with the following ingredients:")
    for ingredient in ingredients:
        print(f" -{ingredient}")
        
def car_builder(manufacturer, model, **car_info):
    "builds a car with the manufacturer and model info, as well as anything else you want to add"""
    car_info['manufacturer_name'] = manufacturer
    car_info['model_name'] = model
    return car_info

megas_car_collection = car_builder('buick', 'roadmaster',
                      year ='1996',
                      color = 'burgundy',
                      engine = 'V8')
print(megas_car_collection)
###############################
############################
#storing your functions in modules
"""this allows you to hide the details of your program's code and also to 
reuse a function in many different programs. There are several ways to do this."""
#importing an entire mondule : module_name.function_name()
"""a module is a file ending in .py"""
def make_pizza(size, *toppings):
    """summarize the pizza we are about to make"""
    print(f"\Making a {size}-inch pizza with the following toppings:")
    for topping in toppings:
        print(f"-{topping}")
        
 """we'll name this pizza.py and make a separate file called making_pizzas.py in the same directory"""
 
 import pizza # to load this module, makes every function in the module available
 
 pizza.make_pizza(16, 'mushrooms', 'pepperoni')
 pizza.make_pizza(12, 'extra cheese')
Exemple #31
0
import pizza

pizza.make_pizza(16, 'pepper')
pizza.make_pizza(12, 'pepper', 'mushrooms', 'cheese')



Exemple #32
0
import pizza

pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(24, 'pepperoni', 'mushrooms', 'extra cheese')
Exemple #33
0
# Importing a function from a module (.py file). Same directory.
# If we use import, it imports all the functions from the module.
import pizza

pizza.make_pizza(12, "cheese", "pepperoni")  # Declare module module_name.

# We can import the function directly from the module.
from pizza import make_pizza

make_pizza(6, "mozzarela", "eggs")  # Omit the module_name call.

# Using as to give a function an alias.
from pizza import make_pizza as mp

mp(18, "provolone", "lettuce", "pineapple")
"""Syntax is from module_name import function_name as fn"""

# Using as to give a module an alias.

import pizza as p

# We use to call the module, and then the function we want. Similar to Numpy.
# (import numpy as np. It imports the module numpy as np. then we choose the
# function we want to use)
p.make_piza(12, "apple", "raspberry")

# Import all functions in a module.

from pizza import *

make_pizza(7, "hello")
import pizza
#from pizza import make_pizza
#from pizza import *

pizza.make_pizza(12, 'pepperoni', 'choclo', 'anana')
pizza.make_pizza(15, *pizza.STANDAR)

make_my_pizza = pizza.make_pizza

make_my_pizza(18, 'banana', 'durazno', 'frutilla', 'chocolate')
#coding:utf-8

import pizza

pizza.make_pizza(12, 'toppingA')
pizza.make_pizza(16, 'toppingA', 'toppingB', 'toppingC')