Python Basics

The absolute basics:

Strings

print("Goodbye, World!")
x = "string value"
print (x)

Integers

myint = 7
print(myint)

Floats

myfloat = 7.0
print(myfloat)
myfloat = float(7)
print(myfloat)

Examples

one = 1
two = 2
three = one + two
print(three)

hello = "hello"
world = "world"
helloworld = hello + " " + world
print(helloworld)

Further Example

This one with a few conditionals involved

mystring = "hello"
myfloat = 10.0
myint = 20

# testing code
if mystring == "hello":
print("String: %s" % mystring)
if isinstance(myfloat, float) and myfloat == 10.0:
print("Float: %f" % myfloat)
if isinstance(myint, int) and myint == 20:
print("Integer: %d" % myint)

Lists and Iterating

mylist = []
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist[0]) # prints 1
print(mylist[1]) # prints 2
print(mylist[2]) # prints 3

# prints out 1,2,3
for x in mylist:
print(x)

Example

numbers = [1,2,3]
strings = ["hello","world"]
names = ["John", "Eric", "Jessica"]

# write your code here
second_name = names[1]

# this code should write out the filled arrays and the second name in the names list (Eric).
print(numbers)
print(strings)
print(“The second name on the names list is %s” % second_name)

Mathematical Operators and Ordering

Standard bodmas rules apply, and standard mathematic operators are used

x + y x plus y
x – y x minus y
x * y x multiplied y
x / y x divided by y
x ** y x to the power of y

Strings & Formatting

Very C-like 🙂


# This prints out "Hello, John!"
name = "John"
print("Hello, %s!" % name)

# This prints out “John is 23 years old.”
name = “John”
age = 23
print(“%s is %d years old.” % (name, age))

# This prints out “Hello John Doe. Your current balance is $53.44.”
data = (“John”, “Doe”, 53.44)
format_string = “Hello %s %s. Your current balance is $%s.”

print(format_string % data)

Many examples are mashed in here:


s = "Strings are awesome!"
# Length should be 20
print("Length of s = %d" % len(s))

# First occurrence of “a” should be at index 8
print(“The first occurrence of the letter a = %d” % s.index(“a”))

# Number of a’s should be 2
print(“a occurs %d times” % s.count(“a”))

# Slicing the string into bits
print(“The first five characters are ‘%s'” % s[:5]) # Start to 5
print(“The next five characters are ‘%s'” % s[5:10]) # 5 to 10
print(“The thirteenth character is ‘%s'” % s[12]) # Just number 12
print(“The characters with odd index are ‘%s'” %s[1::2]) #(0-based indexing)
print(“The last five characters are ‘%s'” % s[-5:]) # 5th-from-last to end

# Convert everything to uppercase
print(“String in uppercase: %s” % s.upper())

# Convert everything to lowercase
print(“String in lowercase: %s” % s.lower())

# Check how a string starts
if s.startswith(“Str”):
print(“String starts with ‘Str’. Good!”)

# Check how a string ends
if s.endswith(“ome!”):
print(“String ends with ‘ome!’. Good!”)

# Split the string into three separate strings,
# each containing only a word
print(“Split the words of the string: %s” % s.split(” “))

Conditions and Boolean Operators


x = 2
name = "Rick"
age = 23

print(x == 2) # prints out True
print(x == 3) # prints out False
print(x < 3) # prints out True


if name == "John" and age == 23:
print("Your name is John, and you are also 23 years old.")

if name == “John”:
print(“Your name is John”)
else:
print(“Your name is not John”)

if name == “John” or name == “Rick”:
print(“Your name is either John or Rick.”)

x = 2
if x == 2:
print(“x equals two!”)
else:
print(“x does not equal to two.”)

Note: Python uses indentation to define codeblocks as seen in the above examples. Assuming they display properly – which they may not

The In Operator


name = "John"
if name in ["John", "Rick"]:
print("Your name is either John or Rick.")

The Not Operator


print(not False) # Prints out True

Loops

For Loop


primes = [2, 3, 5, 7]
for prime in primes:
print(prime)

# Prints out the numbers 0,1,2,3,4
for x in range(5):
print(x)

# Prints out 3,4,5
for x in range(3, 6):
print(x)

# Prints out 3,5,7
for x in range(3, 8, 2):
print(x)

Clearly the arguments for this are (min, max, step)

While Loop


# Prints out 0,1,2,3,4

count = 0
while count < 5:
print(count)
count += 1 # This is the same as count = count + 1

 

Break and Continue


# Prints out 0,1,2,3,4

count = 0
while True:
# print(count)
count += 1
if count >= 5:
break

Break to exit the loop


# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
# Check if x is even
if x % 2 == 0:
continue
print(x)

Continue to move to the next statement, or codeblock

 

Else inside loops


#Prints out 0,1,2,3,4 and then it prints "count value reached 5"

count=0

while(count<5):
print(count)
count +=1

else:
print(“count value reached %d” %(count))

# Prints out 1,2,3,4
for i in range(1, 10):
if(i%5==0):
break
print(i)
else:
print(“this is not printed because for loop is terminated because of break but not due to fail in condition”)

You can leave a response, or trackback from your own site.

Leave a Reply

Powered by WordPress and ThemeMag