Python zero foundation crash course - Lecture 2 - Fundamentals of python, operations, variables, data types, input and output

Python zero foundation crash course - Lecture 2 - Python Foundation (basic), operation, variable, data type, input and output

Learning objectives

  1. Output results using print
  2. Operations and operators
  3. variable
  4. Data types (4 most commonly used)
  5. Input and output
  6. Homework after class (4 must do + 1 challenge)

Friendly tips:
1. Copy the following code into JupyterNotebook and execute it directly. Part of the code needs to be executed continuously.
2. Please refer to the previous lecture for the JupyterNotebook installation tutorial and initial course preparation. Python zero foundation crash course - Lecture 1 - understanding python, course objectives, installation environment and completing the first line of code "hello world"

1. Output: use print to output strings and numbers

print("hello world")
hello world
print(222)
222
print("hello world")
print("hello again")
hello world
hello again
print("This is the 3rd line,",
     "this is the 4th line.")
This is the 3rd line, this is the 4th line.

Pay special attention to the usage of \ t and \ n

\t stands for four spaces, also known as indentation, which is equivalent to pressing the Tab key

\n means line feed, which is equivalent to pressing Enter

Advanced tip 1: it is stipulated in the syntax of C, Java and other languages that the semicolon must be used as the identification of the end of the statement. Python also supports semicolons, which are also used to identify the end of a statement. However, in Python, the semicolon is no longer as important as in C and Java. The semicolon in Python can be omitted and the end of a statement can be identified mainly by line feed.

Advanced tip 2: in code blocks such as loop statements and functions, python distinguishes code blocks by indentation, which is usually a Tab key (equivalent to 4 spaces).

# \t indicates Tab indentation
print("This is the 3rd line,\tthis is the 4th line.")
This is the 3rd line,	this is the 4th line.
print("This is the 3rd line,\
this is the 4th line.")
This is the 3rd line,this is the 4th line.
# \n means line feed
print("This is the 3rd line,\nthis is the 4th line.")
This is the 3rd line,
this is the 4th line.

Type is used to verify the type of data

type("first")#String type
str
type(1111)#integer
int
type(111.111)#float 
float
type(False)#Boolean type
bool

2. Operation

Operation rules – > number 1 operator number 2
Operators – > + - */
Numbers – > 1,2,3,4

3 + 4
7
3 / 4
0.75
print(3 / 4)
0.75

How fast can Liu Xiang run? 110 meter hurdles, 13 seconds

