Write a Python Function - Interview Practice - Code Conversation

Real Python · Intermediate ·🏗️ Systems Design & Architecture ·4y ago

Key Takeaways

This video demonstrates how to write a Python function to double each character in a string, covering topics such as systems design, code reusability, and testing, using tools like Python 3 and the if __name__ == '__main__': statement.

Full Transcript

welcome to real python code conversations i'm phillip and today i will challenge my teammate martin with a coding challenge i want him to create a function that accepts a string and the function should return a string with each character in the original string doubled so if the function takes the word martin i want the function to return m-m-a-a-r-r-t-t-i-i-n-n while martin tries to solve this coding challenge you will learn a few things along the way you will learn how to tackle a coding challenge why functions are a good idea how to communicate your thoughts in a coding interview what happens when you import a module and when you should use if thunder name equals dundermane in addition to solving the coding challenge martin will even go a few steps further and create some tests he will also show which conventions about tests exist and what test driven development is real python code conversations is an unfiltered video course format martin and i will have a conversation about the code he writes the session was recorded in one go but i will jump in now and then to explain some things alright let's get started in this part you will see how martin tickles the coding challenge how he sorts his thoughts and how he writes the first lines of code welcome everyone to another real python code conversation my name is philip i'm one of the core content creators at real python and joining me today is martin hi martin hi philip i've got a code challenge for you i send it over to you beforehand so you could have a look at it and the idea of this session is that you solve this little code challenge and i ask you questions and you walk me through the code and hopefully our viewers learn a little bit about one thing or another pro the question i was having for you the code challenge is create a function that accepts a string the function should return a string with each character in the original string string doubled so for example if you put in martin then it should return m-m-a-a-r-r-t-t-i-i-n-n got it so your first thoughts about this challenge like i said you already got it beforehand but once you got it was there anything about this challenge unclear or what were your first thoughts when you when you saw it so first thoughts i guess always when i get a challenge i have a short moment of being like am i going to be able to do this but this one is it's relatively straightforward and then usually when i sit down to just piece it apart you know and stuff goes relatively easily so this was my first thought maybe that's also interesting to know that even if you've been coding for a bit sometimes there's a moment of just being like confused about a question but i think it's relatively clear you wrote it out quite clearly and the instructions that i just reformatted so they fit nicely on my screen here just give me a chance to basically go step by step here and we also have an example there so this is nice to see that i also if i didn't entirely understand the instructions here i get an example that clarifies it some more yeah i think it was interesting that you just reformatted this question right i mean it's not even a question like a challenge because there is no question mark in the end the instructions right because i think just like with code in general it sometimes helps to have it formatted in a way that makes it better readable for yourself so i think now with the different lines it's kind of like three instructions how you could actually start coding like the first one is greater function that accepts a string like okay so is this how you would start now so actually i don't think i would start with a function even though it's pretty explicit in here in your instructions i would probably just see if i can get the code to work on a script basis let me try it out so what i'd start with first is i don't really know where is the input gonna come from right i assume that it should be possible to handle input from separate sources but i don't wanna deal with this at the moment so i'm just gonna make an example string that i'm gonna use for developing the code here and let's stick with this one so we can also compare so i have this example string and then i would just continue on a script basis i want a loop here because i want to see each character in the original string so i'm probably going to need a loop right so for character in example string or let's call it word and it's a little more reusable later for character in word so i'm going to loop over each of those characters and then i want just to double up each of them now i need to save this somewhere so i'm going to make a new variable here that's i'm going to call double and it just starts off as an empty string and then in here in my for loop i want to then address this and fill up the variable and so maybe that's interesting to see right you know you don't necessarily write the first line and you write the second line then you write the third line but i'm kind of following my thought process here with okay i need some input and then i'm like okay i gotta do some looping so i start with the for loop this is not even a valid for loop right now right because i have an error sitting down here because i don't do anything with it didn't do anything in there right so nicer would be to write pass as a placeholder then you also see that vs code isn't complaining that there's an error in there but then at this point i was like okay i'm gonna need a place to hold the new string that i'm creating because strings are immutable so i can change the original string i'm going to need a new one and i need that one before i start doing anything in the for loop because otherwise i would just keep overriding the value yeah that's that's true okay and i'm going to just back back up a little bit like you created a new python file double dot pi and that's where i posted the instructions and that where you're in right now so basically the code that you're having right now you would just run the file and see like if it works if there are errors in this state i'd open up my terminal and then i can say python so i'm in this i'm in the folder where i created the file i have double dot py in this folder and now i can say python three double dot py and then it runs it doesn't bring any errors now because because i added the pass statement if i if it didn't then we'd end this with an error with a syntax error yeah i think this is sometimes at the beginning a very good sign if a file does nothing so sometimes at the beginning there there is an error thrown because there is a variable you're using that is undefined or you're importing maybe an external package that is not installed yet but like you just did just running the file and not getting anything back is a good sign at the beginning right and i could do something like put a placeholder print in here or print each character while i'm iterating over it so then looking at the output is a little more interesting because then you actually see that the loop is working and it's addressing each character separately martin now is in the middle of solving the coding challenge but before we continue let's recap a little bit how he tackled the coding challenge he started by sorting his thoughts and communicated how he understands the challenge that's very vital because if you're in a coding interview for example it's very good that you're on the same page like the interviewer so if you misunderstand the question the coding interviewer can clarify a few things for you you may ask questions if it wasn't clear in this case martin understood the coding challenge completely right and he started coding that's also a good thing to not think about it too much but just get your feet wet and start coding and also be okay with not being perfect right away it's better to start a little bit of code and get started instead of thinking of the perfect solution and trying to get there but take one step after another so far martin encoded everything plainly in the file in the next part he will use functions to structure the code and he will also explain why functions are a good idea in the last part martin started the coding challenge and he wrote everything plainly in the file in this part he will use functions to structure the code and also explain why functions are a good idea okay i don't want to print the character what i want to do is double each of them so i already have access to each of the characters as we just saw in the print statement so now i can just add to this like overwrite it and i want the character double so i'm just gonna multiply by two this is something you can do and sometimes it also helps if you just jump into a little experimental session and figure out for example can i do something like that in python yep that seems to work i can just use the multiplication operator on a string and then i get the string doubled yeah so i like to have the terminal also close by where i can just run quick experiments basically it's a little bit like like a sketch pad where you are trying out an idea and see if it actually works so right now you're you're still having uh i was just pointing like you're still having the pass but you don't need to pass anymore there because okay so that should be it really i just need to make sure that we also see the value at the end so i'm going to print it out and now if i run this wpy i get the word the original word that was input and everything doubled up looks good perfect looks just like what you wanted me to write here that's yeah so we are almost done but right not yet yeah so what we're missing so right now you're just like plainly writing it out from top to bottom in a file what's the advantage of actually putting this in a function now like couldn't we just leave it like this uh yeah it's just not it's not very reusable so in this case first of all you know like the word is hard coded in this file so if you wanted a different word you'd have to go in here and change it for example and oh that's gonna be fun let's look at it with this double key at the end look at that that's nice okay i should change my name to this the screen name much more interesting than mine doubled okay we'll stick with philip so i'd have to go into the file and change this and i can't really reuse this anywhere else and also i can't really write any tests for this easily you know if you package your code up into functions it makes it much more reusable for different things for testing but also for using it in other files so yeah definitely a good suggestion here create a function that accepts a string yeah so i could rework this let's do it oops it's just my hands wrong and the keyboard okay yeah i really like your explanation because an instruction like this could also be part of an oven encoding interview and your short answer could have been like well actually it's in the instructions so that's why i'm creating a function but usually there is a why behind something why it might make sense to to do something and not just follow instructions blindly but also knowing why it might make sense in the long run yeah if you're in a good interview situation then your interviewer is gonna actually value if you explain your thought process of building something yeah because that's often much more valuable that you have someone who actually can communicate what they're doing and why they're doing it in a certain way for a work environment that's super helpful absolutely okay so i'm gonna i'm writing this function i'm gonna call it double characters and it takes a word as input and then essentially i can just indent this you know the word it's already the variable i've been using so this is going to be the attribute that's passed in here and then used down there and then instead of printing it i want to return here so that it's actually reusable that there's an output to this function that's really good and now i would write this if this magic if done domain and under name so i've i've seen this plenty of times what does it do why is it recommended to to add like this if thunder name equals thunder main when you want to run a file so if i don't have this all right and i would run this file now obviously i'm not calling the function so nothing's going to happen but if you'd be importing this file somewhere else one possibility would be right i put a function call here i say pass in the word right now if you run the file oops still not printing it now if you run the file yeah because so far you were just returning it but there wasn't a print statement to actually show it correct yeah print print function here because i removed the print function here i had to add it down there to actually get out put back to the console yeah so i could do this right but now if i want to reuse this function in a different module for example and that's reusability with functions is a big thing yeah so maybe i don't know you you write this other script and you want to use the double characters function that you have defined in this script so you go over and you say from double import double characters and if you had this now let's actually try it out right so let's make a new file in here before we let martin try out importing the code into another file let's quickly recap what happened so far martin basically solved the challenge he created a function that takes a string and returns a string with double the characters the most important line here is the one in the for loop there he adds the duplicated character where he is in the word right now to the double string so with every iteration of the loop one character gets duplicated and added to the string which is then in the end returned from the function martin also already said why he thinks a function is a good idea by using a function his code is easier to maintain functions are reusable and there are less side effects during import and that's what he's about to show now in this part martin will show you what happens when you import a module he will also explain the thunder name equals nunder main statement that you already briefly saw in the last part and he will also mention tests a little bit although he won't go into detail in this part we will get to this in one of the next ones for now it's mostly about what happens when you import a module so let's make a new file in here i'll call it well that can be the test file right i can write some tests for this as well yeah you were mentioning tests when you were thinking of putting it into a function you were mentioning it's it would be easier to test so that's actually a good all right good step so now you're creating a new file and now you want to import the double characters function from double now we're still showing about the standard main why it's helpful so if i say from double import double characters it's the function and then i'm just thinking i want to call it here i'm going to say double characters and pass in 3 or something okay and now if i go ahead and run this you might expect that you get the three doubled printed out and you will but there's also an additional thing you can pause for a second and think about what's gonna happen so if i run this i get both philips name and then the input that i actually put in here printed out and the reason is just because i have this print statement in this file and what python does when you import a module is it executes script because it needs to define the functions in there and it assigns philip to word it also executes this call to print yeah and if you'd be wanting to use double characters to function in any other script you obviously don't want it to print philips name always unless i don't know if you're in fact not for everybody involved so you don't want that but at the same time you still want to be able maybe to test the file itself to just take a look whether it's working and one thing that is often done in python scripts is that you use this make use of the namespace which when you run a script then it runs in this namespace called main and that means that when you run the script directly but not import it then this if statement is gonna be true and then the print will happen and if you import it then it won't because then it's running in the namespace of the file so it's gonna the namespace is gonna be double and here the namespace is going to be main if you run it directly so i would move this in here as well because we don't need to define this word either and now if i run test double i'm only going to get the tree but at the same time if i run the file directly i get this if statement is true and then the indented code here executes i mean the point of this is just that you can still see some output from running the script directly but it doesn't interfere with the possibility for you to import the code somewhere else yeah that was a really nice explanation in that regard that basically you with using thunder name equals dunder main and thunder is like a shorthand term for double underscore right here you can import the file without running to code but if you actually want to run the code of the script then everything that's inside of this if statement is executed when you run the file so basically you now have this double dot pi file which is good for importing but also good for running on its own cool so let's write some tests as you saw the iftander name equals under main statement is really handy the special variable under name has the valued under name inside scripts but it gets the name of the module inside imported modules by using this pattern in a python file you create code that serves two purposes that are isolated from each other it's executable as a script and it's importable as a module to show this behavior martin also created a file with a test prefix in the next part he will follow up with this naming and create some tests

