Skip to content

Instantly share code, notes, and snippets.

@prodeveloper
Last active February 21, 2017 06:20
Show Gist options
  • Select an option

  • Save prodeveloper/847de2609f8941c32db76432d58aca86 to your computer and use it in GitHub Desktop.

Select an option

Save prodeveloper/847de2609f8941c32db76432d58aca86 to your computer and use it in GitHub Desktop.
Working with dynamic information

In previous entries we have been mostly manipulating strings and numbers. The numbers have had to be hard set inside the file.

eg

area = 5 * 3
print(area)

This is obviously useful for learning, but in real world programming. You must admit input from the users.

In this entry we will be looking at just that.

##Step 1

Create a new file called areas.py

Inside this file. Type in the following

print("We are about to calculate the area of a rectangle")
base = input("What is the base?:")
height = input ("What is the height?:")
area =  base * height
print ("The area of the rectangle is {}".format(area))

Save the file and run the code.

As you may remember you run the code from the bash command as

python3 area.py

The script will ask for the missing values and then compute the area.

The key word here being input

Assignment:

  • Create a similar script that computes area of a triangle
  • A circle

##Step 2

Everything in python is an object. format() is a method in a python string object. By using it you can customize a string so as to be able to create a dynamic output.

Lets take a look at an examp;e.

Create a new file called my_template.py

Inside the file type out the following code.

template_str = "My name is {} and I am {} years old. I am currently studying {}"
name = input("What is your name?:")
age = input("What is your age?:")
unit = input("What are you studying:")

print (template_str.format(name,age,unit))

What do you see when you run the code?

In the script above, we were able to specify a general narrative and then ask the user of the script to give us this information.

##Assignment:

  • Create a template for welcoming students. The script should take in a first name, last name and print out a message such as. "Congratulations Ms Jane Wairimu, you have been admitted to Akirachix". Remember the script must take in information from the users.

##References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment