Python: Difference between revisions

From Cheatsheet
Jump to navigationJump to search
Line 14: Line 14:
</syntaxhighlight>
</syntaxhighlight>


=== Basic math ===
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
# Find out the type of a value
# Find out the type of a value
>>> type (1 + 2)
>>> type (1 + 2)
<class 'int'>
<class 'int'>
>>> type (4 / 2)
>>> type (4 / 2)
<class 'float'>
<class 'float'>
>>> type("hello")
>>> type("hello")
<class 'str'>
<class 'str'>
>>> type(False)
<class 'bool'>


# Add values together
# Add values together
Line 85: Line 91:
</syntaxhighlight>
</syntaxhighlight>


=== True and False
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
# True and False
>>> True - False
>>> True - False
1
1
Line 101: Line 109:
1
1


>>> type(False)
# Comparisons
<class 'bool'>
>>> 2 < 3
True
 
>>> 2 > 3
False
 
>>> 2 == 3
False
 
>>> 2 != 3
True
</syntaxhighlight>
</syntaxhighlight>



Revision as of 11:45, 7 February 2024

Applications

  • Python IDLE
  • Pycharm
  • Intellij Idea


Basic Syntax

# Leave a comment by prepending a "#" to your line

# Print "Hello World"
>>> print("Hello World!")
Hello World!

Basic math

# Find out the type of a value
>>> type (1 + 2)
<class 'int'>

>>> type (4 / 2)
<class 'float'>

>>> type("hello")
<class 'str'>

>>> type(False)
<class 'bool'>

# Add values together
>>> 2 + 3
5

# Two to the power of 3
>>> 2 ** 3
8

# Divide whole numbers
>>> 9 / 2
4.5

# Divide whole number but print the number on the left side of the comma
>>> 9 // 2
4

# Modulo - The remainder after subtracting 2 as many times as you can
>>> 9 % 2
1
# Echo 3 strings
>>> "Hello" + " " + "World"
'Hello World'

# Define a variable
>>> a = 3

# Display the contents of a variable
>>> a
3

# Set a value as a specific value-type
>>> int(4.0)
4
>>> float(2)
2.0

# Add a newline to a value
>>> print("Hello World!\n")
Hello World!

# Escape an escape character
>>> print("Hello World\\n")
Hello World\n

# Single bracket are usable inside double-quotes
>>> "Hello 'orld"
"Hello 'orld"

# Escape a double bracket
>>> "Hello \"World"
'Hello "World'

# Display the lowest or highest value of a set values
>>> min(5, 1, 8)
1
>>> max(5, 1, 8)
8

=== True and False

# True and False
>>> True - False
1

>>> False
False

>>> False + False
0

>>> int(False)
0

>>> int(False) + int(True)
1

# Comparisons
>>> 2 < 3
True

>>> 2 > 3
False

>>> 2 == 3
False

>>> 2 != 3
True

Template



Common