DEV Community

Cover image for Python Basics
Shatakshi
Shatakshi

Posted on

Python Basics

The only guide you'd need to deep dive into Python basics like lists, tuples, dictionaries, and so much more.

Variables and Data Types

when you run hello_world.py, we observe the following output:
suppose hello_world.py has:

print("Hello Python world!")
Enter fullscreen mode Exit fullscreen mode

output:
Hello Python world!

Variables

message = "Hello Python world!"
print(message)
Enter fullscreen mode Exit fullscreen mode

output:
Hello Python world!

we've added a variable named message. every variable is connected to a value which is the information associated with that variable

Naming and using Variables

  1. Variable names can contain only letters, numbers, and underscores.
    They can start with a letter or an underscore, but not with a number.

  2. Spaces are not allowed in variable names, but underscores can be used
    to separate words in variable names. For example, greeting_message works but greeting message will cause errors

  3. Avoid using Python keywords and function names as variable names.

  4. variable names should be short but descriptive

Strings

A string is a series of characters. Anything inside quotes is considered
a string in Python, and you can use single or double quotes around your
strings like this:

"This is string"
'This is string'
Enter fullscreen mode Exit fullscreen mode

double quotes are helpful with apostrophes.

changing case in Strings:

name = "john doe"
print(name.title())
Enter fullscreen mode Exit fullscreen mode

output:
John Doe

name = "John Doe"
print(name.lower())#o/p: john doe
print(name.upper())#o/p: JOHN DOE
Enter fullscreen mode Exit fullscreen mode
first_name = "john"
last_name = "doe"
full_name = f"{first_name} {last_name}"
print(full_name)#o/p: john doe
Enter fullscreen mode Exit fullscreen mode

f-strings are used to format the output.

first_name = "ada"
last_name = "lovelace"
print(f"Hello, {full_name.title()}!")
Enter fullscreen mode Exit fullscreen mode

adding whitespace or tabs:

print("\tPython")
Enter fullscreen mode Exit fullscreen mode

output:
Python

print("Languages:\nPython\nC\nJavaScript")
Enter fullscreen mode Exit fullscreen mode

output:
Languages:
Python
C
JavaScript

stripping whitespace:

useful when user might enter spaces after or before any critical information.
like "name "
use .strip() method
name.lstrip(), removes whitespace from left; name.rstrip() removes whitespace from right.
name.strip() removes space from both left and right.

Numbers

integers

uou can add (+), subtract (-), multiply (*), and divide (/) integers in Python.
2 + 3
5
3 - 2
1
2 * 3
6
3 / 2
1.5

Python uses two multiplication symbols to represent exponents:
3 ** 2
9

floats

Python calls any number with a decimal point a float.

0.1 + 0.1
0.2

mixing integers and floats

When you divide any two numbers, even if they are integers that result in a
whole number, you’ll always get a float:
4/2
2.0

Lists

A list is a collection of items in a particular order. You can make a list that
includes the letters of the alphabet, the digits from 0–9, or the names of
all the people in your family. the items in your list don't have to be related in any particular way.
in Python, square brackets([]) indicate a list, and individual elements in the list are separated by commas.

names = ['aaron', 'bob', 'candice', 'daphne']
print(names)
Enter fullscreen mode Exit fullscreen mode

op:
['aaron', 'bob', 'candice', 'daphne']

access item of a list using index or position.

print(names[0])
op: aaron

modifying elements in a list:

print(names)
names[1] = 'barb'
print(names)
Enter fullscreen mode Exit fullscreen mode

op:
['aaron', 'bob', 'candice', 'daphne']
['aaron', 'barb', 'candice', 'daphne']

add elements to a list:

names.append('elle')
print(names)

o/p:
['aaron', 'barb', 'candice', 'daphne', 'elle']

inserting elements into a list:

You can add a new element at any position in your list by using the insert() method.

names.insert(0, 'charlie')
print(names)
Enter fullscreen mode Exit fullscreen mode

o/p:
['charlie', 'aaron', 'barb', 'candice', 'daphne', 'elle']

removing an Item Using the del Statement

If you know the position of the item you want to remove from a list, you can
use the del statement.

del names[0]
print(names)
Enter fullscreen mode Exit fullscreen mode

o/p:
['aaron', 'barb', 'candice', 'daphne', 'elle']

removing an item using pop() method:

The pop() method removes the last item in a list, but it lets you work
with that item after removing it.

print(names)
popped_name = names.pop()
print(names)
print(popped_name)
Enter fullscreen mode Exit fullscreen mode

