python data type conversion and operators

This section needs to know

  1. Reserved Words and Identifiers
  2. Understanding Data Types in Python
  3. basic data type
  4. Conversion between data types
  5. eval() function
  6. different base numbers
  7. operator
  8. operator precedence
  9. small classroom tasks

1. Reserved words

true='real'
True='real'
  File "<ipython-input-2-0244e2f5e602>", line 2
    True='real'
    ^
SyntaxError: cannot assign to True

2. View reserved words

import keyword  # import keyword library
print(keyword.kwlist)  # View reserved words
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

3. Naming rules for identifiers

my_name_1='Ali who loves to listen to music' # my_name_1 is an identifier (letters, numbers, underscores)
print(my_name_1)
Ali who loves to listen to music

4. Naming and using variables

# Create an integer variable and assign it the value 8
luck_number=8
# string variable
my_name='Ali who loves to listen to music'

print(my_name+"The lucky number for is:",luck_number,sep='')
The lucky number of Ah Li who loves listening to music is:8
# type() can view the data type
luck_number=8
print('luck_number The data type of is:',type(luck_number))
luck_number The data type of is: <class 'int'>
num1=num2=1024 # continuous assignment
print(id(num1)) # Check the address of num1
print(id(num2)) # Check the address of num2
99802416
99802416

Constants are generally capitalized by default

5. Integer types

num=987 # default decimal
num2=0b1010101 # Use binary to represent integers
num3=0o765 # Use octal to represent integers
num4=0x87ABF # Integer representation using hexadecimal
print(num)
print(num2)
print(num3)
print(num4)
987
85
501
555711

6. Floating point type

height=187.6 # height
print(height)
print(type(height)) # Query the data type of height

x=10
y=10.0
print('x The number type of is:'+str(type(x)))
print('y The number type of is:'+str(type(y)))
187.6
<class 'float'>
x The number type of is:<class 'int'>
y The number type of is:<class 'float'>
# Uncertain mantissa problem with floating point numbers
print(0.1+0.2)
0.30000000000000004

If you want to keep one decimal place, you can use the built-in function round()

print(round(0.1+0.2,1)) # 1 is to keep only one decimal place
0.3

7. Plural types

x=123+456j
print('real part:',x.real)
print('imaginary part:',x.imag)
real part: 123.0
 imaginary part: 456.0

8. String type

# single line string
city='Beijing'
address='Yanta District, Xi'an'
print(city)
print(address)

print('-------------------')

# Multi-line string (three pairs of single quotes or three pairs of double quotes)
info='''address:Yanta District, Xi'an
 recipient:Ali who loves to listen to music
 Phone number:1860000000
'''
print(info)
Beijing
 Yanta District, Xi'an
-------------------
address:Yanta District, Xi'an
 recipient:Ali who loves to listen to music
 Phone number:1860000000

9. Escape characters

print('Beijing')
print('Welcome')
print('------------')
print('Beijing\n Welcome') # When \n is encountered, it is a newline, and it can be continuous newline
print('north\n Beijing\n joyous\n welcome\n you')
print('-----------')
print('Beijing\t Welcome') # A \t is eight spaces
print('Beijing Beijing\t Welcome') # A \t is eight spaces
print('-----------')
print('The teacher said:\'study well,up every day\'')
print('The teacher said:\"study well,up every day\"')
print('-----------')
print(r'north\n Beijing\n joyous\n welcome\n you') # The escape character will be invalid after adding r
Beijing
 Welcome
------------
Beijing
 Welcome
 north
 Beijing
 joyous
 welcome
 you
-----------
Beijing	Welcome
 Beijing Beijing	Welcome
-----------
The teacher said:'study well,up every day'
The teacher said:"study well,up every day"
-----------
north\n Beijing\n joyous\n welcome\n you

10. Indexing and slicing of strings

s='HELLOWORLD'
print(s[0],s[-10]) # Serial number 0 and serial number -10 represent the same character

print('Beijing welcomes you'[4])
print('Beijing welcomes you'[-1])

print('---------slice--------')
print(s[2:7]) # forward increasing sequence
print(s[-8:-3]) # reverse descending sequence
print('-----------------')
# Slices start at 0 by default
print(s[:5])
print(s[5:])

H H
 you
 you
---------slice--------
LLOWO
LLOWO
-----------------
HELLO
WORLD

11. String type operations

x='2022 year'
y='Beijing Olympic Games'
print(x+y) # Concatenate strings x and y
print(10*x) # The content in x is output 10 times
print(x*10) # The content in x is output 10 times

print('Beijing' in y) # Whether 'Beijing' is a substring of "Beijing Olympic Games"
print('Shanghai' in y) # Whether 'Shanghai' is a substring of "Beijing East Olympic Games"

2022 Beijing East Olympic Games
2022 Year 2022 2022 2022 2022 2022 2022 2022 2022 2022
2022 Year 2022 2022 2022 2022 2022 2022 2022 2022 2022
True
False

12. Boolean type

