Jump to content

basic python stuff can't figure it out!

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
psycho10

psycho10

    Newbie

  • Members
  • Pip
  • 1 posts
1. Ask the user to input their first name, and then ask the user to input their last name. Create a new string variable by concatenating the first and the last name. Name the string variable UserName. Then display back to the name entered, and the number of characters in their name (include spaces if you like).
2. Create a “while loop” that prints each character of UserName on its own line.
3. Create a “for loop” that prints each character of UserName on its own line. Then print only the first letter of UserName. Then print only the first 3 letters of UserName.

I got # 1 it was easy its 2 and 3 i can't seem to figure out!

every book, and every timei google while and for loops, it gives no examples of anything close to this, it just deals with numbers, and this isn't the case, so any help would be greatly appreciated! I am totally 100% lost...

#2
Somelauw

Somelauw

    Newbie

  • Members
  • PipPip
  • 18 posts
Okay.
Are you familiar with while/forloops (you could study the way it works on numbers)
To get a single character from a string, use string[pos].

#3
CatatonicMan

CatatonicMan

    Newbie

  • Members
  • PipPip
  • 13 posts
Let's see...

I don't exactly like doing the problem, but the code is so simple that it really doesn't matter. Still, ask me questions about anything you are confused about.

Here's an example for Python v2.x:


UserName = 'FirstLast'


#Here's a while loop:

limit = len(UserName)

index = 0

while index < limit:

    print UserName[index]

    index = index + 1 #index += index


#Here is the for loop:

for letter in UserName:

    print letter


#Here is the for loop for the first letter:

for letter in UserName[0]:

    print letter


#and here is the first 3 letters:

for letter in UserName[:3]:

    print letter


Some things to note:

The 'print' statement automatically adds a newline after it prints the output.

Python counts the positions between elements in a sequence, rather than the elements themselves, starting from 0.

Python's 'for' loop iterates over items in a sequence and assigns those items to the loop variable. This is a bit different than loops in other languages.