Sololearn Python for Beginners #6 Functions

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

List Slices

List slices allow you to get a part of the list using two colon-separated indices. This returns a new list containing all the values between the indices. squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print( squares [2:6]1) print(squares [3:8]) print (squares [0 :1]) Result: >>> [4, 9, 16, 25] [9, 16, 25, 36, 49] [0] >>> Just like the arguments to range, the first index provided in a slice is included in the result, but the second isn't.

List Functions

Python has a bunch of useful built-in functions for lists. len() lets you get the number of items in a list. Like this: nums 1, 3, 5, 2, 4] print(len( nums) ) Unlike indexing items, len does not start with 0. The list above contains 5 items, meaning len will return 5.

String Formatting

Strings have a format() function, which enables values to be embedded in it, using placeholders. Example: nums [4, 5, 6] msg "Numbers : {0} {1} {2}". format (nums [0], nums [ 1], nums[2]) print (msg) Each argument of the format function is placed in the string at the corresponding position, which is determined using the curly braces { }.

What is the output of this code? x = [2, 4, 5, 7, 4] y = x.index(4) print(y)

1

What do you think is the output of this code: def calc(x, y): return [x+y, x*y] res = calc(3, 4) print(res[1])

12

What's the highest number this function prints if called? def print_numbers(): print(1) print(2) return print(4) print(6)

2

How many arguments are in this function call? range(0, 100, 5)

3

Guess the output of this code: list = [8, 4, 2, 6] list.remove(2) print(len(list)+list.count(6))

4

How many lines will the following code output? def foo(): print(1) print(2) foo() foo() 0

4

What is the result of this code? letters = ["a", "b", "c"] letters += ["d"] print(len(letters))

4

What is the output of this code? nums = [1, 2, 3, 4, 5, 6] res = nums[::-1] print(res[2])

4 Sololearn Python for Beginners #6 functions Functions`A function is a group of related statements that performs a specific task. Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable. Furthermore, it avoids repetition and makes the code reusable.

How many elements will the following slice produce? sq = [0, 1, 4, 9, 16, 25, 36, 49, 64] print(sq[4:])

5

Can you determine the output of this code: nums = [1, 3, 5, 2, 4] res = min(nums) + max(nums) print(res)

6

What is the output of this code? x ="abc" x *= 2 print(len(x))

6

What's the result of this code? def print_double(x): print(2 * x) print_double(3)

6

Guess the output of this code: def foo(x, y): if x >= y: return x else: return y x = foo(4, 7) print(x) 11

7

Guess the output of this code: def x(y): print(y+2) x(5)

7

What is the output of this code: x = 5 #x += 1 x += 2 #increment print(x)

7

What is the result of this code? nums = [9, 8, 7, 6, 5] nums.append(4) nums.insert(2, 11) print(len(nums))

7

What's the result of this code? str="{c}, {b}, {a}".format(a=5, b=9, c=7) print(str)

7, 9, 5

Returning from Functions

Certain functions, such as int or str, return a value instead of outputting it. The returned value can be used later in the code, for example, by getting assigned to a variable. To do this for your defined functions, you can use the return statement. Like this: def sum(X, y): return x*y

Docstrings