o/p:
['aaron', 'barb', 'candice', 'daphne', 'elle']
['aaron', 'barb', 'candice', 'daphne']
elle

removing an Item by Value

Sometimes you won’t know the position of the value you want to remove from a list. If you only know the value of the item you want to remove, you can use the remove() method.

names = ['aaron', 'barb', 'candice']
print(names)

names.remove('barb')
print(names)
Enter fullscreen mode Exit fullscreen mode

o/p:
['aaron', 'barb', 'candice']
['aaron', 'candice']

NOTE:
The remove() method deletes only the first occurrence of the value you specify. If there’s a possibility the value appears more than once in the list, you’ll need to use a loop to
determine if all occurrences of the value have been removed.

organizing a list

sorting a list permanently using sort() method:

cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
Enter fullscreen mode Exit fullscreen mode

o/p:
['audi', 'bmw', 'subaru', 'toyota']

cars.sort(reverse=True) sorts the list in reverse alphabetical order.

sorting a list temporarily using sorted() function:

print("Here is the original list:")
print(cars)

print("\nHere is the sorted list:")
print(sorted(cars))

print("\nHere is the original list again:")
print(cars) 
Enter fullscreen mode Exit fullscreen mode

o/p:
Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']
Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']
Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']

printing a list in reverse order:

print(cars)
cars.reverse()
print(cars)
Enter fullscreen mode Exit fullscreen mode

o/p:
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']

finding length of a list:

len(cars)#returns 4

Keep in mind that whenever you want to access the last item in a list you use the index -1. This will always work, even if your list has changed size since the last time you accessed it:
cars = ['bmw', 'audi', 'toyota', 'subaru'] &
print(cars[-1])
o/p:
'subaru'

working with lists:

Let’s say we have a list of magicians’ names, and we want to print out each name in the list. We could do this by retrieving each name from the list individually, but this approach could cause several problems.

magicians = ['alice', 'david', 'carolina'] 
for magician in magicians: 
    print(magician)
Enter fullscreen mode Exit fullscreen mode

o/p:
alice
david
carolina

when writing your own for loops you can choose any name you want for temporary variable.

for cat in cats:
for dog in dogs:
for item in list_of_items: 
Enter fullscreen mode Exit fullscreen mode

using the range function:

for value in range(1,5):
    print(value)
Enter fullscreen mode Exit fullscreen mode

o/p:
1
2
3
4

We can also use the range() function to tell Python to skip numbers in a given range. For example, here’s how we would list the even numbers between 1 and 10:

even_numbers = list(range(2,11,2)) 
print(even_numbers)
Enter fullscreen mode Exit fullscreen mode

o/p:
[2,4,6,8,10]

statistics with a list of numbers:

A few Python functions are specific to lists of numbers. For example, you
can easily find the minimum, maximum, and sum of a list of numbers:
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
min(digits)
0
max(digits)
9
sum(digits)
45

list comprehensions:

A list comprehension allows you to generate this same list in just one line of code. A list comprehension combines the for loop and the creation of new elements into one line, and automatically appends each new element.

squares = [value**2 for value in range(1,11)]
print(squares)
Enter fullscreen mode Exit fullscreen mode

o/p:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

working with part of a list:

Slicing a list:

To make a slice, you specify the index of the first and last elements you want to work with.

players = ['charles', 'martina', 'michael', 'florence', 'eli'] 
print(players[0:3])
Enter fullscreen mode Exit fullscreen mode

o/p:
['charles', 'martina', 'michael']

If you omit the first index in a slice, Python automatically starts your slice at the beginning of the list:
print(players[:4])
o/p: ['charles', 'martina', 'michael', 'florence']

print(players[2:])
o/p: ['michael', 'florence', 'eli']

copying a list:

To copy a list, you can make a slice that includes the entire original list by omitting the first index and the second index ([:]).
below creates two separate lists.

my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
Enter fullscreen mode Exit fullscreen mode

to create new list that points to same previous list and not create any new list:
friend_foods = my_foods
now any changes in my_foods will be shown in friend_foods

Tuples

sometimes you’ll want to create a list of items that cannot
change. Tuples allow you to do just that. Python refers to values that cannot change as immutable, and an immutable list is called a tuple.

A tuple looks just like a list except you use parentheses instead of square
brackets

 dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
Enter fullscreen mode Exit fullscreen mode

op:
200
50

dimensions[0] = 250 will lead to error. Python returns a Type error.

writing over a tuple

dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
    print(dimension)

dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
    print(dimension)
Enter fullscreen mode Exit fullscreen mode

op:
Original dimensions:
200
50
Modified dimensions:
400
100

