[go: up one dir, main page]

0% found this document useful (0 votes)
5 views12 pages

Python Basics and Practice Problems on Functions

The document covers the basics of Python programming, including syntax, variables, data types, lists, tuples, functions, and mathematical operations. It provides examples of code snippets demonstrating variable assignments, mathematical operations, and the use of built-in functions. Additionally, it explains how to create custom functions and the importance of comments in code.

Uploaded by

ashuthakur6106
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views12 pages

Python Basics and Practice Problems on Functions

The document covers the basics of Python programming, including syntax, variables, data types, lists, tuples, functions, and mathematical operations. It provides examples of code snippets demonstrating variable assignments, mathematical operations, and the use of built-in functions. Additionally, it explains how to create custom functions and the importance of comments in code.

Uploaded by

ashuthakur6106
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

5/5/25, 5:19 PM Python basics and practice Problems

Python Basics

1 Topics covered
Python Syntax
Variables and data types
Storing lots of data in memory: Lists and Tuples
Functions
Comments in code

In [1]: x = 10
print(x)
y = 'galg'
print(y)

10
galg

What does python syntax look like?

In [2]: salary = 213000


tax_rate = 0.30
salary_after_tax = salary * (1-tax_rate)
print(salary_after_tax)

149100.0

What parts of Python did we use in that code?

In [20]: x = "Hello world"


print(x)

Hello world

2 Variables and data types in python


Variables hold data
For example, this might be a number (e.g. an integer) or a text string
Your computer program uses the data in its operations

In [7]: x = 50
print(x)
y = "noida"
print(y)

50
noida

In [3]: simple_sum = 1 + 5

file:///C:/Users/Lenovo/Downloads/Python basics and practice Problems.html 1/12


5/5/25, 5:19 PM Python basics and practice Problems

print(simple_sum)

In [14]: x_y = 10
print(x_y)

10

In [4]: x = 30
y = 5
print(x*y)

150

2.1 Mathematical operations

You can conduct mathematical operations on variables

Operator Name Description

a + b Addition Sum of a and b

a - b Subtraction Difference of a and b

a * b Multiplication Product of a and b

a / b True division Quotient of a and b

a // b Floor division Quotient of a and b , removing fractional parts

a % b Modulus Integer remainder after division of a by b

a ** b Exponentiation a raised to the power of b

-a Negation The negative of a

Example:

the variable z is product of variable x raised to the power of y

