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

Basic Python Programming Guide

Here are solutions to the exercises: 1. Accept 5 numbers, find median and standard deviation: ```python import statistics nums = [] for i in range(5): nums.append(float(input("Enter number: "))) median = statistics.median(nums) std_dev = statistics.stdev(nums) print("Median:", median) print("Standard Deviation:", std_dev) ``` 2. Accept name and print in uppercase: ```python name = input("Enter name: ") print(name.upper()) ``` 3. Check if number exists in list: ```python nums =
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)
16 views12 pages

Basic Python Programming Guide

Here are solutions to the exercises: 1. Accept 5 numbers, find median and standard deviation: ```python import statistics nums = [] for i in range(5): nums.append(float(input("Enter number: "))) median = statistics.median(nums) std_dev = statistics.stdev(nums) print("Median:", median) print("Standard Deviation:", std_dev) ``` 2. Accept name and print in uppercase: ```python name = input("Enter name: ") print(name.upper()) ``` 3. Check if number exists in list: ```python nums =
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

Basic Python

Quick start

python -V # to check the version of python

python -c ’print ("Hello World")’ # simplest hello world program

ipython # IPython 1.2.0 #-- An enhanced Interactive Python

In [4]:

a=2
b=5
c = a+b
d = a-b
q, r = a/b, a%b # Yes, this is allowed!
# Now, let's print!
print "Hello World!" # We just had to do this, did we not? print "Sum, Differe
nce = ", c, d
print "Quotient and Remainder = ", q, r

Hello World!
Quotient and Remainder = 0 2

What we have learned from the above simple program?

Dynamic Typing We don't declare variables and types in advance. (dynamic typing)

Variables created when first assigned values.

Variables don't exist if not assigned. (strong typing)

Commenting Everything after # is a comment and is ignored. Comment freely

In [5]:

##Tuple unpacking assignments


a,b,c,d,e = 5,5,1,0,7

In [6]:

a,b,c,d,e

Out[6]:
(5, 5, 1, 0, 7)
In [7]:

Out[7]:
5

Integers
In [8]:

8 ** 3 # Exponentiation

Out[8]:

512

In [9]:

23**100 # Auto-upgrade to "LONG INT" Notice the L!

Out[9]:
148861915063630393937915565865597542319871196538013686865769882092
224332785393313521523901432773468042334765921794473108595202225298
76001L

In [10]:

2 / 5, 2%5 # Quotient-Remainder Revisited.

Out[10]:

(0, 2)

Floats

In [11]:

5. * 2, 5*2. # Values upgraded to "higher data type".

Out[11]:
(10.0, 10.0)

In [12]:

5**0.5 # Yes, it works! Square-root.

Out[12]:

2.23606797749979
In [13]:

2. / 4. # No longer a quotient.

Out[13]:
0.5

In [14]:

5 % 4.0, 5 % 4.1 # Remainder, yes!!!

Out[14]:

(1.0, 0.9000000000000004)

In [15]:

a="Hello" ; b=" World"


a,b
a+b
a*3

Out[15]:
'HelloHelloHello'

Math Module

In [16]:

import math as mp

In [17]:

x = 45*[Link]/180.0
[Link](x)

Out[17]:

0.7071067811865475

In [18]:

[Link]( [Link](45) ) # nested functions

Out[18]:

0.7071067811865475
In [19]:

print dir(mp) # Prints all functions associated with Math module.

['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh'


, 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', '
cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs
', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot'
, 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'm
odf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'
, 'trunc']

In [20]:

help([Link])

Help on built-in function sqrt in module math:

sqrt(...)
sqrt(x)

Return the square root of x.

Strings

In [21]:

a = 10000.
a

Out[21]:

10000.0

In [22]:

a = "Tom's Laptop" # notice the '

In [23]:

Out[23]:

"Tom's Laptop"

In [24]:

b = 'Tom said, "This is my laptop."' # notice the "


In [25]:

Out[25]:
'Tom said, "This is my laptop."'

In [26]:

a_alt = 'Tom\'s Laptop' # now you need the escape sequence \

In [27]:

a_alt

Out[27]:

"Tom's Laptop"

In [28]:

b_alt = "Tom said, \"This is my laptop.\"" # again escape sequence.

In [29]:

b_alt

Out[29]:

'Tom said, "This is my laptop."'

In [30]:

long_string = """Hello World!


Tom said, "This is my laptop!" """

In [31]:

long_string

Out[31]:
'Hello World! \nTom said, "This is my laptop!" '

In [32]:

a= "Hello World"
b= "This is my laptop"
print a
print b