print(110/12.97)
8.481110254433307
#Mod 
print(10 % 4)
2
#Exponentiation
print(4 ** 3)
64
#Seeking quotient
print(9 // 2)
4
#Seeking quotient
print(-9 // 2)
-5

Tip: jupyter notebook can set multiple outputs for one execution unit. You only need to execute the following code once

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

3. Variable

Python variable naming rules:

1. Variable names can only contain letters, numbers, and underscores. Variable names can start with letters or underscores, but not numbers. For example, you can name the variable message_1, but it cannot be named 1_message.
2. Variable names cannot contain spaces, but underscores can be used to separate words. For example, the variable name send_message works, but the variable name send message raises an error.
3. Do not use Python keywords and function names as variable names, that is, do not use Python to retain words for special purposes, such as print
4. Variable names should be short and descriptive. For example, name is better than n, student_name ratio s_n OK, name_length ratio_ of_ persons_ Name good.
5. Be careful with the lowercase letter l and the capital letter O, as they may be mistaken for the numbers 1 and 0.

Advanced tip: try to use lower case Python variable names. Using uppercase letters in variable names will not cause errors, but it is a good idea to avoid using uppercase letters.

first_number = 22
first_number
22
a = "this is a string"
a
'this is a string'

Unlike other programming languages (such as Java and C) that use braces "{}" to separate code blocks, Python uses code indentation and colon (:) to distinguish the levels between code blocks.

x = 9
if x < 8:
    print("x is lower than 8")
else:
    print("x is bigger than 8")
x is bigger than 8
speed = 100 / 15
distance = 1000
time = distance / speed
print(time)
150.0

4. Data type

There are four types of data commonly used in Python:

1.Integer(int) integer
2.Float(float)
3. Boolean (Boolean) Boolean (True or False)
4.String(str) string type

4.1 Int integer

Contains all integers, such as 0, 5, 42, 100000... In Python 3, the length of integers is theoretically unlimited (as long as the memory is large enough)

a = -2
print(a)
-2
b = 5
b += 5   #Equivalent to b = b + 5
print(b)
10

+=The C + = addition operator is equivalent to the C + = addition operator

-=The subtraction assignment operator c -= a is equivalent to c = c - a

*=The multiplication assignment operator c *= a is equivalent to c = c * a

/=The division assignment operator c /= a is equivalent to c = c / a

%=The modulo assignment operator c% = a is equivalent to C = C% a

**=The power assignment operator c **= a is equivalent to c = c ** a

//=The integer division assignment operator c //= a is equivalent to c = c // a

99 // 2 # quotient, integer
49
99 % 2 #Remainder, integer
1
type(99 // 2)
int

4.2 Float float

Numbers with decimal points, such as 3.14159, 1.0e8, 10000.00

type(100.01)
float
9.8235e2
982.35

4.2.1 Math Functions introducing math package

import math
print(math.pi)
print(math.e)
3.141592653589793
2.718281828459045
#Downward rounding
print(math.floor(98.77))
#Upward integration
print(math.ceil(98.77))
98
99
#Two methods of exponentiation
print(math.pow(2,4))
print(2**4)

#The result data types obtained by the two methods are different
print(type(math.pow(2,4)))#The math package is calculated to be floating point
print(type(2**4))#Direct calculation is an integer
16.0
16
<class 'float'>
<class 'int'>
#Prescription
print(math.sqrt(16))
4.0

4.3 Boolean

Contains two types: True or False

type(1 < 2)
bool
(1 < 3) or (3 < 1)
True
(1 < 3) and (3 < 1)
False
not (1 < 2)
False
a = (2 == 1)#Calculate False in parentheses first, and then assign it to a
print(a)
False
a = (2 != 1)
print(a)
True

4.4 String type

A string is a series of characters. In Python, strings are enclosed in quotation marks, which can be single quotation marks or double quotation marks.

Advanced tip: you can use "string" or "string" to represent a string. Generally, single quotation marks are equivalent to double quotation marks.

print("this is a test")#Double quotation mark
this is a test
print('this is a test')#Single quotation mark
this is a test
print("it's a test")#Double quotation mark embedded single quotation mark effect
it's a test
print("aaaa'a\"aa'a'a\"a'a")#Mixing effect
aaaa'a"aa'a'a"a'a
print('I like "Li Ning, China"')#Single quotation mark embedded double quotation mark effect
I like "Li Ning, China"
#Use 3 quotation marks to represent multiline string text
print('''this is 
a  test
lalala
''')
this is 
a  test
lalala
#Convert string 10 to integer 10, that is, the operation can be performed
1089 + int("10")
1099
#Convert integer 10 into string 10, that is, string splicing can be carried out
"1098"+ str(10)
'109810'
#True and False can be operated. True is 1 and False is 0
True + 3
4
3 - False
3

4.4.1 string splicing and copying

template = "my name is"
name = "Lily"
greeting = template + " " + name + "."
print(greeting)
my name is Lily.
#Quick assignment of string with "*"
laugh = 3 * "ha "
print(laugh)
ha ha ha 

4.4.2 string extraction and slicing

letters = "abcdefghijklmn"
letters[1]#[n] n is the subscript, taking the first character. The subscript of the string starts from 0, that is, the subscript of a is 0, the subscript of b is 1, and the subscript of C is 2 and so on
'b'
letters[13]
'n'
letters[14]#If the subscript range is exceeded, an error will be reported
---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_192/2629420110.py in <module>
----> 1 letters[14]#If the subscript range is exceeded, an error will be reported


IndexError: string index out of range
letters[-1]#Reverse value, reverse value from back to front
'n'

4.4.3 slicing: extracting substrings

Format: arr[start 🔚 step]

Syntax: cut the elements of [start, end]. Note that it is closed on the left and open on the right. The step size is step (when the step size is negative, it indicates reverse order). That is, start is taken on the left and end is not taken on the right

By default, start means to start from the leftmost index = 0
end means to get the rightmost index = len(arr) - 1 by default
step defaults to 1

letters = "abcdefghijklmn"
letters[0:3]
'abc'

[start:] all characters from start to end

letters[3:]
'defghijklmn'
letters[-3:]
'lmn'

[: end] reverse order offset from start to end-1

letters[:4]
'abcd'
letters[:-4]
'abcdefghij'
letters[:100]
'abcdefghijklmn'

[start:end] from start to (end - 1), that is, end is not included

letters[1:3]
'bc'
letters[-6:-2]
'ijkl'
letters[-2:-6]
''

[start 🔚 Step] from start to (END-1), skip the character value according to the step size

letters = "0123456789"
letters[0:9:3]#At this time, the step size is 3, that is, skip 2 characters
'036'
letters[::2]#All values, step size is 2, that is, skip 1 character value
'02468'
letters[::-2]#All reverse values are taken in steps of 2
'97531'

4.4.4 find string length

letters = "abcdefghijklmn"
len(letters)
14
len("Python description:Python is a programming ")

4.4.5 string splitting and splicing

Split into array format

lan = "today is a cloudy day"
lan.split()#Split by default
['today', 'is', 'a', 'cloudy', 'day']
#Split characters according to "," and
tan = "today,is,a, cloudy,day"
tan.split(',')
['today', 'is', 'a', ' cloudy', 'day']
print(tan)
tan.split()#Split by default
today,is,a, cloudy,day





['today,is,a,', 'cloudy,day']

join concatenated string, syntax: "n" join, that is to separate and splice strings according to the contents of N in quotation marks

For example, "" join represents a direct splicing string, ". join represents a space separated splicing string," - " join represents - as a concatenated string

t = ","
t.join("today")#Separate splicing strings according to ","
't,o,d,a,y'
"|".join("today is a cloudy day")
't|o|d|a|y| |i|s| |a| |c|l|o|u|d|y| |d|a|y'
#If the spliced content is an array, it will be spliced into a string according to the separator and each element in the array
"|".join(["today"," is" , " a" ," cloudy"," day" ])
'today| is| a| cloudy| day'

4.4.6 string substitution

test = "today is a cloudy day,a cloudy day,a cloudy day,a cloudy day"
test.replace("cloudy","sunny")#Replace all by default
'today is a sunny day,a sunny day,a sunny day,a sunny day'
test.replace("cloudy","sunny",1)#Replacement times, 1 means only one replacement
'today is a sunny day,a cloudy day,a cloudy day,a cloudy day'

4.4.7 string layout

#center centered, space filled
align = 'learn how to align'
align.center(30)
'      learn how to align      '
#Right justified, space filled remaining
align.ljust(30)
'learn how to align            '
#Left justified, space filled remaining
align.rjust(30)
'            learn how to align'
#The strip() method removes the leading and trailing spaces
ralign = align.rjust(30)
ralign.strip()
'learn how to align'

4.4.8 other common methods

#The method title() capitalizes the first letter of each word
name = "harry smith"
print(name.title())
Harry Smith
#The method upper() changes all letters of a word to uppercase
#The method lower() changes all letters of the word to lowercase
name = "harry smith"
print(name.upper())        
print(name.lower())        
HARRY SMITH
harry smith

Advanced tip: the method lower() is useful when storing data. Many times, you can't rely on users to provide the correct case, so you need to convert strings to lowercase first and then store them. When you need to display this information later, convert it to the most appropriate case.

#The method startwith() indicates whether it starts with some characters and returns bool
py_desc = "Python description:Python is a programming language that let you work quickly and effictively."
py_desc.startswith("Python description:")    
True
#The method endwith() indicates whether it ends with some characters and returns bool
py_desc.endswith("work quickly and effictively.")    
True
#The method find() means that it ends with some characters and returns the found position. If it is not found, it returns - 1
py_desc = "Python description:Python is a programming language that let you work quickly and effictively."
py_desc.find('language')    
43
#The method count() indicates the number of times some characters are found
py_desc = "Python description:Python is a programming language that let you work quickly and effictively."
py_desc.count("Python")
2
#Remove the fixed characters at the beginning and end, and the default bit space. You can customize and pass in parameters
py_desc = "*Python description .Python is a programming language that let you work quickly and effictively.  "
py_desc.strip('*')
'Python description .Python is a programming language that let you work quickly and effictively.  '
favorite_language = "##python##"
print(favorite_language.rstrip("#"))#Remove trailing fixed characters
print(favorite_language.lstrip("#"))#Remove the fixed characters on the head edge
print(favorite_language.strip("#"))#Remove the fixed characters at the beginning and end
##python
python##
python

4.5 data type conversion

#int + float = float
10 + 10.1
20.1
#The types are inconsistent and cannot be added. An error is reported
"10" + 10
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_192/1141157989.py in <module>
      1 #The types are inconsistent and cannot be added. An error is reported
----> 2 "10" + 10


TypeError: can only concatenate str (not "int") to str
#String splicing
"10" + "110"
'10110'
#Integer to string, then splice
str(10) + "110"
'10110'
#String to integer, add again
10 + int("110")
120
#String addition
str(True) + "3"
'True3'
#Value addition, True=1, False=0
True + 3.0
4.0

5. Input and output

input (from keyboard), print output (from display)

Advanced tip: the% s% d in python is the formatted string. After use, it occupies a position in the long string to be output. When outputting a string, you can automatically update the content of the string according to the value of the variable.

Common formatting strings are as follows:

%s string (display with str())
%d decimal integer
%f floating point number
%c single character
%r string (display with repr())

name = input("what's your name?")
age = input("how old are you?")
height = input("how tall are you?")

print("so,your name is %s,your are %s years old, %s meters tall" % (name,age,height))
print("so,your name is" +" " + name)
what's your name?lulugege
how old are you?38
how tall are you?181
so,your name is lulugege,your are 38 years old, 181 meters tall
so,your name is lulugege

Add \ n to achieve input line feed effect

name = input("what's your name?\n")
age = input("how old are you?\n")
height = input("how tall are you?\n")
print("so,your name is %s,your are %s years old, %s meters tall" % (age,name,height))
what's your name?
lulugege
how old are you?
38
how tall are you?
181
so,your name is 38,your are lulugege years old, 181 meters tall

6. After class homework, the answer is in the next lecture

1. Write a program to read the two input numbers and add them to output

Your code:

2. Hands on programming, use Python to calculate the formula

21980 + 987345

4950782 - 2340985

3456 * 4390

9285 / 5

The 21st power of 57

Remainder of 98434 / 456

Your code:

3. Enter a number, which represents the number of minutes from 0 a.m. in the past. Please calculate and output the current time

This program needs to output two decimals: hour (0 to 23): minute (0 to 59)

For example, if your input is 150, it should be 2:30, so your program should output 2:30

Your code:

4. Use Python to express the following formula

b ∗ ( 1 + r 100 ) n b*(1+\frac{r}{100})^n b∗(1+100r​)n
a 2 + b 2 b \sqrt \frac{a^2+b^2}{b} ba2+b2​ ​

Your code:

*(challenge) 5. Programming practice project

Small project: King glory hero information extraction

1. Purpose: in https://pvp.qq.com/web201605/herolist.shtml Three hero avatar pictures and hero names are extracted and output on a new line

2. Methods: the HTML text of the list of King glory heroes was intercepted, and the required information was extracted by string related operations

3. Output result reference style:

HTML material is as follows:

Your code:

Tags: Python

Posted by mister_t101 on Sun, 17 Apr 2022 01:14:25 +0930