if statements

The following short example shows how if tests let you respond to special situations correctly.

cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())
Enter fullscreen mode Exit fullscreen mode

op:
Audi
BMW
Subaru
Toyota

every if statement is an expression that can be evaluated as
True or False and is called a conditional test. Python uses the values True and False to decide whether the code in an if statement should be executed. If a conditional test evaluates to True, Python executes the code following the if statement. If the test evaluates to False, Python ignores the code following the if statement

requested_topping = 'mushrooms'
u if requested_topping != 'anchovies':
    print("Hold the anchovies!")
Enter fullscreen mode Exit fullscreen mode

op:
Hold the anchovies!

checking multiple conditions

type following in cmd line:
age_0 = 22
age_1 = 18
age_0 >= 21 and age_1 >= 21
False

checking if a value is in a list:

requested_toppings = ['mushrooms', 'onions', 'pineapple']
'mushrooms' in requested_toppings
True
'pepperoni' in requested_toppings
False

checking if value not in list:

banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
    print(user.title() + ", you can post a response if you wish.")
Enter fullscreen mode Exit fullscreen mode

Marie, you can post a response if you wish.

simple if statements

if conditional_test:
do something

if-else statements:

age = 17
if age >= 18:
    print("You are old enough to vote!")
    print("Have you registered to vote yet?")
else:
    print("Sorry, you are too young to vote.")
    print("Please register to vote as soon as you turn 18!")
Enter fullscreen mode Exit fullscreen mode

op:
Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!

if-elif-else chain:

age = 12
if age < 4:
    print("Your admission cost is $0.")
elif age < 18:
    print("Your admission cost is $5.")
else:
    print("Your admission cost is $10.")
Enter fullscreen mode Exit fullscreen mode

op:
Your admission cost is $5

note: you can use multiple elif blocks if required. you can also omit the else block completely.

styling your if-statements:

if age > 4 is better than if age>4. Such spacing does not affect the way Python interprets your code; it just makes your code easier for you and others to read.

Dictionaries

Python’s dictionaries, allow you to connect pieces of related information

alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
Enter fullscreen mode Exit fullscreen mode

op:
green
5

working with dictionaries:

A dictionary in Python is a collection of key-value pairs. Each key is connected to a value, and you can use a key to access the value associated with that key.
A key’s value can be a number, a string, a list, or even another dictionary.
In fact, you can use any object that you can create in Python as a value in a dictionary.

accessing values in a dictionary

alien_0 = {'color': 'green'}
print(alien_0['color'])
Enter fullscreen mode Exit fullscreen mode

op:
green

adding new key-value pair:

alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)

op:
{'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}
remember order doesn't matter in Python dictionary

modifying values in a dictionary:

alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")

op:
The alien is green.
The alien is now yellow.

removing key-value pairs:

alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)

op:
{'color': 'green', 'points': 5}
{'color': 'green'}

looping through a dictionary:

user_0 = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
    }
for key, value in user_0.items():
    print("\nKey: " + key)
    print("Value: " + value)
Enter fullscreen mode Exit fullscreen mode

method items(), which returns a list of key-value pairs.
The for loop then stores each of these pairs in the two variables provided.
Key: last
Value: fermi
Key: first
Value: enrico
Key: username
Value: efermi

looping through all keys in a dictionary:

for name in favorite_languages.keys():
    print(name.title())
Enter fullscreen mode Exit fullscreen mode

op:
Jen
Sarah
Phil
Edward

note:
Looping through the keys is actually the default behavior when looping through a dictionary, so this code would have exactly the same output if you wrote:
for name in favorite_languages:
rather than . . .
for name in favorite_languages.keys():

method favorite_languages.keys() returns list of keys

looping through dictionaries keys in order:

One way to return items in a certain order is to sort the keys as they’re returned in the for loop. You can use the sorted() function to get a copy of the keys in order:

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }
for name in sorted(favorite_languages.keys()):
    print(f"{name.title()}, thank you for taking the poll.")
Enter fullscreen mode Exit fullscreen mode

op:
Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.

looping through all values in a dictionary:

print("The following languages have been mentioned:")
for language in favorite_languages.values():
    print(language.title())
Enter fullscreen mode Exit fullscreen mode

op:
The following languages have been mentioned:
Python
C
Python
Ruby

nesting

a list of dictionaries:

alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
    print(alien)
Enter fullscreen mode Exit fullscreen mode

op:
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}

list in dictionary:

pizza = {
    'crust': 'thick',
    'toppings': ['mushrooms', 'extra cheese'],
    }
