Python: Difference between revisions
From Cheatsheet
Jump to navigationJump to search
| (37 intermediate revisions by the same user not shown) | |||
| Line 1: | Line 1: | ||
[[Category:Cheatsheet|Cheatsheets]] | |||
== Applications & Webpages == | |||
* Python IDLE | |||
* Pycharm | |||
* Intellij Idea | |||
* https://peps.python.org/pep-0008/ | |||
* https://automatetheboringstuff.com/2e/ | |||
* https://www.w3schools.com/python/default.asp | |||
== Basic Syntax == | == Basic Syntax == | ||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
# Leave a comment by prepending a "#" to your | # Leave a comment by prepending a "#" to your command | ||
# Print "Hello World" | # Print "Hello World" | ||
| Line 7: | Line 19: | ||
Hello World! | Hello World! | ||
# Add | # Echo 3 strings | ||
>>> | >>> "Hello" + " " + "World" | ||
'Hello World' | |||
# Add a newline to a value | |||
>>> print("Hello World!\n") | |||
Hello World! | |||
# Escape an escape character | |||
>>> print("Hello World\\n") | |||
Hello World\n | |||
# Single apostrophe is usable inside double-quotes | |||
>>> "Hello 'orld" | |||
"Hello 'orld" | |||
# Escape a double apostrophe | |||
>>> "Hello \"World" | |||
'Hello "World' | |||
</syntaxhighlight> | |||
=== Value types === | |||
<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") | |||
<class 'str'> | |||
>>> type(False) | |||
<class 'bool'> | |||
>>> mytuple = ("pizza", "pancake") | |||
>>> type(mytuple) | |||
<class 'tuple'> | |||
# Set a value as a specific value-type | |||
>>> int(4.0) | |||
4 | |||
>>> float(2) | |||
2.0 | |||
</syntaxhighlight> | |||
=== Basic math === | |||
<syntaxhighlight lang="python"> | |||
# Add values together | |||
>>> 2 + 3 | |||
5 | |||
# Two to the power of 3 | # Two to the power of 3 | ||
| Line 21: | Line 77: | ||
8 | 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 | |||
# Display the lowest or highest value of a set values | |||
>>> min(5, 1, 8) | |||
1 | |||
>>> max(5, 1, 8) | |||
8 | |||
</syntaxhighlight> | |||
=== Variables === | |||
<syntaxhighlight lang="python"> | |||
# Define a variable | # Define a variable | ||
>>> a = 3 | >>> a = 3 | ||
# Display the contents of a variable | # Display the contents of a variable | ||
>>> a = 3 | |||
>>> a | >>> a | ||
3 | 3 | ||
# | # Swap the contents of 2 variables | ||
>>> | >>> b, c = c, b | ||
>>> | # Create a list | ||
2 | >>> d = [5, "Bami", 3] | ||
# Fetch the second entry from a list | |||
>>> d[1] | |||
'Bami' | |||
# Modify the value of a list entry | |||
>>> d[2] | |||
3 | |||
>>> d[2] = 7 | |||
>>> d[2] | |||
7 | |||
# Create a Tuple (immutable list) | |||
>>> e = (5, "Bami", 3) | |||
# Fetch the second entry of a Tuple | |||
>>> e[1] | |||
'Bami' | |||
# Display a specific character of a variable | |||
>>> s = "Apple" | |||
>>> s[0] | |||
'A' | |||
>>> s[-1] | |||
'e' | |||
</syntaxhighlight> | |||
=== Operators === | |||
==== Comparison ==== | |||
<pre> | |||
<= = Smaller than or equal | |||
>= = Bigger than or equal | |||
< = Smaller than | |||
> = Bigger than | |||
== = Equal | |||
!= = Is not equal | |||
and = Is True if 2 given values is True | |||
or = Is True if either of 2 given values is True | |||
not = Turns False into True, or True into False | |||
</pre> | |||
==== Boolean ==== | |||
<syntaxhighlight lang="python"> | |||
# True and False | |||
>>> True - False | >>> True - False | ||
1 | 1 | ||
| Line 53: | Line 175: | ||
1 | 1 | ||
>>> | # Comparisons | ||
< | >>> 2 < 3 | ||
True | |||
>>> 2 > 3 | |||
False | |||
>>> 2 == 3 | |||
False | |||
>>> 2 != 3 | |||
True | |||
</syntaxhighlight> | |||
# | == Common blocks == | ||
=== if === | |||
<syntaxhighlight lang="python"> | |||
# If block and expression | |||
if ( n % 2 == 1 ): | |||
print("Weird") | |||
# | # if and elif blocks with expressions | ||
> | if ( n % 2 == 1 ): | ||
print("Weird") | |||
elif ( n >= 3 and n <= 5 and n % 2 == 0): | |||
print("Not Weird") | |||
</syntaxhighlight> | |||
=== for === | |||
<syntaxhighlight lang="python"> | |||
# Basic for loop printing each character separately | |||
for char in name: | |||
print(char) | |||
# | # For loop that checks for "top" inside words and lists the words | ||
for word in ('stop', 'desktop', 'post', 'top'): | |||
' | if 'top' in word: | ||
print(word) | |||
print('Done.') | |||
# | # Output list entries using a for loop | ||
names = ["Alex", "Alice", "Baba", "Bertha"] | |||
a_list = [name for name in names if name[0] == "A"] | |||
print(a_list) | |||
</syntaxhighlight> | </syntaxhighlight> | ||
== | === range === | ||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
# Print digits 0 through 3 using the range function | |||
for number in range(3): | |||
print(number) | |||
# Print digits 0 through 3 but don't output on a newline | |||
for number in range(3): | |||
print(number, end=" ") | |||
# Print digit for every 2 numbers between 0 and 11, starting from 0 | |||
for number in range(0, 11, 2): | |||
print(number, end=" ") | |||
</syntaxhighlight> | </syntaxhighlight> | ||
=== try === | |||
<syntaxhighlight lang="python"> | |||
# The following takes 2 user-inputs, adds their values together and outputs it and prints that the block is finished. | |||
try: | |||
INPUTONE = int(input()) | |||
INPUTTWO = int(input()) | |||
except ValueError: | |||
print("Invalid input. Please enter an integer.") | |||
else: | |||
print(INPUTONE + INPUTTWO) | |||
finally: | |||
print("Finished") | |||
</syntaxhighlight> | |||
== | === function === | ||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
# Define a basic function, printing a message | |||
def greeting(): | |||
print('Hello mortal') | |||
greeting() | |||
# Define a function using a variable input | |||
name = input("What is your name?") | |||
def hello(var): | |||
print('Hello ' + var) | |||
hello(name) | |||
# Same as above but prettier and more chaotic | |||
def hello(var): | |||
greeting = "Hello " + var | |||
return greeting | |||
print(str(hello(input("What is your name?")))) | |||
</syntaxhighlight> | |||
== Basics == | |||
If you're going to work with pip packages on Linux, always create a venv. | |||
<syntaxhighlight lang="bash"> | |||
# Create a venv in folder .venv/ | |||
python3 -m venv .venv/ | |||
# Activate your virtual environment | |||
source .venv/bin/activate | |||
# You can list active pip packages with pip list | |||
pip list | |||
# Deactivate your virtual environment | |||
deactivate | |||
</syntaxhighlight> | </syntaxhighlight> | ||
Latest revision as of 08:21, 11 July 2025
Applications & Webpages
- Python IDLE
- Pycharm
- Intellij Idea
- https://peps.python.org/pep-0008/
- https://automatetheboringstuff.com/2e/
- https://www.w3schools.com/python/default.asp
Basic Syntax
# Leave a comment by prepending a "#" to your command
# Print "Hello World"
>>> print("Hello World!")
Hello World!
# Echo 3 strings
>>> "Hello" + " " + "World"
'Hello World'
# Add a newline to a value
>>> print("Hello World!\n")
Hello World!
# Escape an escape character
>>> print("Hello World\\n")
Hello World\n
# Single apostrophe is usable inside double-quotes
>>> "Hello 'orld"
"Hello 'orld"
# Escape a double apostrophe
>>> "Hello \"World"
'Hello "World'
Value types
# 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'>
>>> mytuple = ("pizza", "pancake")
>>> type(mytuple)
<class 'tuple'>
# Set a value as a specific value-type
>>> int(4.0)
4
>>> float(2)
2.0
Basic math
# 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 # Display the lowest or highest value of a set values >>> min(5, 1, 8) 1 >>> max(5, 1, 8) 8
Variables
# Define a variable >>> a = 3 # Display the contents of a variable >>> a = 3 >>> a 3 # Swap the contents of 2 variables >>> b, c = c, b # Create a list >>> d = [5, "Bami", 3] # Fetch the second entry from a list >>> d[1] 'Bami' # Modify the value of a list entry >>> d[2] 3 >>> d[2] = 7 >>> d[2] 7 # Create a Tuple (immutable list) >>> e = (5, "Bami", 3) # Fetch the second entry of a Tuple >>> e[1] 'Bami' # Display a specific character of a variable >>> s = "Apple" >>> s[0] 'A' >>> s[-1] 'e'
Operators
Comparison
<= = Smaller than or equal >= = Bigger than or equal < = Smaller than > = Bigger than == = Equal != = Is not equal and = Is True if 2 given values is True or = Is True if either of 2 given values is True not = Turns False into True, or True into False
Boolean
# 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
Common blocks
if
# If block and expression
if ( n % 2 == 1 ):
print("Weird")
# if and elif blocks with expressions
if ( n % 2 == 1 ):
print("Weird")
elif ( n >= 3 and n <= 5 and n % 2 == 0):
print("Not Weird")
for
# Basic for loop printing each character separately
for char in name:
print(char)
# For loop that checks for "top" inside words and lists the words
for word in ('stop', 'desktop', 'post', 'top'):
if 'top' in word:
print(word)
print('Done.')
# Output list entries using a for loop
names = ["Alex", "Alice", "Baba", "Bertha"]
a_list = [name for name in names if name[0] == "A"]
print(a_list)
range
# Print digits 0 through 3 using the range function
for number in range(3):
print(number)
# Print digits 0 through 3 but don't output on a newline
for number in range(3):
print(number, end=" ")
# Print digit for every 2 numbers between 0 and 11, starting from 0
for number in range(0, 11, 2):
print(number, end=" ")
try
# The following takes 2 user-inputs, adds their values together and outputs it and prints that the block is finished.
try:
INPUTONE = int(input())
INPUTTWO = int(input())
except ValueError:
print("Invalid input. Please enter an integer.")
else:
print(INPUTONE + INPUTTWO)
finally:
print("Finished")
function
# Define a basic function, printing a message
def greeting():
print('Hello mortal')
greeting()
# Define a function using a variable input
name = input("What is your name?")
def hello(var):
print('Hello ' + var)
hello(name)
# Same as above but prettier and more chaotic
def hello(var):
greeting = "Hello " + var
return greeting
print(str(hello(input("What is your name?"))))
Basics
If you're going to work with pip packages on Linux, always create a venv.
# Create a venv in folder .venv/ python3 -m venv .venv/ # Activate your virtual environment source .venv/bin/activate # You can list active pip packages with pip list pip list # Deactivate your virtual environment deactivate