python Basics

Keywords: Python Ruby Attribute Java

The code section has very detailed comments, basically zero-based can read more, so let's not say much here, just go to the code.Where there are errors or shortcomings, please leave a message below.

Know the dictionary:

# -*- coding: utf-8 -*-
#A python dictionary defines a dictionary that stores attributes, the first one being keys and the last one being values, which need to be used in the middle: separated, used between each attribute, separated
alien = {'color': 'green', 'age': 18}
#Remove the data from the dictionary
print(alien['color'])

#Add key-value pairs
alien['x_pos'] = 0
alien['y_pos'] = 10
print(alien)

#Modify values in the dictionary
alien['color'] = 'red'
print(alien)

#Delete key-value pairs
del alien['color']
print(alien)

#Dictionary traversal, key s and value s are variables that can be freely written
user = {
	'username': 'admin',
	'first': 'enrico',
	'last': 'fermi',
}
for key, value in user.items():
	print("\nkey:"+key)
	print("value:"+value)

#Traverse all keys in a dictionary
for name in user.keys():
	print(name.title())
	
#A small case of a dictionary
print("Dictionaries and if A small case")
friends = ['first', 'last']
for name in user.keys():
	print(name.title())
	if name in friends:
		print('  key: '+name.title()+" : "+user[name].title())
		
#sorted() key value ordering
print()
for name in sorted(user.keys()):
	print(name)
	
#Traversing through all values in a dictionary
favorite = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'python',
}
print()
for language in favorite.values():
	print(language.title());
	
#set() removes duplicate elements
print("set()Remove duplicate elements")
for language in set(favorite.values()):
	print(language.title());

Run result:

Basic uses of dictionaries:

# -*- coding: utf-8 -*-
#Nested list
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}

aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
	print(alien)
	
#A simple little case
#Create an empty list
print("Small Case")
aliens = []
#Create 30 pieces of data
for alien_number in range(0, 30):
	new_alien = {'color': 'green', 'points': 5}
	aliens.append(new_alien)
for alien in aliens[0: 3]:
	if alien['color'] == 'green':
		alien['color'] = 'yellow'
		alien['speed'] = 'medium'
		alien['points'] = 10
for alien in aliens[0: 5]:
	print(alien)

#Store lists in a dictionary
print("Store lists in a dictionary")
favorite = {
	'jen': ['python', 'ruby'],
	'sarah': ['c'],
	'edward': ['ruby', 'go'],
	'phil': ['python', 'hashell'],
}
#Traversal Output
for name, languages in favorite.items():
	print(name.title()+"'s favorite languages are:")
	for language in languages:
		print('\t'+language.title())
		
#Store a dictionary in a dictionary
print("Store a dictionary in a dictionary")
users = {
	'aeinstenin': {
		'first': 'albert',
		'last': 'einstein',
		'location': 'princeton',
	},
	'mcurie':{
		'first': 'marie',
		'last': 'curie',
		'location': 'paris',
	},
}
for username, user_info in users.items():
	print("Username: "+username)
	full_name = user_info['first']+" "+user_info['last']
	location = user_info['location']
	
	print("\tFull name: "+full_name.title())
	print("\tLocation: "+location.title())


input() Basic usage of user keyboard input function:

# -*- coding: utf-8 -*-
#input() User keyboard input, prompt inside input
message = input("Please enter:")
print(message)

#int() Converts a string number to an int type
age = input("Please enter age:")
if int(age) > 18:
	print("adult")
else:
	print("Under age")
	
#% Remainder Operator, Remainder
number = input("Please enter a number:")
if int(number) % 2 == 0:
	print(str(number) + "Is Even")
else:
	print(str(number)+"is odd")

Run result:

Basic use of while loops:

# -*- coding: utf-8 -*-
#While loop, which executes the code block inside while if the condition after while is satisfied
number = 1
while number <= 5:
	print(number)
	number += 1
	
#break exits the loop
while True:
	city = input("Please enter a region:")
	if city == 'quit':
		break;
	else:
		print(city.title())

#continue ends this cycle
number = 0
while number < 10:
	number += 1
	if number % 2 == 0:
		continue
	print(number)

#while Loop Deletes List Elements
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while('cat') in pets:
	pets.remove('cat')
print(pets)