Hello World
This is my laptop

String Arithmetic
In [33]:

s1 = "Hello" ; s2 = "World!"

In [34]:

string_sum = s1 + s2
print string_sum

HelloWorld!

In [35]:

string_product = s1*3
print string_product

HelloHelloHello

In [36]:

print s1*3+s2

HelloHelloHelloWorld!

String is a sequence!

In [37]:

a = "Python rocks!"

In [38]:

a[0:6:2], a[1], a[6] # Positions begin from 0 onwards.

Out[38]:
('Pto', 'y', ' ')

In [39]:

a[-1], a[-2], a[-3] # Negative indices - count backwards!

Out[39]:

('!', 's', 'k')

In [40]:

len(a) # Measures length of both sequence/unordered collection s!

Out[40]:
13

Sequences can be sliced!


In [41]:

a[2:6] # elements with indices 2,3,4,5 but not 6

Out[41]:
'thon'

In [42]:

a[8:-2] # indices 8,9 ... upto 2nd last but not including it.

Out[42]:

'ock'

In [43]:

a[:5] # Missing first index, 0 assumed.

Out[43]:
'Pytho'

In [44]:

a[5:] # Missing last index, len(a) assumed.

Out[44]:

'n rocks!'

In [45]:

a[1:6:2],a[1],a[3],a[5] # Indices 1, 3, 5

Out[45]:
('yhn', 'y', 'h', 'n')

In [46]:

a[::2] # beginning to end

Out[46]:

'Pto ok!'

In [47]:

a[::-1] # Reverse slicing!

Out[47]:
'!skcor nohtyP'

String Methods
In [48]:

a = " I am a string, I am an object, I am immutable! "

In [49]:

[Link]()

Out[49]:
' I Am A String, I Am An Object, I Am Immutable! '

In [50]:

[Link](",")

Out[50]:

[' I am a string', ' I am an object', ' I am immutable! ']

In [51]:

[Link]() # Remove trailing and leading whitespaces.

Out[51]:
'I am a string, I am an object, I am immutable!'

In [52]:

a = "0000000this is string example....wow!!!0000000";


print [Link]( '0' )

this is string example....wow!!!


In [53]:

# Modified first program.


a = raw_input("Please enter number 1: ")
b = raw_input("Please enter number 2: ")
c, d = a+b, a-b
q, r = a/b, a*b
print c,d,q,r

Please enter number 1: 1


Please enter number 2: 2

------------------------------------------------------------------
---------
TypeError Traceback (most recent c
all last)
<ipython-input-53-846d8c97a6ee> in <module>()
2 a = raw_input("Please enter number 1: ")
3 b = raw_input("Please enter number 2: ")
----> 4 c, d = a+b, a-b
5 q, r = a/b, a*b
6 print c,d,q,r

TypeError: unsupported operand type(s) for -: 'str' and 'str'

In [54]:

a = float( raw_input("Enter Number 1: ") )


b = float( raw_input("Enter Number 2: ") )
c,d = a+b, a-b
q,r = a*b, a/b
print "Addition = %f, Difference = %f " % (c,d)
print "Division = %f, Quotient = %f" % (q,r)

Enter Number 1: 1
Enter Number 2: 2
Addition = 3.000000, Difference = -1.000000
Division = 2.000000, Quotient = 0.500000

In [55]:

a = float( raw_input("Enter Number 1: ") )


b = float( raw_input("Enter Number 2: ") )
c,d = a+b, a-b
q,r = a*b, a/b
print "Addition = %5.2f, Difference = %5.2f " % (c,d)
print "Division = %5.2f, Quotient = %5.2f" % (q,r)

Enter Number 1: 1
Enter Number 2: 3
Addition = 4.00, Difference = -2.00
Division = 3.00, Quotient = 0.33
In [56]:

gal_name = "NGC 7709"


int_bmagnitude = 13.6

statement1 = "The galaxy %s has an integrated B-band magnitude of %.2f" % (gal


_name, int_bmagnitude)

statement2 = "The galaxy {:s} has an integrated B-band magnitude of {:.2f}".fo


rmat(gal_name, int_bmagnitude)

statement3 = "The galaxy {name:s} has an integrated B-band magnitude of {mag:.


2f}".format(name=gal_name, mag=int_bmagnitude)

In [57]:

print statement1

The galaxy NGC 7709 has an integrated B-band magnitude of 13.60

In [58]:

print statement2

The galaxy NGC 7709 has an integrated B-band magnitude of 13.60

In [59]:

print statement3

