python data types and operators
First, python type judgment
type, isinstance
type (variable or constant): return data type
a = 23.3 print(type(a)) b = 2e3 print(b, type(b)) outputs:
2000.0
isinstance(variable or constant, data type name) Determine the data type. Returns true if it is the specified data type, otherwise returns false
a = 10 if isinstance(a, int): print("a is an integer")
Second, python data types are divided into built-in types (types supported by the language itself) and custom types, classes.
Common built-in types include:
1. Numerical type
- Integer int, representing the integer type. For example: 3,4,5
- A floating-point number float, representing a real number. There are 2 ways of writing: natural notation and scientific notation
Natural notation: 2.3, 4.5
Scientific notation: 2e2 means 200. e refers to an exponent with base 10, and e must be followed by an integer
a = 23.3 print(type(a)) b = 2e3 print(b, type(b)) outputs:
2000.0
- complex number complex 2+3j
c = 3 + 2j print(c, type(c)) output: (3+2j)
2. Boolean type
The Boolean type represents true and false, right and wrong, yin and yang, etc. As long as it is two states, it can be represented by the Boolean type. It has two values: True(1) and False(0)
Arithmetic operations that can be performed on numbers and booleans
a = 3
b = 3.5
c = True
print(a + c)
print(c * 5)
3. String type
Strings enclosed in quotation marks
'single quoted string'
'double quoted string'
'''
multiline string
'''
"""
multiline string
"""
Escape the string, if the single quote contains a single quote, then the single quote inside needs to be escaped
escape character description escape character description
\' represents an ordinary character single quote
\rEnter
\"represents an ordinary character double quotation mark
\nNewline
\''' an ordinary triple single quote
\\ an ordinary character
\\"""A normal triple double quotation mark
\ttab key
3. Operators and expressions (expressions have no value)
1. Arithmetic operators include: + - * / //(divide) %(modulus, remainder) **(exponent)
The purpose of the modulo operator: judging parity, judging whether it can be divisible, the greatest common divisor, daffodil number
2. Function
- math function
- random function
The random function is introduced into the random library
import random print(random.randint(1,100)) Random integers between 1 and 100, before and after the package print(random.random()) Random decimals between 0 and 1, without print(random. randrange(1,100,2)) Output random numbers with a step size of 2 between 1 and 100, output before and after the packet : 33 0.05559590353134125 21
3. Assignment operator
= += -= *= /=
The left side of the assignment operator must be a variable
4. Relational Operators
Relational operators are comparison operators, and the result is a boolean value
Exercise:
1. Convert Fahrenheit to Celsius
C = float(input()) F = 1.8 * C + 32 print(F)
2. Solve the first-order equation ax+b=0, enter the values of a and b, and solve x
a = int(input("Please enter the coefficient a of the linear equation:")) b = int(input("Please enter the constant b of the linear equation:")) print("The root of the linear equation %dx+%d=0 is : x=%d"%(a, b, (0 - b)/a)) output please enter the coefficients of the linear equation a: 2 please enter the constants of the linear equation b: 6 the root of the linear equation 2x+6=0 is : x=-3 3. Write a program to receive the names, math scores and computer scores of 2 students input from the keyboard, store the chalk into 6 variables, and then print out the names and total scores of the 2 students
name1 = input("请输入同学a的名字:")name2 = input("请输入同学b的名字:")core1 = float(input("请输入同学a的数学成绩:"))core2 = float(input("请输入同学b的数学成绩:"))core3 = float(input("请输入同学b的计算机成绩:"))core4 = float(input("请输入同学b的计算机成绩:"))core_all = core1 + core2 + core3 + core4print("同学%s和同学%s的总成绩为:%.0f"%(name1, name2, core_all))print("同学%s和同学%s的总成绩为:%.2f"% (name1, name2, (core1 + core2 + core3 + core4)))
4.编写一程序,对用户输入的两个数据a和b,输出交换后的a和b的值
a = int(input("请输入值a:"))b = int(input("请输入值b:"))a, b = b, aprint("分别输出a和b的值:%d,%d"%(a, b))
5.从控制台输入2个数,输出较大的值
a = int(input("please enter the value a:")) b = int(input("please enter the value b:")) print("please output the maximum value: %d"% max(a, b)) 6 .Enter an integer from the keyboard to determine whether the number is divisible by 3
a = int(input("Please enter the value a:")) if a % 3 ==0: print("Divisible by 3") 7. Input a 3-digit number from the keyboard, and find the difference of each number of the three-digit number and
a = int(input("Please enter a three-digit integer a:")) gewei = a % 10 shiwei = a // 10 % 10 baiwei = a // 100 print("The sum of the digits is: %d"% (gewei + shiwei + baiwei))
8. Enter a three-digit number from the console, if it is the number of daffodils, it will print"is the number of daffodils", otherwise it will print"not the number of daffodils"
a = int(input("Please enter a three-digit integer a:")) gewei = a % 10 shiwei = a // 10 % 10 baiwei = a // 100 if gewei**3 + shiwei**3 + baiwei** 3 == a: print("is the number of daffodils") else: print("is not the number of daffodils")
python data types and operators Related posts
- python variable data types and immutable data types
There are six standard data types in python3: number (number type), string (string type), list (list), type (yuan ancestor), dictionary (dictionary), set (set), of which there are three immutable types: number, type, stri; the remaining three are variable data types.0x01: immutable data typeFor judg ...
- Python variables and data types-data types
type of data1. IntegerPython can handle integers of any size, of course, including negative integers. In Python programs, the representation of integers is exactly the same as mathematical writing, for example: 1, 100, -8080, 0, and so on. Because computers use binary, it is sometimes more convenien ...
- Module 10: I/O stream (how java communicates with external data)
Module 10 :I/Ostream ( how javacommunicates with external data)Input/Output: Refers to cross the boundary of the JVMand exchange data with the source or target data source of external data.outputenterNote: I /O is for the JVM.The File class ( java.io.*) can represent a file or a directory (in JAVA, ...
- python-Numpy data type: data type is not understood
It is still fairly new to Numpy in Python... I am trying to build my own array from RINEX data (see example):G13 2014 01 02 02 00 00 .440594740212D-04 -.375166564481D-11 .000000000000D+00 .290000000000D+02 .705937500000D+02 .382980238378D-08 -.135945866650D+01 .353716313839D-05 .509947887622D-02 .13 ...
- java - why is there no best case in Big O notation for arrays/stacks/queues and other data structures?
I'm going through this cheat sheet https://www.packtpub.com/sites/default/files/downloads/4874OS_Appendix_Big_O_Cheat_Sheet.pdf and I'm wondering why the best case is not mentioned on the site. Why only the normal case and the worst case condition?Solution:Mainly for the same reason you have auto in ...
- Java-JPA repository and block I/O
I encountered a problem, after using JpaRepository to write to the database, I need to execute several slow HTTP requests on a separate thread. The problem is that doActualJob() blocks while waiting for a series of futures to settle. This seems to prevent the basics The Hibernate session is closed, ...
- Python file I/O Ⅳ
Directory in Python:All files are contained in different directories, but Python can handle them easily. The os module http://www.xuanhe.net/ has many ways to help you create, delete and change directories.mkdir() methodYou can use the mkdir() method of the os module to create new directories in the current directory. You need to provide a parameter that contains the name of the directory to be created.grammar:example:The following example will create a new directory test in the current director ...
- Data Structure and Algorithm (Python Version): Time Complexity and Big O Notation
1. Time complexityFirst, let's look at a question·:Question: If a+b+c=1000, and a^2+b^2=c^2 (a, b, c are natural numbers), how to find all possible combinations of a, b, c? When we saw this question, our first reaction was to directly apply the three-cycle enumeration method to get the answer direct ...
- cloud computing Python automatic operation and maintenance development practice III, python file type
Cloud computing Python automatic operation and maintenance development practice 3. python file typeIntroduction:There are 3 file types commonly used in python1. Source code py2. Byte code pyc3. Optimize the code pyoSourcecode:The files of python source code have the extension"py", which are interpre ...
- [Python data structure and algorithm review day38] 1-02-Time complexity and big O notation + if a+b+c=1000, and a^2 + b^2=c^2 (A, b, c are natural numbers), how to find all possible combinations of a
1-02-Time Complexity and Big O NotationArticle Directory1-02-Time Complexity and Big O NotationtopicPython code description algorithmresultNew optimization ideasNewly optimized codeNew optimization resultsThe problem of measuring algorithm efficiencyExecution time reflects algorithm efficiencyIs the time value alone absolutely credible?Time complexity and "Big O Notation"How to understand "Big O Notation"Worst time complexitySeveral basic calculation rules of time complexitytopicIf a+b+c=1000, a ...
- python concurrent programming---I/O model
Some things you need to know before learning something newSynchronous: When a process is executing a task, another process must wait for its execution to complete before continuing to execute#The so-called synchronization means that when a function call is issued, the call will not return until the ...
- Why is heappop time complexity in python O(logn) (not O(n))?
For a list, heappop will pop up the previous element. The time complexity of deleting an element from the front of the list is O(n). Am I missing something?Solution:A heappop() rearranges the log(n) elements in the list so that it does not have to move every element.This is easy to see:>>> ...
- python data type-variable data type and immutable data type
Data types in python include the following categories:1. Number type (Number): integer type (int), floating point type (float), complex number (complex)2. String type (String)3. List4. Set5.Tuple6. Dictionary (Dict)Among the above types are variable types: Dict, List, SetThe immutable types are: Boo ...
- 【Unity|C#】(3)——File reading and writing (I/O type)
【Learning Materials】> Online DocumentationOfficial document: https://docs.microsoft.com/zh-cn/dotnet/csharp/Novice tutorial: https://www.runoob.com/csharp/csharp-tutorial.html> Video TutorialTencent Academy, Siki Academy【notes】File operation- File / FileInfo / FileStreamhttps://www.runoob.com/ ...
- Python eight data types
Article Directory1.number (number type)2.string (string type)3. Boolean (Boolean value) and null value4.list (list type)5.tuple (tuple type)6.dict (dictionary type)7.set (collection type)8. Data type replacementMainly refer to Python basics (3)-eight data types, slightly modifiedThe eight data types ...
- "Data Structure and Algorithm"-O(3N)=O(N)?
God's grinding wheel turns very slowly, but it grinds very finely. -MaughamThis article has been included in my GitHub, everyone is welcome to star and issues. https://github.com/midou-tech/articlesBasic concepts of data structuredata structureA collection of data elements that have one or more spec ...
Recent Posts
- javascript-Cannot execute code from the released script
I have a function in a different frame that I need to cover. Also, I need to call the original function from my cover. For this, I use the following:myFrame.SomeFunction = (function () {var originalSomeFunction = myFrame.SomeFunction; return function(arg1, arg2, arg3) {alert('In override!'); origina...
- Batch Normalization algorithm training and inference process
Batch Normalization is batch normalization, adding a Batch Normalization process before the layer of the neural network is not activated and output, hereinafter referred to as BN. About the principle of BN, there are a lot of information on the Internet, you can also refer to this https://www.cnblog...
- Create multiple java threads in the while loop according to the number of inputs
I am trying to write a java program that reads information from the database and creates a new thread for each row of the table. So I don't know how many threads I need. I have this so far:con = DriverManager.getConnection(url, user, passwd); pst = con.prepareStatement("select hostname, ipadress, vn...
- copy the boost.python object
I have some boost python classes, which I instantiate in python. I want to copy them. So, if I havep = Bernoulli(0.5)I want to doq = Bernoulli(p)But, what if I don't know the type of p? I tried to do this:q = copy.deepcopy(p)But python says it can't pickle p.Is my only solution to add a clone() func...
- java--Regular check
java--regular check// boolearn matches(String regex): Determine whether the current string matches the specified regular expression true/false demo: String qq ="12345"; boolearn flag = qq.matches("[1-9][0-9]{ 4,14}"); // true (judge whether qq is 5~15 digits, and the first letter cannot be zero)...
- php-How to solve: UPLOAD_ERR_CANT_write Value: 7, Cannot write file to disk
I have a PHP uploader as follows Send this file: In jsonlog.php:if($_FILES['file']['error']>0){ echo"Reading Error:". $_FILES['file']["error"] ."";}else{ code to process}It passes to my localhost, but when I try to use the linux server, it always gives me the error:UPLOAD_ERR_CANT_write value: 7,...
- python list exercises
1. Write the code, with the following list, implement each function as requiredli = ["alex","WuSir","ritian","barry","wenzhou"] Calculate the length of the list and output the additional element"seven"in the output list, and output the added list, please be the first in the list Insert the element"T...
- RSA encryption algorithm in Java: No BigIntegers
I need to implement the RSA algorithm in Java. I found the best solution using BigIntegers, the problem is that I only need to use int or long. Encryption is done like this: M [i] ^ e mod n where M [i] is Enter the character, e is the key value. I tried to use the ASCII code of the character, and us...
- javascript-Enable the tabs one by one in the form submission
There are 4 tabs and there are 4 forms in these 4 tabs, I want to write a jQuery program so that if I submit Form1 in tab1, tab2 containing the form should be enabled, and when I submit form2, it should be Enable tab3 containing form 3 until I reach form 4.I wrote the code, but it enabled all tabs, ...
- java-the best way to use random key to get child node data in firebase?
This is a one-to-many relationship: the author has many booksauthors: randomAuthorId1: authorId: authorName: randomAuthorId2: authorID: authorName:books: randomAuthorId1: randomBookId1: bookId: bookName: randomBookId2: bookId: bookName: randomAuthorId2: randomBookId3: bookId: bookName:In my case, I ...