Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Preventing Code Injection | Understanding Python Vulnerabilities
Python Security Best Practices

bookChallenge: Preventing Code Injection

Task

Swipe to start coding

Refactor a function that previously used eval() to perform mathematical operations based on a string input, so that it cannot be exploited for code injection. Use only a dictionary of explicitly allowed operations.

  • Only allow the operations "add", "subtract", "multiply", and "divide".
  • For each allowed operation, perform the corresponding arithmetic on a and b.
  • If an operation is not allowed, return None.
  • For division, if b is zero, return None.

Solution

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 1. ChapterΒ 5
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Suggested prompts:

Can you explain this in simpler terms?

What are some examples related to this topic?

Where can I learn more about this?

close

Awesome!

Completion rate improved to 5.56

bookChallenge: Preventing Code Injection

Swipe to show menu

Task

Swipe to start coding

Refactor a function that previously used eval() to perform mathematical operations based on a string input, so that it cannot be exploited for code injection. Use only a dictionary of explicitly allowed operations.

  • Only allow the operations "add", "subtract", "multiply", and "divide".
  • For each allowed operation, perform the corresponding arithmetic on a and b.
  • If an operation is not allowed, return None.
  • For division, if b is zero, return None.

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 1. ChapterΒ 5
single

single

some-alt