The galaxy NGC 7709 has an integrated B-band magnitude of 13.60

In [60]:

print statement1, "\n", statement2, "\n", statement3, "\n"

The galaxy NGC 7709 has an integrated B-band magnitude of 13.60


The galaxy NGC 7709 has an integrated B-band magnitude of 13.60
The galaxy NGC 7709 has an integrated B-band magnitude of 13.60

Click on the link : [Link] ([Link] for find more


information about Python formatting.

Conditionals
In [61]:

num = int( raw_input("Enter number: ") )


if num %2 == 0:
print "%d is even!" % num
else:
print "%d is odd!" % num

Enter number: 5
5 is odd!

Conditions are anything that return True or False.


'==' (equal to)

'!='

'>'

'>='

'<'

'<='

You can combine conditionals using "logical operators"


'and'

'or'

'not'

The Boolean Data Type


In [62]:

a = True; b = False
if a:
print "This comes on screen."
if b:
print "This won't come on screen."

This comes on screen.

Exercise time
1. Write a program to accept 5 numbers and print their median and standard deviation.

1. Write a program which accepts a name from a user and prints the same name with all letters
capitalized. Use iPython to find the correct string method for the same.
2. Create a program which defines a list [1,2,3,4,5,7,8,9,10]. And then it should accept from the
number from the user and check if it exists inside the list. If in the list it should display "Yes,
found it!" or it should display "Sorry, could not find that."
3. Define a function which accepts a number and checks if the number is prime or not. It should
return True if prime else return a False.

Common questions

Powered by AI

Nested functions in Python, especially when using the math module, enable more complex calculations by combining multiple function outputs in a single expression. This enhances code clarity and efficiency. For instance, using 'mp.sin(mp.radians(45))' performs conversion to radians and computes the sine simultaneously, optimizing mathematical computations in one line .

Python’s slicing feature allows easy and efficient extraction of subsequences from strings, lists, and other iterable collections. It simplifies tasks like getting sub-parts, reversing sequences, and skipping elements, replacing more verbose and error-prone loop constructs found in other languages. Slicing provides a simple syntax, e.g., `a[::2]` for skipping every other element, enhancing productivity and reducing potential for bugs .

Escape sequences in Python strings are used to include special characters such as quotes that would otherwise prematurely end a string. For instance, using '\' allows a single quote to be part of a string defined by single quotes, such as '\', to correctly format strings like 'Tom\'s Laptop' or '"This is my laptop."' .

Dynamic typing in Python means that you do not need to declare the data type of a variable when creating it; the type is determined at runtime. Variables are created by assignment, and if they are not assigned, they do not exist—demonstrating strong typing where the data type of an object cannot be ignored. This means Python enforces the rule that operations are only valid between compatible types, despite not requiring explicit declarations of these types at compile time .

Tuple unpacking in Python allows assignment of multiple variables at once by unpacking the values from a tuple or iterable into individual variables. This feature enhances code readability by making multiple assignments more concise and improves flexibility by allowing easy swapping of variable values or parallel assignment from data structures, aiding in better, cleaner code management .

Python enhances user interaction using 'input()' to receive data from users, enabling dynamic program behavior. A common pitfall is failing to account for the input type, as input() returns strings, which can cause errors if not correctly converted before operations expecting numerical types. Proper input validation and conversion, such as converting to 'int' or 'float', are essential to avoid TypeErrors, as demonstrated by errors when performing arithmetic with strings .

A simple Python program to check if a number is even or odd uses conditionals and Boolean logic. One would use 'if num % 2 == 0:', then print 'even', otherwise print 'odd'. This leverages the modulus operator to determine evenness, combined with a conditional statement to branch execution based on the Boolean result of parity testing, demonstrating Python's straightforward approach to decision-making .

Python automatically handles large integers by upgrading them to 'long int' when their size exceeds the typical integer storage capacity. This is demonstrated by Python's ability to compute and return large numbers using exponentiation without explicit conversion by the user, a feature of Python’s dynamic typing system which seamlessly supports large integers .

Python allows string concatenation using the '+' operator and repetition using the '*' operator. For example, combining two strings 's1' and 's2' as 's1 + s2' results in their concatenation, while 's1*3' repeats the string 's1' three times. This flexibility indicates that strings in Python are sequences that allow arithmetic-like operations .

Python raises a TypeError when incompatible types are used in mathematical operations. For example, trying to subtract one string from another using the '-' operator would result in a TypeError because such an operation is not defined for strings, as shown in the error for `a-b` with strings as operands . To manage this, data type conversion or casting is necessary before the operation .

You might also like