Introduction to Python programming to practice (2)

1. User input and while loop

Python 2.7 uses raw_input() to prompt the user for input, which is interpreted as a string just like input() in python3.

name=input("please enter your name: ")
print("Hello, "+name+"!")
please enter your name: Eric
Hello, Eric!

  

2. Function

(1) Pass any number of arguments

def make_pizza(*toppings):
    print(toppings)
    
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')

The asterisk in the parameter name *toppings tells Python to create an empty tuple called toppings and wrap all received values ​​into this tuple.

 

(2) Use any number of keyword arguments

def build_profile(first,last,**user_info):
    profile={}
    profile['first_name']=first
    profile['last_name']=last
    for key,value in user_info.items():
        profile[key]=value
    return profile
    
user_profile=build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)
{'first_name': 'albert', 'location': 'princeton', 'field': 'physics', 'last_name': 'einstein'}

The two asterisks in the parameter **user_info cause Python to create an empty dictionary called user_info that accepts any number of keyword arguments.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325233442&siteId=291194637