Docstrings (documentation strings) are similar to comments, in that they're designed to explain code. But, they're more specific and have a different syntax. They're created by putting a multiline string containing an explanation of the function below the function's first line. Like this: `def shout(word) : Print a word with an exclamation mark following it. print(word "") shout("spam")

list.count(item): Returns a count of how many times an item occurs in a list. list.remove(item): Removes an item from a list. list.reverse(): Reverses items in a list.

F 12, 4, 6, 2, 7, 2, 9] print(x.count (2 )) X.remove (4) print(x) X.reverse() print(x)

List Functions

The append() function is used to add an item to the end of the list: nums =1, 2, 3] nums.append (4) print (nums) Note, that the function is called using the list name, followed by a dot.

A function has a name and can have arguments.

For example: print("Hello") PY Here, print is the function name and "Hello" is the argument.

Functions can have multiple arguments. For example, range(2, 20) has two arguments, 2 and 20.

Function arguments need to be separated by commas.

Arguments

Functions can take arguments, which can be used to generate the function output. For example: def exclamation (word): print (word "") exclamation ( "spam") As you can see from the example, the argument is defined inside the parentheses and is named word.

Docstrings act as documentation for other developers who use your function.

Unlike conventional comments, docstrings are retained throughout the runtime of the program. This allows the programmer to inspect these comments at run time.

Comments

We're so close to the finish line! Well done for making it this far! Comments are annotations to code used to make it easier to understand. They don't affect how code is run. In Python, a comment is created by inserting an octothorpe (otherwise known as a number sign or hash symbol: #). All text after it on that line is ignored. For example: X = 365 y = 7 print(x % y) # find the remainder

You can have multiple comments in your code.

X 365 y = 7 # this is a comment print(x % y) # find the remainder # print (x II y) # another comment

max(list): Returns the maximum value. min(list): Returns the minimum value.

X = l1, 8, 42, 3] print(min(x) ) print(max(x))

replace() replaces one substring in a string with another. For example:

X ="Hello ME" print(x.replace( "ME", "world "))

List Functions

You can also use len on strings to return their length (character count). For example: str " some text" x = len(str) print(x) Remember that space is also a character.

Functions

You can create your own functions by using the def statement. Here's an example of a function named my_func. It takes no arguments, and prints "spam" three times. def my_func(): print("spam") print("spam") print("spam")

As you can see in the previous examples, arguments can be used as variables inside the function.

You can have different statements in your functions, working with the argument variables, such as if statements and loops.

What's the output of this code? sqs = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(sqs[1::4])

[1, 25, 81]

What's the result of this code? sqs = [0, 1, 4, 9, 16, 25, 36, 49, 64] print(sqs[4:7])

[16, 25, 36]

What's the output of this code? sqs = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(sqs[7:5:-1])

[49, 36]

You can also name the placeholders, instead of the index numbers.

a = "{xt, {y}".format (x=5, y=12) print(a)

We have seen the str() function in action before. What does the str() function do?

converts its argument to a string

Once you return a value from a function, it immediately stops being executed. Any code placed after the return statement won't be executed. For example:

def add_numbers (%, y): total = x * y return total print("This won't be printed ") print (add_numbers(4, 5))

A function can only return once, thus, if you need to return multiple values, you can use a list.

def double(a, b): return [a*2, b*2] X = double(6, 9) print(x)

You can call the same function with different arguments.

def exclamation (word): print(word"") exclamation ( "spam" ) exclamation ("eggs ") exclamation ( "python") Arguments are used to pass information to the function. This allows us to reuse the function logic for different values.

So once you've defined a function, you can call it multiple times in your code.

def hello(): print("Hello world! ") hello() hello() hello() Note, that we call a function using its name and the parentheses.

You can use the returned value in your code, for example, an if statement:

def max(x, y): if x >=y: return x else: return y if(max(6, 4) > 10): print(Yes ") else: print("Nope ")

Just like with if statements, the code block within every function starts with a colon (:) and is indented.

def my_func(): print("spam") print("spam") print("spam")

Even better, you can define functions with more than one argument; separate them with commas. Like this:

def print_sum_twice (x, y): print(x y) print(x + y) print_sum_twice(5, 8)

Now we can use our function and assign the result to a variable:

def sum(x, y): y): return x+y res = sum(42, 7) print(res) Returning is useful when you don't need to print the result of the function, but need to use it in your code. For example, a bank account's withdraw() function could return the remaining balance of the account.

The function needs to be defined before it can be called. Calling a function before its definition will cause an error

hello() def hello() : print("Hello world ! ")

index() finds the first occurrence of a list item and returns its index.

letters = ['p', 'q', 'r', 's print(letters . index('r')) print(letters . index'p*)) print(letters . index('q')) p 'p', 'u'] An error is returned in case the specified item is not found in the list.

Using [::-1] as a slice is a common and idiomatic way to reverse a list.

nums [5, 42, 7, 1, 0] res nums [: :-1]1 print(res)

There are many built-in functions in Python. To jog your memory, here are some examples that you've already seen:

print("Hello world!") range(2, 20) str(12) range(10, 20, 3)

lower() and upper() change the case of a string to lowercase and uppercase.

print("This is a sentence. ".upperO) print("AN ALL CAPS SENTENCE". lower())

You call the function by using its name, followed by parentheses, which enclose the arguments. For example, we call the print function with a string argument to generate output:

print("some text")

Just like with ranges, your list slices can include a third number, representing the step, to include only alternate values in the slice. Like this:

squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(squares [ : :21) print (squares [2 :8:3])

If the first number in a slice is omitted, it's taken to be the start of the list.

squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(squares [ :7])

If the second number is omitted, it's taken to be the end.

squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(squares [7 : 1)

Negative values can also be used in list slicing (as well as normal list indexing). Which means that when negative values are used for the first and second values in a slice (or a normal index), they count from the end of the list. Like this:

squares = [e, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(squares [1 : -1]) Result: >>> [1, 4, 9, 16, 25, 36, 49, 64] >>> If a negative value is used for the step, the slice will be done backwards.

split() is the opposite of join(). It turns a string with a certain separator into a list. For example, let's split a sentence into words:

str = "some text goes here" x = str.split(' *) print(x)

The result of join() is a:

string

insert() inserts a new item at the given position in the list:

words = ["Python", "fun"] words.insert (1, "is") print (words) The first argument is the position index, while the second parameter is the item to insert at that position.

join() joins a list of strings with another string as a separator. For example:

x ".join(["spam", "eggs, "ham" 1) print(x) #prints "spam, eggs, ham"

Can a docstring contain multiple lines of text?

yes


Kaugnay na mga set ng pag-aaral

Torts - Invasion of Right to Privacy

View Set

Genetics Final Exam Homework Review

View Set

US History Final Chapter 20, Emergence of Urban America

View Set

The Hero's Journey- An Archetypal Story

View Set

Series 65 Knopman Marks Practice Questions

View Set

CHAPTER 4 Social Entrepreneurship and the Global Environment for Entrepreneurship

View Set