In [5]: x = 25
y = 3
print(x + y) # addition
print(x - y) # subtraction
print(x * y) # multiplication
print(x / y) # true division
print(x // y) # floor divisipon
print(x % y) # modulus
print(x ** y) # exponentiation
print(-x) # negation

file:///C:/Users/Lenovo/Downloads/Python basics and practice Problems.html 2/12


5/5/25, 5:19 PM Python basics and practice Problems

28
22
75
8.333333333333334
8
1
15625
-25

Example:

the variable foo is the negation of variable bar

In [12]: bar = 10
foo = -bar
print(foo)

-10

2.2 Variables Names


Rules:

Variables names can only contain letters, numbers, and _ (underscores)


Always start with a letter, e.g., file_name instead of 2file_name

Tips:

_ is used instead of spaces, e.g., file_name instead of file name


If you include a space or start with numbers then you will get a SyntaxError !

In [11]: lecture_name = 'tom'


print(lecture_name)

tom

2.3 Data type for Variables

Each variable has a data type

In [3]: foo = 1000


bar = 'hello everyone'
print(type(foo))
print(type(bar))
x = -10
y = '10'
print(type(x))
print(type(y))
z = 2.2
print(type(z))

file:///C:/Users/Lenovo/Downloads/Python basics and practice Problems.html 3/12


5/5/25, 5:19 PM Python basics and practice Problems

<class 'int'>
<class 'str'>
<class 'int'>
<class 'str'>
<class 'float'>

In [25]: x = True
y = False
spam = 3.142
eggs = 10000000

print(type(x))
print(type(y))
print(type(spam))
print(type(eggs))

<class 'bool'>
<class 'bool'>
<class 'float'>
<class 'int'>

3 Lists and Tuples


Python uses Lists and Tuples to store data
Lists are more felxible, and can hold any type of data
Tuples hold one type of data

3.1 Operations of Lists

Using Lists is a simple and flexible way to store variables and data
Using [] and , to define a list

In [1]: foo = [1, 2, 9, 0, 5]


print(foo)

[1, 2, 9, 0, 5]

A list can hold different types of variable

In [11]: list_1 = ['spam', 5, 82.96, True]


print(list_1)
bar = ['spam', [2, 'eggs'], 82.96, True]
print(bar)

['spam', 5, 82.96, True]


['spam', [2, 'eggs'], 82.96, True]

A list has a length which is calculated by len


len counts the number of the items of the list

In [1]: bar = ['spam', [2, 'eggs'], 82.96, True, 22,True, [2, 'true']]
length_of_bar = len(bar)

file:///C:/Users/Lenovo/Downloads/Python basics and practice Problems.html 4/12


5/5/25, 5:19 PM Python basics and practice Problems

print(length_of_bar)

Every element stored within a List has a numbered index


Indices start from zero (don't forget)

In [3]: foo = [1, 5, 6, 2, 8, 9, 10, 20, 23, 1, 5]


print(foo[3]) # access an item
print(foo[7]) # access an item

foo[2] = 10 # assign an item


print(foo)

2
20
[1, 5, 10, 2, 8, 9, 10, 20, 23, 1, 5]

3.2 Inserting and removing items


New list items:

can be appended to the end of a List


or inserted at a specified index

Existing list items:

can be removed from a specified index


or replaced by value

In [16]: foo = []

foo.append('ttk') # append an entry at the end of the list


print(foo)

foo.append('swan') # append an entry at the end of the list


print(foo)

foo.insert(1, 'bar') # insert an entry at a specified index


print(foo)

del foo[2] # Remove a specific index (and the value on this index)
print(foo)

foo.remove('ttk') #Remove a specific value, foo[0]


print(foo)

['ttk']
['ttk', 'swan']
['ttk', 'bar', 'swan']
['ttk', 'bar']
['bar']

3.3 Operations of Tuples

file:///C:/Users/Lenovo/Downloads/Python basics and practice Problems.html 5/12


5/5/25, 5:19 PM Python basics and practice Problems

Using () and , to define a tuple


A tuple is similar to a list with one key difference
A list is mutable whereas a tuple is immutable

In [3]: foo = [1, 2, 7, 8, 3]


bar = (1, 2, 7, 8, 3)

print(foo[1])
print(bar[2])

2
7

In [18]: foo[1] = 4
print(foo)

bar[2] = 7
print(bar)

[4, 4, 7, 8, 3]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-18-73bfa8f6bd90> in <module>
2 print(foo)
3
----> 4 bar[2] = 7
5 print(bar)

TypeError: 'tuple' object does not support item assignment

4 Functions
We have already seen some Python built-in functions: print() , type() and
len()
Python has lots of them
If you are not sure how they work you can use the help() function!

In [3]: help(print)

Help on built-in function print in module builtins:

print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.


Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

In [18]: help(len)

file:///C:/Users/Lenovo/Downloads/Python basics and practice Problems.html 6/12


5/5/25, 5:19 PM Python basics and practice Problems

Help on built-in function len in module builtins:

len(obj, /)
Return the number of items in a container.

4.1 Importing functions from Python modules

Functions are stored within modules (or packages)


Use the import statement to access the modules you need

Let's generate a random integer between 1 and 100

We need a function from the random module

In [8]: import random


u = random.randint(150, 200)
print(u)
# print('Our winner is', u)

import random as rnd


u = rnd.randint(1,100)
print(' My random integer is', u)

178
My random integer is 78

We can also import specific functions from modules

In [17]: from random import randint, gauss

u1 = randint(1, 100)
u2 = gauss(0, 1)

print('I sampled a random int', u1, 'from 1 to 100\n\


and a normally distributed value', u2)

I sampled a random int 6 from 1 to 100


and a normally distributed value 0.7003456708089183

4.2 Custom Functions

You can also code your own bespoke functions


A function is a reusable block of code that has a single responsibility
That means you function should do one thing only

4.2.1 Motivation
You have been asked to convert degrees celsius to fahrenheit conversions

In [1]: deg_celsius = 40
deg_fahrenheit = 9.0/5.0 * deg_celsius + 32

file:///C:/Users/Lenovo/Downloads/Python basics and practice Problems.html 7/12


5/5/25, 5:19 PM Python basics and practice Problems

print(deg_fahrenheit)

deg_celsius = 10
deg_fahrenheit = 9.0/5.0 * deg_celsius + 32
print(deg_fahrenheit)

104.0
50.0

A reusable function would come in very handy here!

In [2]: def celsius_to_fahrenheit (deg_celsius):


deg_fahrenheit = 9.0/5.0 * deg_celsius + 32
return deg_fahrenheit

In [6]: deg_celsius = 0
deg_fahrenheit = celsius_to_fahrenheit(deg_celsius)
print(deg_fahrenheit)
# print(deg_celsius,'C =',deg_fahrenheit,'F')

32.0

In [11]: def rupees_to_gbp (rupees):


gbp = rupees*1/120
return gbp
rupees = 500
gbp= rupees_to_gbp (rupees)
print(gbp)

4.166666666666667

4.2.2 Rules for writing a function


def function_name(input1,input2,...):
line1
line2
...
lineN
return value1, value2,...

function_name only contains letters, numbers, and _, always starts with a letter
Lines follow : must be indented by 4 spaces (use tab key or 4 spaces)

In [24]: def celsius_to_fahrenheit(deg_celsius):


deg_fahrenheit = 9.0/5.0 * deg_celsius + 32
return deg_fahrenheit

File "<ipython-input-24-7ec59b39a4f5>", line 2


deg_fahrenheit = 9.0/5.0 * deg_celsius + 32
^
IndentationError: expected an indented block

If a function returns a value you can pass it to another function

In [9]: def add(num1, num2, num3):


sum3nums = num1 + num2 + num3

file:///C:/Users/Lenovo/Downloads/Python basics and practice Problems.html 8/12


5/5/25, 5:19 PM Python basics and practice Problems

return sum3nums

def square(num):
num2 = num ** 2
return num2

In [10]: result = square(add(1, 3, 5))


print(result)

81

4.2.3 Functions can return multiple values


In [13]: def list_info(data):
list_sum = sum(data)
list_len = len(data)
list_mean = list_sum / list_len
return list_sum, list_len, list_mean

data_0 = [1, 2, 3, 4, 5]
results = list_info(data_0)
print(results)
#print("results = {0} has type {1}".format(results, type(results)))

#data_sum, data_length, data_mean = list_info(data_0)


#print('Seperate variables: data_sum={0}, data_length={1}, data_mean={2}'.\
#format(data_sum, data_length,data_mean))

(15, 5, 3.0)

4.2.4 Comments in code


In [28]: def celsius_to_fahrenheit(deg_celsius):
'''
Converts degrees celsius to degrees fahrenheit
Keyword arguments:
deg_celsius -- a float temperature in degree celsius, e.g., 18.5
'''
deg_fahrenheit = 9.0/5.0 * deg_celsius + 32
return deg_fahrenheit

In [29]: help(celsius_to_fahrenheit)

Help on function celsius_to_fahrenheit in module __main__:

celsius_to_fahrenheit(deg_celsius)
Converts degrees celcius to degrees fahrenheit
Keyword arguments:
deg_celsius -- a float temperature in degree celsius, e.g., 18.5

Using hashtags # is another way to add comments to code


Useful to clarify "complex" code and aid your memory
But won't be picked up by help()

In [1]: from math import pi # import the constant pi from math module

file:///C:/Users/Lenovo/Downloads/Python basics and practice Problems.html 9/12


5/5/25, 5:19 PM Python basics and practice Problems

def area_of_circle(radius):
# area of a circle with the radius
area = pi * radius ** 2
return area
radius = 4
area = area_of_circle(radius)
print(area)

50.26548245743669

In [31]: help(area_of_circle)

Help on function area_of_circle in module __main__:

area_of_circle(radius)

In [3]: help(print)

Help on built-in function print in module builtins:

print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.


Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

In [10]: number = 100


if number < 50:
print("Number < 50")
elif number < 75:
print("50 <= number < 75")
else:
print("Number >= 75")

Number >= 75

In [1]: x = '1' + '1'


print(x)

11

In [2]: u = '1 + 1'


print(u)

1 + 1

In [3]: y = '1' + 1
print(y)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-4b1149ab9b70> in <module>
----> 1 y = '1' + 1
2 print(y)

TypeError: can only concatenate str (not "int") to str

file:///C:/Users/Lenovo/Downloads/Python basics and practice Problems.html 10/12


5/5/25, 5:19 PM Python basics and practice Problems

In [4]: p = 1 + 1
print(p)

In [1]: # Python code to merge dict using update() method


def Merge(dict1, dict2):
return(dict2.update(dict1))

# Driver code
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}

# This returns None


print(Merge(dict1, dict2))

# changes made in dict2


print(dict2)

None
{'d': 6, 'c': 4, 'a': 10, 'b': 8}

In [3]: # some more functions


def is_prime(n):
if n in [2, 3]:
return True
if (n == 1) or (n % 2 == 0):
return False
r = 3
while r * r <= n:
if n % r == 0:
return False
r += 2
return True
print(is_prime(11), is_prime(10))

True False

In [4]: # Python program to find the largest number among the three input numbers

# change the values of num1, num2 and num3


# for a different result
num1 = 10
num2 = 14
num3 = 12

# uncomment following lines to take three numbers from user


#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number is", largest)

The largest number is 14

file:///C:/Users/Lenovo/Downloads/Python basics and practice Problems.html 11/12


5/5/25, 5:19 PM Python basics and practice Problems

In [ ]:

file:///C:/Users/Lenovo/Downloads/Python basics and practice Problems.html 12/12

You might also like