print("You ordered a " + pizza['crust'] + "-crust pizza " + "with the following toppings:")

for topping in pizza['toppings']:
    print("\t" + topping)
Enter fullscreen mode Exit fullscreen mode

op:
You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese

a dictionary in a dictionary:

users = {
    'aeinstein': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton'
    },
    'mcurie': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris',
    }
}

for username, user_info in users.items():
     print("\nUsername: " + username)
     full_name = user_info['first'] + " " + user_info['last']
     location = user_info['location']

     print("\nFull name: " + full_name.title())
     print("Location: " + location.title())
Enter fullscreen mode Exit fullscreen mode

op:
ae

mc

user input and while loops:

how the input() function works:

message = input("Tell me something, and I will repeat it back to you: ")
print(message)

op:
Tell me something, and I will repeat it back to you: Hello everyone!
Hello everyone!

using int() to accept numerical inputs


age = input("how old are you?")

op:
how old are you? 21

print(age) returns '21'. '21', the string representation of the numerical value entered.
so always convert numerical input to int.

age = int(age)
print(age) # returns 21

while loops:

The for loop takes a collection of items and executes a block of code once for each item in the collection. In contrast, the while loop runs as long as, or while, a certain condition is true.

current_number = 1
while current_number <= 5:
    print(current_number)
    current_number += 1
Enter fullscreen mode Exit fullscreen mode

op:
1
2
3
4
5

using break to exit a loop:

To exit a while loop immediately without running any remaining code in the loop, regardless of the results of any conditional test, use the break statement.

using continue in a loop:

Rather than breaking out of a loop entirely without executing the rest of its code, you can use the continue statement to return to the beginning of the loop based on the result of a conditional test.

Functions:

def greet_user():
     """Display a simple greeting."""
     print("Hello!")
greet_user()
Enter fullscreen mode Exit fullscreen mode

def to inform Python that you’re defining a function. This
is the function definition, which tells Python the name of the function and, if applicable, what kind of information the function needs to do its job. The parentheses hold that information. In this case, the name of the function is greet_user(), and it needs no information to do its job, so its parentheses are empty.

the lines that follow def greet_user() make up the body of the function. the first line is a comment called a docstring. Docstrings are enclosed in triple quotes, which Python looks for when it generates documentation for the functions in your programs.
last line is calling the function but as no arguments are needed so parentheses are empty.

passing information to a function:

args

op:
Hello, Jesse!

arguments vs parameters:

the value that we pass inside the parentheses are termed as argument. both arguments and parameter are used interchangably, even though they have different meaning.

The variable username is an example of parameter, a piece of information the function needs to do its job. the value 'jesse' is an example of argument.

Passing arguments:

Because a function definition can have multiple parameters, a function call may need multiple arguments. You can pass arguments to your functions in a number of ways. You can use positional arguments, which need to be in Functions the same order the parameters were written; keyword arguments, where each argument consists of a variable name and a value; and lists and dictionaries
of values. Let’s look at each of these in turn.

Positional arguments:

When you call a function, Python must match each argument in the function call with a parameter in the function definition.

def describe_pet(animal_type, pet_name):
    """Display information about a pet."""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('hamster', 'harry')
Enter fullscreen mode Exit fullscreen mode

op:
I have a hamster.
My hamster's name is Harry.

When we call describe_pet(), we need to provide an animal type and a name, in that order. For example, in the function call, the
argument 'hamster' is stored in the parameter animal_type and the argument 'harry' is stored in the parameter pet_name

order matters in positional arguments:

if we do describe_pet('harry', 'hamster') we would get unexpected result because now animal_type is 'harry' and pet_name is 'hamster'

keyword arguments:

A keyword argument is a name-value pair that you pass to a function. You directly associate the name and the value within the argument, so when you pass the argument to the function, there’s no confusion.

in this we'd do: describe_pet(animal_type='hamster', pet_name='harry')

the order of keyword arguments does not matter

img

NOTE: When you use keyword arguments, be sure to use the exact names of the parameters in the function’s definition.

Default values:

when writing a function, we can define default values. if an argument for a parameter is provided in the function call, python uses the argument value. if not, it uses the parameter's default value.

def describe_pet(pet_name, animal_type='dog'):
"""Display information about a pet."""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')
Enter fullscreen mode Exit fullscreen mode

Python still interprets this as a positional argument, so if
the function is called with just a pet’s name, that argument will match up with the first parameter listed in the function’s definition. This is the reason the first parameter needs to be pet_name.

NOTE: When you use default values, any parameter with a default value needs to be listed after all the parameters that don’t have default values. This allows Python to continue interpreting positional arguments correctly.