Original Description

Whether you’re looking to ace your coding interview or simply to level up your development skills, solving coding challenges can help you grow as a programmer. In this Real Python Code Conversation, Philipp Ascany challenges Martin Bruess to write a function that doubles each character in a string. This is a portion of the complete course, which you can find here: https://realpython.com/courses/interview-practice-python-function/ The rest of the course covers: - Writing tests - Test Driven Development - Additional Interview Practice Feedback
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Real Python · Real Python · 0 of 60

← Previous Next →
1 A better Python REPL – bpython vs python interpreter
A better Python REPL – bpython vs python interpreter
Real Python
2 Introducing large-type.com – A Utility Website
Introducing large-type.com – A Utility Website
Real Python
3 Reading Hacker News Without Wasting Tons of Time
Reading Hacker News Without Wasting Tons of Time
Real Python
4 Forward References and Python 3 Type Hints
Forward References and Python 3 Type Hints
Real Python
5 Using Sublime Text as your Git Editor
Using Sublime Text as your Git Editor
Real Python
6 Python Code Linting and Auto-Complete for Sublime Text
Python Code Linting and Auto-Complete for Sublime Text
Real Python
7 Make your Python Code More Readable with Custom Exceptions
Make your Python Code More Readable with Custom Exceptions
Real Python
8 Write Better Tests with Sublime Text's Split Layout Feature
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
9 How to Use Sublime Text from the Command Line
How to Use Sublime Text from the Command Line
Real Python
10 Rename Variables with Multiple Selection in Sublime Text
Rename Variables with Multiple Selection in Sublime Text
Real Python
11 Sublime Text Settings for Writing PEP 8 Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
12 Write Cleaner Python with Sublime Text's Indent Guides
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
13 Sublime Text Whitespace Settings for Python Development
Sublime Text Whitespace Settings for Python Development
Real Python
14 Function Argument Unpacking in Python
Function Argument Unpacking in Python
Real Python
15 Python Code Review: Debugging and Refactoring "Conway's Game of Life" +  Automated Tests
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
16 Using "get()" to Return a Default Value from a Python Dict
Using "get()" to Return a Default Value from a Python Dict
Real Python
17 A Python Shorthand for Swapping Two Variables
A Python Shorthand for Swapping Two Variables
Real Python
18 Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
19 Click & Jump to Test Failures from the Command Line (iTerm2)
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
20 Setting up Sublime Text for Python Developers
Setting up Sublime Text for Python Developers
Real Python
21 Sublime Text + Python Guide Overview
Sublime Text + Python Guide Overview
Real Python
22 Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
23 Type-Checking Python Programs With Type Hints and mypy
Type-Checking Python Programs With Type Hints and mypy
Real Python
24 A Shorthand for Merging Dictionaries in Python 3.5+
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
25 Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
26 My Python Code Looks Ugly and Confusing – Help!
My Python Code Looks Ugly and Confusing – Help!
Real Python
27 Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
28 Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
29 Programmer Portfolio – Example and Walkthrough
Programmer Portfolio – Example and Walkthrough
Real Python
30 How to Get Your 1st Speaking Gig at a Tech Conference
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
31 How to Build Your Public Speaking Skills as a Developer
How to Build Your Public Speaking Skills as a Developer
Real Python
32 The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
33 Setting up Sublime Text for Python Developers – Lesson #1
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
34 Cool New Features in Python 3.6
Cool New Features in Python 3.6
Real Python
35 "is" vs "==" in Python – What's the Difference? (And When to Use Each)
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
36 Emulating switch/case Statements in Python with Dictionaries
Emulating switch/case Statements in Python with Dictionaries
Real Python
37 Python Function Argument Unpacking Tutorial (* and ** Operators)
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
38 What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
39 A Crazy Python Dictionary Expression ?!
A Crazy Python Dictionary Expression ?!
Real Python
40 String Conversion in Python: When to Use __repr__ vs __str__
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
41 Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
42 Optional Arguments in Python With *args and **kwargs
Optional Arguments in Python With *args and **kwargs
Real Python
43 Python Context Managers and the "with" Statement (__enter__ & __exit__)
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
44 Installing Python Packages with pip and virtualenv / venv
Installing Python Packages with pip and virtualenv / venv
Real Python
45 "For Each" Loops in Python with enumerate() and range()
"For Each" Loops in Python with enumerate() and range()
Real Python
46 Python Code Review: LibreOffice Automation and the Python Standard Library
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
47 Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
48 Python Tutorial: List Comprehensions Step-By-Step
Python Tutorial: List Comprehensions Step-By-Step
Real Python
49 Leveraging Python's Implicit "return None" Statements
Leveraging Python's Implicit "return None" Statements
Real Python
50 What's the meaning of underscores (_ & __) in Python variable names?
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
51 Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
52 Writing automated tests for Python command-line apps and scripts
Writing automated tests for Python command-line apps and scripts
Real Python
53 How to find great Python packages on PyPI, the Python Package Repository
How to find great Python packages on PyPI, the Python Package Repository
Real Python
54 Immutable vs Mutable Objects in Python
Immutable vs Mutable Objects in Python
Real Python
55 PyPI vs Warehouse, the Next-Generation Python Package Repository
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
56 pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
57 My Experience at PyCon 2017 in Portland
My Experience at PyCon 2017 in Portland
Real Python
58 Pylint Tutorial – How to Write Clean Python
Pylint Tutorial – How to Write Clean Python
Real Python
59 "Reverse a List in Python" Tutorial: Three Methods & How-to Demos
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
60 Python Refactoring: "while True" Infinite Loops & The "input" Function
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python