#A while loop is used in conjunction with a dictionary to add a dictionary
responses = {}
while True:
	name = input("Enter dictionary name:")
	response = input("Enter dictionary contents:")
	responses[name] = response
	
	repeat = input("Whether to continue typing(yes/no): ")
	if repeat == 'no':
		break
for nema, response in responses.items():
	print("Dictionary name:"+name+", Dictionary contents:"+response)

Run result:

Definition and use of functions (important):

Functions are the equivalent of Java's method of writing some code in a function that can be called repeatedly by name of the function. Let's look at some code below.

# -*- coding: utf-8 -*-
#Definition of function, def function name () defines function, function can be called repeatedly
def greet_user():
	"""Notes"""
	print("hello")
greet_user()

#A function with parameters, which are called with parameters
def greet_user(username):
	print("hello, "+username.title())
greet_user("Zhang San")
greet_user("Li Si")

#Key Arguments
def pet(name, age):
	print("name:"+name+", type:"+str(age))
#Key argument, parameter order can be distorted
#The following two are equivalent
pet(name="Zhang San", age=19)
pet(age = 18, name="Li Si")

#Set default values for functions
def describe(name, age=18):
	print("name:"+name+", type:"+str(age))
describe(name="Zhang San")
describe("Li Si")
describe("King Five", 16)
describe(name="King Five", age=16)

#Return return value with return value function
def getName(name):
	return name
name = getName("Zhang San")
print(name)

#Small Case
def get_formatted(first_name, last_name, middle_name=''):
	if middle_name:
		return first_name+" "+middle_name+" "+last_name
	else:
		return first_name+" "+last_name
musician = get_formatted('jimi', 'hendrix')
print(musician)
musician = get_formatted('john', 'hooker', 'lee')
print(musician)

Operation effect:

Use of functions:

# -*- coding: utf-8 -*-
#Function Return Dictionary
def build_person(first_name, last_name):
	person={'first': first_name, 'last': last_name}
	return person
musician = build_person('jimi', 'hendrix')
print(musician)

#Combining functions with while loops
def get_formatted_name(first_name, last_name):
	full_name = first_name+" "+last_name
	return full_name.title()
while True:
	f_name = input("First name(input q Sign out):")
	if f_name == 'q':
		break;
	l_name = input("Last name(input q Sign out):")
	if l_name == 'q':
		break;
	name = get_formatted_name(f_name, l_name)
	print(name)

#Pass List to Function
def greet_users(names):
	for name in names:
		msg = "Hello, "+name.title()+"!"
		print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)

#Pass any number of arguments, *toppings, *sign means you need to pass a tuple of toppings
print("Pass any number of arguments")
def make_pizza(*toppings):
	print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green')

Run result:

# -*- coding: utf-8 -*-
#Combining positional and any number of arguments
def make_pizza(size, *toppings):
	print("Size:"+str(size))
	for topping in toppings:
		print(" - "+topping)
make_pizza(10, 'pepperoni')
make_pizza(20, 'mushrooms', 'green')

#With any number of keyword arguments, **user_info, ** indicates that a list of user_info needs to be passed
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', loaction='princeton', field='physics')
print(user_profile)

Run result:

Import the entire module:

Import module, after importing, all functions in the imported file can be called, just like referencing something inside a file, first you need to create a new imported python file, which can contain some functions, such as make_pizza function inside:

# -*- coding: utf-8 -*-
#Combining positional and any number of arguments
def make_pizza(size, *toppings):
	print("Size:"+str(size))
	for topping in toppings:
		print(" - "+topping)

You can import this Python file into another file, then you can call the function inside the python file (both files must be in the same directory)

# -*- coding: utf-8 -*-
#Import entire module, hsDemo03 import file name
import hsDemo03

hsDemo03.make_pizza(12, 'pepperoni')

Run result:

Import specific functions:

To import a specific function, only the functions you import can be used, as shown below

#Import a specific function, followed by several function names, separated by signs
#from filename import function name 1, function name 2
#form filename import * represents all functions in the import module
from hsDemo03 import make_pizza

make_pizza(12, 'pepperoni')

as defines aliases:

Sometimes the import module or specific function file name is too long to use. You can take an alias to import when importing.

Format: Module or function name as alias

import hsDemo03 as hs

hs.make_pizza(12, 'pepperoni')
from hsDemo03 import make_pizza as m

m(12, 'pepperoni')

 

Posted by Angus on Wed, 31 Jul 2019 18:51:13 -0700