Python
Python
Eg.
name = input('Enter your name: ')
print('Hello, ', name)
Variable
Variable names
There are just a couple of rules to follow when naming
your variables.
Variable names can contain letters, numbers, and the
underscore.
Variable names cannot contain spaces.
Variable names cannot start with a number.
Case matters for instance, temp and Temp are
different.
For loops
There are several ways to repeat things in Python, the most
common of which is the for loop.
Ex.
Write a program that generates a random number, x, between 1
and 50, a random number y between 2 and 5, and computes xy
.
If statements
from random import randint
num = randint(1,10)
guess = eval(input('Enter your guess: '))
if guess==num:
print('You got it!')
The comparison operators are ==, >, <, >=, <=, and !=.
That last one is for not equals.
Order of operations In terms of order of operations, and
is done before or
grade = eval(input('Enter your score: '))
if grade>=90:
print('A')
elif grade>=80:
print('B')
elif grade>=70:
print('C')
elif grade>=60:
print('D'):
else:
print('F')
Exercise
Write a program that asks the user to enter a number and prints
out all the divisors of that number.
Counting
Very often we want our programs to count how many times something
happens.
count = 0
for i in range(10):
num = eval(input('Enter a number: '))
if num>10:
count=count+1
print('There are', count, 'numbers greater than 10.')
A program counts how many of the squares from 12 to 100 2
end in a
4.
count = 0
for i in range(1,101):
if (i**2)%10==4:
count = count + 1
print(count)
Strings
Strings are a data type in Python for dealing with text. Python has a
number of powerful features for manipulating strings.
A string is created by enclosing text in quotes. You can use either
single quotes, ', or double quotes, ". A triple-quote can be used for
multi-line strings.
s = 'Hello'
t = "Hello"
m = """This is a long string that is
spread across two lines.""“
num = (int)(input('Enter a number: ')) # to insert number
string = input('Enter a string: ') # to insert string
Length --- len(variable name)
Concatination ------ + operator
Repeatition ----- * operator are used
Example 2 The + operator can be used to build up a
string, piece by piece
s=‘'
for i in range(10):
t = input('Enter a letter: ')
if t=='a' or t=='e' or t=='i' or t=='o' or t=='u':
s=s+t
print(s)
The in operator
The in operator is used to tell if a string contains something. For
example:
if 'a' in string:
print('Your string contains the letter a.')
You can combine in with the not operator to tell if a string does not
contain something:
if ';' not in string:
print('Your string does not contain any semicolons.')
for r in range(10):
for c in range(5):
print(L[r][c], end=" ")
print()
While loops
temp = 0
while temp!=-1000:
temp = eval(input('Enter a temperature (-1000 to quit): '))
print('In Fahrenheit that is', 9/5*temp+32)
for i in range(10):
num = eval(input('Enter number: '))
if num<0:
print('Stopped early')
break
else:
print('User entered all ten values')
from random import randint
secret_num = randint(1,100)
for num_guesses in range(5):
guess = eval(input('Enter your guess (1-100): '))
if guess < secret_num:
print('HIGHER.', 5-num_guesses, 'guesses left.\n')
elif guess > secret_num:
print('LOWER.', 5-num_guesses, 'guesses left.\n')
else:
print('You got it!')
break
else:
print('You lose. The correct number is', secret_num)
Here is an example that tells a person born on
January 1, 1991 how old they are in 2010.
birthday = 'January 1, 1991'
year = int(birthday[-4:])
print('You are', 2021-year, 'years old.')
String formatting
uses the format method of strings.
Formatting integers To format integers, the formatting code is {:d}. Putting a
number in front of the d allows us to right-justify integers.
Here is an example:
print('{:3d}'.format(2))
print('{:3d}'.format(25))
print('{:3d}'.format(138))
2
25
138
To center integers instead of right-justifying, use the ^ character, and to left-justify,
use the < character.
print('{:^5d}'.format(2))
print('{:^5d}'.format(222))
print('{:^5d}'.format(13834))
2
122
13834
Formatting floats To format a floating point number, the formatting
code is {:f}. To only display
the number to two decimal places, use {:.2f}.
Formatting strings To format strings, the formatting code is {:s}.
Here is an example that centers
some text:
print('{:^10s}'.format('Hi'))
print('{:^10s}'.format('there!'))
Hi
there!
To right-justify a string, use the > character:
print('{:>6s}'.format('Hi'))
print('{:>6s}'.format('There'))
Hi
there!
Dictionaries
A dictionary is a more general version of a list
Here is a dictionary of the days in the months of the year:
days = {'January':31, 'February':28, 'March':31, ‘
April':30,’May':31, 'June':30, 'July':31,
'August':31,'September':30, 'October':31,
'November':30, 'December':31}
Output
Enter a word: mouse
The definition is: chased by cats
Functions
Functions are defined with the def statement.
The statement ends with a colon, and the code that is part of
the function is indented below the def statement.
def print_hello():
print('Hello!')
print_hello()
print('1234567')
print_hello()
Arguments
We can pass values to functions. Here is an example:
def print_hello(n):
print('Hello ' * n)
print()
print_hello(3)
print_hello(5)
times = 2
print_hello(times)
Returning values
We can write functions that perform calculations and return a result.
Example 1 Here is a simple function that converts temperatures from Celsius to
Fahrenheit.
def convert(t):
return t*9/5+32
print(convert(20))
Default arguments and keyword arguments
You can specify a default value for an argument.
This makes it optional, and if the caller decides not to use it,
then it takes the default value. Here is an example:
def multiple_print(string, n=1)
print(string * n)
print()
multiple_print('Hello', 5)
multiple_print('Hello')
def fancy_print(text, color='black', background='white',
style='normal', justify='left'):
Object-Oriented Programming
everything is an object
A class is a template for objects. It contains the code for all the
object’s methods.
class Example:
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
e = Example(8, 6)
print(e.add())
Python labraries/ packages
Pandas
Numpy
Scipy
Matplotlib
Seaborn
Scikit learn
Tensorflow
Keras