This video teaches how to write a Python function to double each character in a string, covering systems design, code reusability, and testing. It demonstrates how to create a function, use a loop to duplicate characters, and test the function using the if __name__ == '__main__': statement.

Key Takeaways
  1. Start with a script basis instead of a function
  2. Create a loop to iterate over each character in the original string
  3. Save the doubled string in a new variable
  4. Add a placeholder pass statement to avoid syntax errors
  5. Create a function that accepts a string to make the code reusable and testable
  6. Use a for loop to duplicate each character in the word and add it to the double_string
  7. Return the double_string from the function
  8. Use the if __name__ == '__main__': statement to run a file as a script
  9. Import a module and use a function from it
  10. Create a new file for testing the double characters function
💡 Using functions and the if __name__ == '__main__': statement can make code more reusable and maintainable.

Related Reads

📰
FULL STACK Developer
Learn the basics of full stack development and its importance in the tech industry
Dev.to · Parthipan M
📰
Workflow Series (10): Enterprise Architecture — Registry, Composition, and Governance
Learn to manage multiple workflows with enterprise architecture principles, including registry, composition, and governance, to scale your workflow systems efficiently
Dev.to · WonderLab
📰
I Said “Just Add More Servers” in a System Design Interview. That Was the Wrong Answer.
Learn why simply adding more servers is not a viable solution to scaling issues and how to identify bottlenecks in system design
Medium · Programming
📰
I Said “Just Add More Servers” in a System Design Interview. That Was the Wrong Answer.
Learn why simply adding more servers is not a viable solution to scaling issues and how to identify bottlenecks in system design
Medium · DevOps
Up next
How to Forward Device Data Via HTTP/MQTT/Modbus/BACnet in EG71
Milesight IoT
Watch →