x=True
print(x)
print(type(x))
print(True+10) # 1+10
print(False+10) # 0+10
print('--------------------')
# The bool value of the test object
print(bool(18)) # True
print(bool(0),bool(0.0)) # False False
# In summary, all non-zero numeric Boolean values ​​are True
print(bool('Beijing welcomes you')) # True
print(bool('')) # False
print(bool(False)) # False
print(bool(None)) # False
True
<class 'bool'>
11
10
--------------------
True
False False
True
False
False
False

13. Conversion between data types

x=10
y=3
z=x/y # When performing a division operation, assign the result of the operation to z
print(z,type(z)) # implicit conversion, the type of the result is implicitly converted by the operation


# Convert the float class to int type, the result only retains the integer part
print('Will float class converted to int type',int(3.14))
print('Will float class converted to int type',int(3.9))
print('Will float class converted to int type',int(-3.14))
print('Will float class converted to int type',int(-3.9))


# Convert int type to float type
print('Will int Type converted to float type',float(10))

# Convert str type to int type
print(int('100')+int('200'))

# Convert str type to float type
print('Will str typecast to float type',float('3.14'))
3.3333333333333335 <class 'float'>
Will float class converted to int Type 3
 Will float class converted to int Type 3
 Will float class converted to int type -3
 Will float class converted to int type -3
 Will int Type converted to float Type 10.0
300
 Will str typecast to float Type 3.14
# When converting the str type to int or float type, an error is reported
print(int('18a'))
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-118-170fe4a42e45> in <module>
      1 # When converting the str type to int or float type, an error is reported
----> 2 print(int('18a'))


ValueError: invalid literal for int() with base 10: '18a'
# When converting the str type to int or float type, an error is reported
print(int('3.14')) # It can only be an integer to help convert
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-123-20103c6ee87d> in <module>
      1 # When converting the str type to int or float type, an error is reported
----> 2 print(int('3.14'))


ValueError: invalid literal for int() with base 10: '3.14'
# When converting str to float type error reporting
print(float('45a.987'))
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-124-abba69a210c9> in <module>
      1 # When converting str to float type error reporting
----> 2 print(float('45a.987'))


ValueError: could not convert string to float: '45a.987'
# chr() and ord() functions
print(ord('dripping')) # 28435 The corresponding value in the Unicode table
print(chr(28435)) # Convert an integer value to the corresponding word
28435
 dripping
# Conversion operation between bases Conversion operation between decimal and other bases
print('decimal to hexadecimal:'+hex(28435))
print('decimal to octal conversion:'+oct(28435))
print('decimal to binary conversion:'+bin(28435))
decimal to hexadecimal:0x6f13
 decimal to octal conversion:0o67423
 decimal to binary conversion:0b110111100010011

14. Use of eval function

s='3.14+3'
print(s,type(s))
x=eval(s)
print(x,type(x))
3.14+3 <class 'str'>
6.140000000000001 <class 'float'>
# The eval() function is often used together with the input() function to obtain the numeric value entered by the user
age=eval(input('Please enter your age:'))
print(age,type(age))
height=eval(input('Please enter your height:')) # Convert the string to float type, which is equivalent to float(height)
print(height,type(height))
Please enter your age:18
18 <class 'int'>
Please enter your height:178.3
178.3 <class 'float'>
# When using eval() to report an error
# hello='Welcome to Beijing'
# print(hello)
print(eval('hello'))
# type(eval('hello'))
Beijing welcomes you
 Beijing welcomes you
str

15. Arithmetic operators