equivalent function calls:

# A dog named Willie.
describe_pet('willie')
describe_pet(pet_name='willie')
# A hamster named Harry.
describe_pet('harry', 'hamster')
describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='hamster', pet_name='harry')
Enter fullscreen mode Exit fullscreen mode

return values:

A function doesn’t always have to display its output directly. Instead, it can process some data and then return a value or set of values. The value the function returns is called a return value.

 def get_formatted_name(first_name, last_name):    
     """Return a full name, neatly formatted."""
     full_name = first_name + ' ' + last_name
     return full_name.title()

musician = get_formatted_name('jimi', 'hendrix')
print(musician)
Enter fullscreen mode Exit fullscreen mode

op:
Jimi Hendrix

passing an arbitrary number of arguments:

consider a function that builds a pizza. It needs to accept a
number of toppings, but you can’t know ahead of time how many toppings a person will want. The function in the following example has one parameter, *toppings, but this parameter collects as many arguments as the calling line provides:

def make_pizza(*toppings):
    """Print the list of toppings that have been requested."""
    print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
Enter fullscreen mode Exit fullscreen mode

op:
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')

The asterisk in the parameter name *toppings tells Python to make an empty tuple called toppings and pack whatever values it receives into this tuple.

mixing positional and arbitrary arguments:

If you want a function to accept several different kinds of arguments, the parameter that accepts an arbitrary number of arguments must be placed last in the function definition.
Python matches positional and keyword arguments first and then collects any remaining arguments in the final parameter.

example:
sample

using arbitrary keyword arguments:

The following example takes in a first and last name, but it accepts an arbitrary number of keyword arguments as well:

ex
The
double asterisks before the parameter **user_info cause Python to create an empty dictionary called user_info and pack whatever name-value pairs it receives into this dictionary.

Storing your functions in Modules:

One advantage of functions is the way they separate blocks of code from your main program.You can go a step further by
storing your functions in a separate file called a module and then importing that module into your main program. An import statement tells Python to make the code in a module available in the currently running program file.

This allows efficient use of functions.

importing an entire module:

a module is a file ending in .py that contains the code you want to import into your program. we make a module that has function make_pizza(). to make this module we'll remove everything from this file pizza.py except the function make_pizza():

pizzapy
now, we'll make a separate file called making_pizzas.py in same directory as pizza.py. This file imports the module we just created and then makes two calls to make_pizza():

ImakkingPizzas

When Python reads this file, the line import pizza tells Python to open the file pizza.py and copy all the functions from it into this program. All you need to know is that any function defined in pizza.py will now be available in making_pizzas.py.
To call a function from an imported module, enter the name of
the module you imported, pizza, followed by the name of the function, make_pizza(), separated by a dot. This code produces the same output
as the original program that didn’t import a module:

img

importing specific functions:

from pizza import make_pizza

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
Enter fullscreen mode Exit fullscreen mode

using as to give a function an Alias:

from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
Enter fullscreen mode Exit fullscreen mode

if the name of function you're importing might conflict with existing name in your program you can use short , unique alias - an alternate name similar to nickname for the function.

using as to give module an alias:

You can also provide an alias for a module name. Giving a module a short alias, like p for pizza, allows you to call the module’s functions more quickly.

import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
Enter fullscreen mode Exit fullscreen mode

importing all functions in a module:

You can tell Python to import every function in a module by using the asterisk (*) operator:

from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
Enter fullscreen mode Exit fullscreen mode

The asterisk in the import statement tells Python to copy every function from the module pizza into this program file.
However, this is not the best approach.
The best approach is to import the function or functions you want, or import the entire module and use the dot notation.

Styling functions:

You need to keep a few details in mind when you’re styling functions.

  • Functions should have descriptive names, and these names should use lowercase letters and underscores. This helps you and others understand your code better.
  • Every function should have a comment that explains concisely what the function does. This comment should appear immediately after the function definition and use the docstring format.
  • If you specify a default value for a parameter, no spaces should be used on either side of the equal sign: def function_name(parameter_0, parameter_1='default value')
  • The same convention should be used for keyword arguments in function calls: function_name(value_0, parameter_1='value')
  • If your program or module has more than one function, you can separate each by two blank lines to make it easier to see where one function ends and the next one begins.
  • All import statements should be written at the beginning of a file.

The concept remains is OOPs(Object Oriented Programming) in Python and will be shared in next blog.

Source of this article: Python Crash Course Book by Eric Matthes
if you have come this far Thank you so much! You can leave a feedback of any kind below.

Top comments (0)