a=7
b=4
print('a > b is',a>b)
print('a < b is',a<b)
print('a == b is',a==b)
print('a != b is',a!=b)
print('a >= b is',a>=b)
print('a <= b is',a<=b)
#Output
a > b is True
a < b is False
a == b is False
a != b is True
a >= b is True
a <= b is False
# Example using bitwise operators
a=7
b=4
# Result: a and b is 4
print('a and b is',a and b)
# Result: a or b is 7
print('a or b is',a or b)
# Result: not a is False
print('not a is',not a)
#Output
a and b is 4
a or b is 7
not a is False
# Example using 'in' operator
list1=[1,2,3,4,5]
list2=[6,7,8,9]
for item in list1:
if item in list2:
print("overlapping")
else:
print("not overlapping")
# Output: not overlapping
# Example of 'is' identity operator
x = 5
if (type(x) is int):
print ("true")
else:
print ("false")
# Output: true
| Operator | Example | Similar |
|---|---|---|
| = | x = 8 | x = 8 |
| += | x += 8 | x = x + 8 |
| -= | x -= 8 | x = x - 8 |
| *= | x *= 8 | x = x * 8 |
| /= | x /= 8 | x = x/8 |
| %= | x %= 8 | x = x%8 |
| **= | x **= 8 | x = x**8 |
| &= | x &= 8 | x = x & 8 |
| |= | x |= 8 | x = x|8 |
| ^= | x ^= 8 | x = x ^ 8 |
| <<= | x <<= 8 | x = x << 8 |
| >>= | x >>= 8 | x = x >> 8 |
print "hello" # print statement only valid in Py2
print 1+1
print 'Hello' + 'world'
print('Hello' , 'World') # print function valid in both Py2 and Py3 (use this)
# Printing without newline, still has space seperating though
print "First statement ",
print "%s" % ("Second statement"),
print "Third statement"
# Output: 'First statement Second statement Third statement'
print("hello")
print(1+1)
print('Hello' + 'World')
print('Hello' , 'World')
# Printing without newline
print("First statement ", end=" ")
print("{}".format("Second statement"), end="")
print("Third statement")
# Output: 'First statement Second statementThird statement'
% formatting follows C style and is being phased out. It is highly recommend to use .format()… but have practice with both!
# Basic Positional Formatting
print "%s World!" % "Hello"
'Hello World!'
# Basic Positional Formatting
print "%s %s!" % ("Hello", "World")
'Hello World!'
# Padding 10 left
print '%10s' % ('test',)
' test'
# Negative Padding (10 right)
print '%-10s %s' % ('test', 'next word')
'test next word'
# Truncating Long Strings
print '%.5s' % ('what in the world',)
'what '
# Truncating and padding
print '%10.5s' % ('what in the world',)
' what'
# Numbers
print '%d' % (50,)
50
# Floats
print '%f' % (3.123513423532432)
3.123513
# Padding numbers
print '%4d' % (50,)
50
# Padding Floating Points/precision
print '%06.2f' % (3.141592653589793,)
003.14
# Name Placeholders
things = {'car': 'BMW E30', 'motorcycle': 'Harley FXDX'}
print 'My fav car %(car)s and motorcycle %(motorcycle)s' % things
'My fav car BMW E30 and motorcycle Harley FXDX'
Format strings contain "replacement fields" surrounded by curly braces {}. Anything that is not contained in braces is considered literal text.
"The sum of 4 + 5 is {}".format(4 + 5)
# Basic Positional Formatting
print('{} {}!'.format('Hello', 'World'))
'Hello World!'
# Basic Positional Formatting
print("{!s} {!s}".format("Hello", "World"))
'Hello World!'
# Actual Positional Formatting
# EXCLUSIVE
print('{1} {0}!'.format('World', 'Hello'))
'Hello World!'
# Padding 10 left
print('{:>10}'.format('test'))
' test'
# Negative Padding 10 right
print('{:<10}'.format('test'))
'test '
# Changing Padding Character
# EXCLUSIVE
print('{:_>10}'.format('test'))
'______test'
# Center Align
# EXCLUSIVE
print('{:_^10}'.format('test'))
'___test___'
# Truncating Long Strings
print('{:.5}'.format('what in the world'))
'what '
# Truncating and padding
print('{:10.5}'.format('what in the world'))
' what'
# Numbers
print('{:d}'.format(50))
50
# Floats
print('{:f}'.format(3.123513423532432))
3.123513
# Padding numbers
print('{:4d}'.format(50))
50
# Padding Floating Points/precision
print('{:06.2f}'.format(3.141592653589793))
003.14
# Name Placeholders
things = {'car': 'BMW E30', 'motorcycle': 'Harley FXDX'}
print('My favorite car is a {car} and motorcycle {motorcycle}'.format(**things))
'My fav car BMW E30 and motorcycle Harley FXDX'
# Date and Time
# EXCLUSIVE
from datetime import datetime
print('{:%Y-%m-%d %H:%M}'.format(datetime(2017, 10, 17, 10, 45)))
2017-10-17 10:45
#Variables
nBalloons = 8
print("Sammy has {} balloons today!".format(nBalloons))
Output
Sammy has 8 balloons today!
sammy = "Sammy has {} balloons today!"
nBalloons = 8
print(sammy.format(nBalloons))
Output
Sammy has 8 balloons today!
| Format Symbol | Conversion |
|---|---|
| %c | character |
| %s | string conversion via str() prior to formatting |
| %i | signed decimal integer |
| %d | signed decimal integer |
| %u | unsigned decimal integer |
| %o | octal integer |
| %x | hexadecimal integer (lowercase letters) |
| %e | exponent notation |
| %f | floating point real number |
Python offers a robust and insanely easy to use toolset to interact with files.
First, a file must be opened before it can be modified... this includes creating new files. We use the open() function to achieve this. The first argument passed is the file name; rather it exists or not. The second argument is the operation in which we would like to perform. ex read, write, overwrite, etc.
file = open("file.txt", 'r')
Once the file is open, we can begin reading, adding or modifying the file's contents. Below are some of the methods to make that happen.
f = open('file_name', 'a')
data = f.read()
print data
file.close()
a = 100
if a > 100:
print('a is greater than 100')
elif a < 100:
print('a is less than 100')
else:
print('a is equal to 100')
a is equal to 100
What is the output?
for a in range(51):
if a == 0:
print("{} you can't divide by zero!".format(a))
elif a % 10 == 0:
print ('{} can be divided by 10!!!'.format(a))
elif a % 2 == 0:
print('{} is even!'.format(a))
else:
print('{} is odd!'.format(a))
While loops, just like C and C++, loop through each iteration until either the condition is met or a break statement is called.
count = 0
while count < 5:
print('count: ' + str(count))
count += 1
count: 0
count: 1
count: 2
count: 3
count: 4
The while-else runs like a regular while loop except for the one iteration when the while loop becomes false. This results in the else statement being executed once!
count = 0
while count <= 4:
print('count: {}'.format(count))
count += 1
else:
print('while loop executed... count is: {}'.format(count))
count: 0
count: 1
count: 2
count: 3
count: 4
while loop executed... count is: 5
When using the while loop, a few factors will make a difference in the output... that could break your program if you don't pay attention. The value of the incrementing var, where the count increment is placed and the comparison operator are the three most common factors. Here are a few things to keep in mind:
char *my_string = "Python";
for (int i = 0; i < strlen(my_string); i++) {
printf(%c\n", my_string[i]);
}
my_string = "Python"
for i in range(len(my_string)):
print(my_string[i])
my_string = "Python"
for letter in my_string:
print(letter)
One way to set up looping for a dictionary
#In python 2 use the method iteritems()
for key, value in dict.iteritems():
pass
#In python 3 the method is now just items()
for key, value in dict.items():
pass
Here is an example of how to do this
x = {'stu1':'James', 'stu2':'Bob', 'stu3':'Rengar'}
for stu_id, name in x.items():
print("{}'s name is {}".format(stu_id, name))
The break statement simply breaks out of the innermost enclosing loop.
for i in range(1, 101):
if i == 10:
print("WE BROKE IT!")
break
print(i)
1
2
3
4
5
6
7
8
9
WE BROKE IT!
The continue statement continues with the next iteration of the loop.
for i in range(1, 100):
if i % 2 == 0:
print("{} is an even number!".format(i))
continue #prevents second print from running
print("{} is an odd number!".format(i))
1 is an odd number!
2 is an even number!
3 is an odd number!
4 is an even number!
5 is an odd number!
6 is an even number!
7 is an odd number!
8 is an even number!
9 is an odd number!
10 is an even number!
11 is an odd number!
12 is an even number!
13 is an odd number!
14 is an even number!
15 is an odd number!
16 is an even number!
17 is an odd number!
18 is an even number!
19 is an odd number!
20 is an even number!
....