print('addition:',1+1)
print('subtraction:',1-1)
print('multiplication:',2*3)
print('division:',10/2) # an implicit conversion has occurred
print('Take the remainder:',10%3)
print('evenly divisible:',10//3)
print('exponentiation:',2**3) # 2*2*2
addition: 2
 subtraction: 0
 multiplication: 6
 division: 5.0
 Take the remainder: 1
 evenly divisible: 3
 exponentiation: 8
# 0 cannot be a divisor
print(10/0)
---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

<ipython-input-29-1abbd1704c2f> in <module>
      1 # 0 cannot be a divisor
----> 2 print(10/0)


ZeroDivisionError: division by zero

16. Assignment operator

x=20 # Direct assignment, directly assign 20 to the variable x on the left
y=10
x=x+y # Assign the sum of x+y to x, and the value of x is 30
print(x)
x+=y
print(x) # x=40
x-=y # Equivalent to x=x-y
print(x) # x=30
x*=y # Equivalent to x=x*y
print(x) # x=300
x/=y # x=x/y
print(x) # x=30.0,type(x) is float
x%=2 # x=x%2
print(x) # x=0.0
z=3
y//=z # y=y//z
print(y) #y=3
y**=2 # y=y**2
print(y)

# Python supports chained assignment
a=b=c=100 # It is equivalent to executing a=100 b=100 c=100
print(a,b,c)

# Python also supports series unpacking assignment
a,b=10,20 # It is equivalent to executing a=10 b=20
print('before exchange\na the value of:',a,'\nb the value of:',b)


print('--------How to swap the values ​​of two variables--------')
# in other languages
temp=0
temp=a # Assign the value of a to temp, and the value of temp is 10
a=b # Assign the value of b to a, the value of a is 20
b=temp #Assign the value of temp to b, and the value of b is 10
print('after exchange\na the value of:',a,'\nb the value of:',b)

# in the Python language
b,a=a,b # The value of a is assigned to b, and the value of b is assigned to a
print(a,b)
30
40
30
300
30.0
0.0
3
9
100 100 100
 before exchange
a the value of: 10 
b the value of: 20
--------How to swap the values ​​of two variables--------
after exchange
a the value of: 20 
b the value of: 10
10 20

17. Comparison Operators

print('98 greater than 90?',98>90)
print('98 Less than 90?',98<90)
print('98 equal to 90?',98==90)
print('98 Is it equal to 98?',98==98)
print('98 Isn't it equal to 90??',98!=90)
print('98 Isn't it equal to 98??',98!=98)
print('98 greater than or equal to 98?',98>=98)
print('98 Is it less than or equal to 98?',98<=98)
98 greater than 90? True
98 Less than 90? False
98 equal to 90? False
98 Is it equal to 98? True
98 Isn't it equal to 90?? True
98 Isn't it equal to 98?? False
98 greater than or equal to 98? True
98 Is it less than or equal to 98? True

18. Logical operators

logic and

print(True and True)
print(True and False)
print(False and False)
print(False and True)
print('-------------')
print(8>7 and 6>5) # True and True
print(8>7 and 6<5) # True and False
print(8<7 and 6<5) # False and False
print(8>7 and 6>5) # False and True
print(8<7 and 10/0) # Do not evaluate the second expression when the first expression is False
True
False
False
False
-------------
True
False
False
True
False

logical or

print(True or True)
print(True or False)
print(False or False)
print(False or True)
print('---------------------')
print(8>7 or 10/0)# Do not evaluate the second expression when the first expression is True
True
True
False
True
---------------------
True

logical NOT

print(not True)
print(not False)
print(not 8>7)
False
True
False

19. Bit operation (just understand)

print(12&8)
8

print(4|8)
12

print(31^22)
9

print(~123)
-124

print(2<<2)
print(2<<3)
8
16

print(8>>2)
print(-8>>2)
2
-2

20. Operator precedence

You can increase the priority of operations by adding parentheses

little practice

1. Which of the following is not a reserved word in the Python language ( C )
A.False
B.and
C.true
D.if

2.x=5,y=3, after executing x,y=y,x, what are the values ​​of x and y respectively? ( B )
A.5,3
B.3,5
C.3,3
D.5,5

3. Which of the following variable names is illegal (A)
A.for
B._my
C.a_int
D.c888

4. "The world is so big, I want to see it" [7:-3] ( D )
A. I want to go
B. want to go
C. I think
D. think

5. The value equal to 0xf2 is ( B )
A.342
B.242
C.0b11010010
D.o362

6. Which of the following is not a built-in data type of Python ( A )
A.char
B.int
C.float
D.list

7. The following is the result of the print('\nPython') statement (A)
A. Output on a new line: Python
B. Directly output '\nPython'
C. Directly output '\nPython'
D. Output n first, and then output Python in a new line

8. Among the following options, the description about the Python string is wrong ( D )
A. A string is zero or more strings enclosed in a pair of double quotes "" or a pair of single quotes ''
B. A string is a sequence of characters and a type of sequence
C. Strings use [] for indexing and slicing
D. The slicing method of Python string is [N:M], excluding M

9. Regarding the assignment statement, the error described in the following options is ( B )
A. The assignment statement is represented by the symbol "="
B. Assignment and binary operators can be combined, such as &=
C.a,b=b,a can realize the exchange of a and b values
D.a,b,c=b,c,a is illegal

combat one
Topic: Obtain a 4-digit integer from the keyboard, and enter the numbers in the ones, tens, hundreds, and thousands respectively
Requirements: You can use the eval() function or the int() function to convert the number obtained from the keyboard into an int type, and obtain the number through integer division and remainder operations
Running effect diagram

num=eval(input('Please enter a four-digit integer:'))
sd=num%10 # Digits
tens=num//10%10
hundred=num//100%10
thousands=num//1000
print('Digits:',sd)
print('tens digit:',tens)
print('Hundreds digit:',hundred)
print('thousands digit:',thousands)
Please enter a four-digit integer:1234
 Digits: 4
 tens digit: 3
 Hundreds digit: 2
 thousands digit: 1

Combat two
Topic: Predict the height of the son based on the height of the parents
Requirements: Input the height of the parents from the keyboard, and use eval() to convert float() to the input data type. Calculation formula: son height = (father's height + mother's height) * 0.54
Running effect diagram

father_height=eval(input('Please enter father's height:'))
mother_height=eval(input('Please enter mother's height:'))
son_height=(father_height+mother_height)*0.54
print('The predicted height of the son is:',round(son_height,2))
Please enter father's height:187.4
 Please enter mother's height:165.8
 The predicted height of the son is: 190.73

Tags: Python programming language

Posted by wardo on Wed, 23 Nov 2022 03:48:14 +0300